summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--browser/components/newtab/.eslintrc.js211
-rw-r--r--browser/components/newtab/.nvmrc1
-rw-r--r--browser/components/newtab/AboutNewTabService.jsm523
-rw-r--r--browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm339
-rw-r--r--browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm266
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js2321
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.css1644
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.html49
-rw-r--r--browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm707
-rw-r--r--browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm242
-rw-r--r--browser/components/newtab/actors/ASRouterChild.sys.mjs111
-rw-r--r--browser/components/newtab/actors/ASRouterParent.sys.mjs103
-rw-r--r--browser/components/newtab/bin/render-activity-stream-html.js146
-rw-r--r--browser/components/newtab/bin/try-runner.js193
-rw-r--r--browser/components/newtab/bin/vendor.js38
-rw-r--r--browser/components/newtab/common/Actions.sys.mjs459
-rw-r--r--browser/components/newtab/common/ActorConstants.sys.mjs47
-rw-r--r--browser/components/newtab/common/Dedupe.sys.mjs36
-rw-r--r--browser/components/newtab/common/Reducers.sys.mjs864
-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.jsx140
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss1676
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/AdditionalCTA.jsx30
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/CTAParagraph.jsx45
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/EmbeddedMigrationWizard.jsx38
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/HelpText.jsx49
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/HeroImage.jsx24
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/LanguageSwitcher.jsx294
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MRColorways.jsx198
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.jsx108
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MobileDownloads.jsx71
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MultiSelect.jsx52
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx468
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MultiStageProtonScreen.jsx472
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/OnboardingVideo.jsx34
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx105
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/Themes.jsx51
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/Zap.jsx60
-rw-r--r--browser/components/newtab/content-src/activity-stream.jsx57
-rw-r--r--browser/components/newtab/content-src/asrouter/README.md34
-rw-r--r--browser/components/newtab/content-src/asrouter/asrouter-content.jsx346
-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.scss51
-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.scss103
-rw-r--r--browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx86
-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.md63
-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/first-run.md68
-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.md986
-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/BackgroundTaskMessagingExperiment.schema.json312
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/FxMSCommon.schema.json128
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/MessagingExperiment.schema.json1640
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/corpus/ReachExperiments.messages.json15
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/extract-test-corpus.js65
-rwxr-xr-xbrowser/components/newtab/content-src/asrouter/schemas/make-schemas.py475
-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.json64
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json67
-rw-r--r--browser/components/newtab/content-src/asrouter/template-utils.js22
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json66
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json320
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json89
-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.json171
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss55
-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.json196
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.js32
-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.json186
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ProtectionsPanelMessage.schema.json62
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/Spotlight.schema.json66
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json45
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json47
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json73
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/PBNewtab/NewtabPromoMessage.schema.json153
-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.json243
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js39
-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.json114
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss190
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx222
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json159
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss131
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json167
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx408
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json235
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/_SubmitFormSnippet.scss176
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/ToastNotification/ToastNotification.schema.json85
-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.jsx1967
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss280
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/CopyButton.jsx31
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/SimpleHashRouter.jsx35
-rw-r--r--browser/components/newtab/content-src/components/Base/Base.jsx273
-rw-r--r--browser/components/newtab/content-src/components/Base/_Base.scss143
-rw-r--r--browser/components/newtab/content-src/components/Card/Card.jsx362
-rw-r--r--browser/components/newtab/content-src/components/Card/_Card.scss331
-rw-r--r--browser/components/newtab/content-src/components/Card/types.js30
-rw-r--r--browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx116
-rw-r--r--browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss106
-rw-r--r--browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx177
-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.jsx176
-rw-r--r--browser/components/newtab/content-src/components/ContextMenu/ContextMenuButton.jsx72
-rw-r--r--browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss57
-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.jsx308
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx87
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss311
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx384
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss67
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx536
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss355
-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.scss38
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx491
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss251
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx118
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss81
-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.scss47
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx100
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss83
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx263
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss48
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx70
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss28
-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.scss37
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx72
-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.jsx168
-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.scss92
-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.scss45
-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/Navigation/Navigation.jsx112
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss180
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink.jsx20
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/_PrivacyLink.scss10
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx65
-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.scss18
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss77
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget.jsx125
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/_TopicsWidget.scss88
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx250
-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.jsx110
-rw-r--r--browser/components/newtab/content-src/components/MoreRecommendations/MoreRecommendations.jsx21
-rw-r--r--browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss24
-rw-r--r--browser/components/newtab/content-src/components/PocketLoggedInCta/PocketLoggedInCta.jsx42
-rw-r--r--browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss42
-rw-r--r--browser/components/newtab/content-src/components/Search/Search.jsx223
-rw-r--r--browser/components/newtab/content-src/components/Search/_Search.scss412
-rw-r--r--browser/components/newtab/content-src/components/Sections/Sections.jsx378
-rw-r--r--browser/components/newtab/content-src/components/Sections/_Sections.scss123
-rw-r--r--browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx192
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSite.jsx873
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSiteForm.jsx323
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSiteFormInput.jsx111
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSiteImpressionWrapper.jsx149
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSites.jsx213
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js39
-rw-r--r--browser/components/newtab/content-src/components/TopSites/_TopSites.scss628
-rw-r--r--browser/components/newtab/content-src/components/Topics/Topics.jsx33
-rw-r--r--browser/components/newtab/content-src/components/Topics/_Topics.scss24
-rw-r--r--browser/components/newtab/content-src/lib/aboutwelcome-utils.js119
-rw-r--r--browser/components/newtab/content-src/lib/constants.js38
-rw-r--r--browser/components/newtab/content-src/lib/detect-user-session-start.js82
-rw-r--r--browser/components/newtab/content-src/lib/init-store.js175
-rw-r--r--browser/components/newtab/content-src/lib/link-menu-options.js292
-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/selectLayoutRender.js255
-rw-r--r--browser/components/newtab/content-src/styles/_activity-stream.scss177
-rw-r--r--browser/components/newtab/content-src/styles/_feature-callout-theme.scss56
-rw-r--r--browser/components/newtab/content-src/styles/_feature-callout.scss314
-rw-r--r--browser/components/newtab/content-src/styles/_icons.scss211
-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.scss99
-rw-r--r--browser/components/newtab/content-src/styles/_variables.scss217
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-linux.scss11
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-mac.scss16
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-windows.scss11
-rw-r--r--browser/components/newtab/css/activity-stream-linux.css4812
-rw-r--r--browser/components/newtab/css/activity-stream-mac.css4816
-rw-r--r--browser/components/newtab/css/activity-stream-windows.css4812
-rw-r--r--browser/components/newtab/data/content/abouthomecache/page.html.template44
-rw-r--r--browser/components/newtab/data/content/abouthomecache/script.js.template19
-rw-r--r--browser/components/newtab/data/content/activity-stream.bundle.js15290
-rw-r--r--browser/components/newtab/data/content/assets/confetti.svg55
-rw-r--r--browser/components/newtab/data/content/assets/default.svg6
-rw-r--r--browser/components/newtab/data/content/assets/device-migration.svg36
-rw-r--r--browser/components/newtab/data/content/assets/firefox.svg168
-rw-r--r--browser/components/newtab/data/content/assets/glyph-cfr-feature-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-20.svg8
-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-pin-16.svg6
-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-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/heart.webpbin0 -> 100396 bytes
-rw-r--r--browser/components/newtab/data/content/assets/icon-removed-bookmark.svg4
-rw-r--r--browser/components/newtab/data/content/assets/long-zap.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mobile-download-qr-existing-user-cn.svg5
-rw-r--r--browser/components/newtab/data/content/assets/mobile-download-qr-existing-user.svg7
-rw-r--r--browser/components/newtab/data/content/assets/mobile-download-qr-new-user-cn.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mobile-download-qr-new-user.svg7
-rw-r--r--browser/components/newtab/data/content/assets/mr-colorways.avifbin0 -> 63824 bytes
-rw-r--r--browser/components/newtab/data/content/assets/mr-gratitude.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-import.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-mobilecrosspromo.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-pinprivate.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-pintaskbar.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-privacysegmentation.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-rtamo-background-image.svg4
-rw-r--r--browser/components/newtab/data/content/assets/mr-settodefault.svg4
-rw-r--r--browser/components/newtab/data/content/assets/noodle-C.svg6
-rw-r--r--browser/components/newtab/data/content/assets/noodle-outline-L.svg13
-rw-r--r--browser/components/newtab/data/content/assets/noodle-solid-L.svg6
-rw-r--r--browser/components/newtab/data/content/assets/person-typing.svg4
-rw-r--r--browser/components/newtab/data/content/assets/pocket-onboarding.avifbin0 -> 7462 bytes
-rw-r--r--browser/components/newtab/data/content/assets/pocket-onboarding@2x.avifbin0 -> 18590 bytes
-rw-r--r--browser/components/newtab/data/content/assets/pocket-swoosh.svg11
-rw-r--r--browser/components/newtab/data/content/assets/remote/mountain.svg12
-rw-r--r--browser/components/newtab/data/content/assets/remote/umbrella.pngbin0 -> 4292 bytes
-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/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 -> 4286 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 -> 2799 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 -> 1338 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/yandex-ru.pngbin0 -> 1368 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.svg106
-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.svg12
-rw-r--r--browser/components/newtab/data/content/tippytop/images/ebay@2x.pngbin0 -> 5361 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 -> 6516 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/yandex-ru@2x.pngbin0 -> 6638 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.rst110
-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.md360
-rw-r--r--browser/components/newtab/docs/v2-system-addon/data_events.md1417
-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.md278
-rw-r--r--browser/components/newtab/docs/v2-system-addon/remote_cfr.md82
-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.mn46
-rw-r--r--browser/components/newtab/karma.mc.config.js346
-rw-r--r--browser/components/newtab/lib/ASRouter.jsm2101
-rw-r--r--browser/components/newtab/lib/ASRouterDefaultConfig.jsm65
-rw-r--r--browser/components/newtab/lib/ASRouterNewTabHook.sys.mjs117
-rw-r--r--browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm179
-rw-r--r--browser/components/newtab/lib/ASRouterPreferences.jsm259
-rw-r--r--browser/components/newtab/lib/ASRouterTargeting.jsm1225
-rw-r--r--browser/components/newtab/lib/ASRouterTriggerListeners.jsm1087
-rw-r--r--browser/components/newtab/lib/AWScreenUtils.jsm79
-rw-r--r--browser/components/newtab/lib/AboutPreferences.jsm312
-rw-r--r--browser/components/newtab/lib/ActivityStream.jsm758
-rw-r--r--browser/components/newtab/lib/ActivityStreamMessageChannel.jsm332
-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/CFRMessageProvider.sys.mjs821
-rw-r--r--browser/components/newtab/lib/CFRPageActions.jsm1049
-rw-r--r--browser/components/newtab/lib/DefaultSites.sys.mjs46
-rw-r--r--browser/components/newtab/lib/DiscoveryStreamFeed.jsm2427
-rw-r--r--browser/components/newtab/lib/DownloadsManager.jsm191
-rw-r--r--browser/components/newtab/lib/FaviconFeed.jsm197
-rw-r--r--browser/components/newtab/lib/FeatureCalloutMessages.sys.mjs648
-rw-r--r--browser/components/newtab/lib/FilterAdult.jsm3036
-rw-r--r--browser/components/newtab/lib/HighlightsFeed.jsm350
-rw-r--r--browser/components/newtab/lib/InfoBar.jsm172
-rw-r--r--browser/components/newtab/lib/LinksCache.sys.mjs133
-rw-r--r--browser/components/newtab/lib/MomentsPageHub.jsm174
-rw-r--r--browser/components/newtab/lib/NewTabInit.jsm57
-rw-r--r--browser/components/newtab/lib/OnboardingMessageProvider.jsm1276
-rw-r--r--browser/components/newtab/lib/PageEventManager.sys.mjs94
-rw-r--r--browser/components/newtab/lib/PanelTestProvider.sys.mjs626
-rw-r--r--browser/components/newtab/lib/PersistentCache.sys.mjs92
-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.jsm282
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.js44
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm311
-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.jsm566
-rw-r--r--browser/components/newtab/lib/PrefsFeed.jsm280
-rw-r--r--browser/components/newtab/lib/RecommendationProvider.jsm132
-rw-r--r--browser/components/newtab/lib/RemoteL10n.sys.mjs249
-rw-r--r--browser/components/newtab/lib/Screenshots.jsm136
-rw-r--r--browser/components/newtab/lib/SearchShortcuts.sys.mjs67
-rw-r--r--browser/components/newtab/lib/SectionsManager.jsm712
-rw-r--r--browser/components/newtab/lib/ShortURL.jsm83
-rw-r--r--browser/components/newtab/lib/SiteClassifier.jsm99
-rw-r--r--browser/components/newtab/lib/SnippetsTestMessageProvider.sys.mjs688
-rw-r--r--browser/components/newtab/lib/Spotlight.jsm85
-rw-r--r--browser/components/newtab/lib/Store.jsm195
-rw-r--r--browser/components/newtab/lib/SystemTickFeed.jsm75
-rw-r--r--browser/components/newtab/lib/TelemetryFeed.jsm1403
-rw-r--r--browser/components/newtab/lib/TippyTopProvider.sys.mjs60
-rw-r--r--browser/components/newtab/lib/ToastNotification.jsm118
-rw-r--r--browser/components/newtab/lib/ToolbarBadgeHub.jsm318
-rw-r--r--browser/components/newtab/lib/ToolbarPanelHub.jsm612
-rw-r--r--browser/components/newtab/lib/TopSitesFeed.jsm1715
-rw-r--r--browser/components/newtab/lib/TopStoriesFeed.jsm746
-rw-r--r--browser/components/newtab/lib/UTEventReporting.sys.mjs62
-rw-r--r--browser/components/newtab/lib/cache-worker.js205
-rw-r--r--browser/components/newtab/loaders/inject-loader.js59
-rw-r--r--browser/components/newtab/metrics.yaml1221
-rw-r--r--browser/components/newtab/moz.build58
-rw-r--r--browser/components/newtab/nsIAboutNewTabService.idl39
-rw-r--r--browser/components/newtab/package-lock.json12021
-rw-r--r--browser/components/newtab/package.json124
-rw-r--r--browser/components/newtab/pings.yaml45
-rw-r--r--browser/components/newtab/prerendered/activity-stream-debug.html47
-rw-r--r--browser/components/newtab/prerendered/activity-stream-noscripts.html36
-rw-r--r--browser/components/newtab/prerendered/activity-stream.html47
-rw-r--r--browser/components/newtab/test/.eslintrc.js41
-rw-r--r--browser/components/newtab/test/InflightAssetsMessageProvider.jsm342
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser.ini39
-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.js35
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_disabled.js97
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_experiments_api_control.js63
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js30
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js27
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_no_cache_on_SessionStartup_restore.js37
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js83
-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.js54
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_shutdown_timeout.js45
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/head.js360
-rw-r--r--browser/components/newtab/test/browser/annotation_first.html2
-rw-r--r--browser/components/newtab/test/browser/annotation_second.html2
-rw-r--r--browser/components/newtab/test/browser/annotation_third.html2
-rw-r--r--browser/components/newtab/test/browser/blue_page.html6
-rw-r--r--browser/components/newtab/test/browser/browser.ini112
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js214
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_configurable_ui.js668
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_fxa_signin_flow.js303
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_glean.js174
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_import.js106
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_mobile_downloads.js112
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage_default.js736
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage_experimentAPI.js597
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage_languageSwitcher.js705
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage_mr.js621
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage_video.js97
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_observer.js71
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js298
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_screen_targeting.js152
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_upgrade_multistage_mr.js316
-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_bug1761522.js232
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_bug1800087.js48
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_cfr.js914
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js505
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_group_frequency.js190
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js160
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_infobar.js226
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js116
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_snippets.js190
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_snippets_dismiss.js99
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_targeting.js1697
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_toast_notification.js139
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js149
-rw-r--r--browser/components/newtab/test/browser/browser_context_menu_item.js18
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_content.js222
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_render.js27
-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.js33
-rw-r--r--browser/components/newtab/test/browser/browser_feature_callout_in_chrome.js487
-rw-r--r--browser/components/newtab/test/browser/browser_getScreenshots.js90
-rw-r--r--browser/components/newtab/test/browser/browser_highlights_section.js96
-rw-r--r--browser/components/newtab/test/browser/browser_multistage_spotlight.js58
-rw-r--r--browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js145
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_header.js76
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js151
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_overrides.js138
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_ping.js216
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_towindow.js45
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_trigger.js50
-rw-r--r--browser/components/newtab/test/browser/browser_open_tab_focus.js37
-rw-r--r--browser/components/newtab/test/browser/browser_remote_l10n.js56
-rw-r--r--browser/components/newtab/test/browser/browser_topsites_annotation.js980
-rw-r--r--browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js126
-rw-r--r--browser/components/newtab/test/browser/browser_topsites_section.js299
-rw-r--r--browser/components/newtab/test/browser/browser_trigger_listeners.js343
-rw-r--r--browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js152
-rw-r--r--browser/components/newtab/test/browser/ds_layout.json90
-rw-r--r--browser/components/newtab/test/browser/file_pdf.PDF12
-rw-r--r--browser/components/newtab/test/browser/head.js392
-rw-r--r--browser/components/newtab/test/browser/red_page.html6
-rw-r--r--browser/components/newtab/test/browser/redirect_to.sjs9
-rw-r--r--browser/components/newtab/test/browser/snippet.json46
-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.json53
-rw-r--r--browser/components/newtab/test/schemas/pings.js304
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/AWScreenUtils.test.jsx140
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/CTAParagraph.test.jsx49
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/HeroImage.test.jsx40
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MRColorways.test.jsx328
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MobileDownloads.test.jsx69
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MultiSelect.test.jsx151
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MultiStageAWProton.test.jsx564
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx824
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/OnboardingVideoTest.test.jsx45
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouter.test.js3040
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterChild.test.js74
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js153
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js106
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js428
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js491
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js574
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js778
-rw-r--r--browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js32
-rw-r--r--browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js1252
-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/RemoteL10n.test.js217
-rw-r--r--browser/components/newtab/test/unit/asrouter/RichText.test.jsx101
-rw-r--r--browser/components/newtab/test/unit/asrouter/SnippetsTestMessageProvider.test.js43
-rw-r--r--browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js88
-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.js125
-rw-r--r--browser/components/newtab/test/unit/asrouter/constants.js137
-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.jsx213
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx112
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx106
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx108
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx277
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx81
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx259
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx354
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/isEmailOrPhoneNumber.test.js56
-rw-r--r--browser/components/newtab/test/unit/common/Actions.test.js236
-rw-r--r--browser/components/newtab/test/unit/common/Dedupe.test.js38
-rw-r--r--browser/components/newtab/test/unit/common/Reducers.test.js1566
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx516
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Base.test.jsx130
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Card.test.jsx510
-rw-r--r--browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx67
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx447
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx182
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx227
-rw-r--r--browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx72
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx313
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx354
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx134
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx544
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx138
-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.jsx146
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx151
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx57
-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.jsx94
-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.jsx278
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx131
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/PrivacyLink.test.jsx29
-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/TopicsWidget.test.jsx238
-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.jsx68
-rw-r--r--browser/components/newtab/test/unit/content-src/components/HelpText.test.jsx41
-rw-r--r--browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx582
-rw-r--r--browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx48
-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.jsx179
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Sections.test.jsx600
-rw-r--r--browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx1919
-rw-r--r--browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx56
-rw-r--r--browser/components/newtab/test/unit/content-src/components/TopSites/TopSiteImpressionWrapper.test.jsx150
-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.js35
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js120
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/init-store.test.js207
-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.js576
-rw-r--r--browser/components/newtab/test/unit/lib/AboutPreferences.test.js429
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStream.test.js576
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js432
-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/DiscoveryStreamFeed.test.js3581
-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.js112
-rw-r--r--browser/components/newtab/test/unit/lib/HighlightsFeed.test.js822
-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.js81
-rw-r--r--browser/components/newtab/test/unit/lib/PersistentCache.test.js142
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js95
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js479
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js356
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js456
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js1543
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js134
-rw-r--r--browser/components/newtab/test/unit/lib/PlacesFeed.test.js1245
-rw-r--r--browser/components/newtab/test/unit/lib/PrefsFeed.test.js357
-rw-r--r--browser/components/newtab/test/unit/lib/RecommendationProvider.test.js162
-rw-r--r--browser/components/newtab/test/unit/lib/Screenshots.test.js209
-rw-r--r--browser/components/newtab/test/unit/lib/SectionsManager.test.js897
-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.js305
-rw-r--r--browser/components/newtab/test/unit/lib/SystemTickFeed.test.js76
-rw-r--r--browser/components/newtab/test/unit/lib/TelemetryFeed.test.js2606
-rw-r--r--browser/components/newtab/test/unit/lib/TippyTopProvider.test.js121
-rw-r--r--browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js649
-rw-r--r--browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js934
-rw-r--r--browser/components/newtab/test/unit/lib/TopSitesFeed.test.js3020
-rw-r--r--browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js1903
-rw-r--r--browser/components/newtab/test/unit/lib/UTEventReporting.test.js115
-rw-r--r--browser/components/newtab/test/unit/unit-entry.js684
-rw-r--r--browser/components/newtab/test/unit/utils.js406
-rw-r--r--browser/components/newtab/test/xpcshell/ds_layout.json89
-rw-r--r--browser/components/newtab/test/xpcshell/head.js105
-rw-r--r--browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js98
-rw-r--r--browser/components/newtab/test/xpcshell/test_ASRouterTargeting_snapshot.js138
-rw-r--r--browser/components/newtab/test/xpcshell/test_ASRouter_getTargetingParameters.js73
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js33
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js251
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutNewTab.js359
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js69
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js101
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry_glean.js143
-rw-r--r--browser/components/newtab/test/xpcshell/test_CFRMessageProvider.js32
-rw-r--r--browser/components/newtab/test/xpcshell/test_InflightAssetsMessageProvider.js41
-rw-r--r--browser/components/newtab/test/xpcshell/test_OnboardingMessageProvider.js229
-rw-r--r--browser/components/newtab/test/xpcshell/test_PanelTestProvider.js83
-rw-r--r--browser/components/newtab/test/xpcshell/test_reach_experiments.js97
-rw-r--r--browser/components/newtab/test/xpcshell/test_remoteExperiments.js37
-rw-r--r--browser/components/newtab/test/xpcshell/topstories.json53
-rw-r--r--browser/components/newtab/test/xpcshell/xpcshell.ini32
-rw-r--r--browser/components/newtab/tools/babel-jsm-to-commonjs.js287
-rw-r--r--browser/components/newtab/tools/resourceUriPlugin.js41
-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.js9
-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.js80
-rw-r--r--browser/components/newtab/yamscripts.yml58
673 files changed, 213102 insertions, 0 deletions
diff --git a/browser/components/newtab/.eslintrc.js b/browser/components/newtab/.eslintrc.js
new file mode 100644
index 0000000000..b6362a9552
--- /dev/null
+++ b/browser/components/newtab/.eslintrc.js
@@ -0,0 +1,211 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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",
+ },
+ 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")
+ "prettier", // require("eslint-config-prettier")
+ ],
+ overrides: [
+ {
+ // These files use fluent-dom to insert content
+ files: [
+ "content-src/aboutwelcome/components/Zap.jsx",
+ "content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx",
+ "content-src/aboutwelcome/components/MultiStageScreen.jsx",
+ "content-src/aboutwelcome/components/MultiStageProtonScreen.jsx",
+ "content-src/aboutwelcome/components/MultiSelect.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": "off",
+ "jsx-a11y/heading-has-content": "off",
+ "jsx-a11y/label-has-associated-control": "off",
+ "jsx-a11y/no-onchange": "off",
+ },
+ },
+ {
+ files: [
+ "bin/**",
+ "content-src/**",
+ "./*.js",
+ "loaders/**",
+ "tools/**",
+ "test/unit/**",
+ ],
+ env: {
+ node: true,
+ },
+ },
+ {
+ // Use a configuration that's more appropriate for JSMs
+ files: "**/*.jsm",
+ parserOptions: {
+ sourceType: "script",
+ },
+ rules: {
+ "no-implicit-globals": "off",
+ },
+ },
+ {
+ files: "test/xpcshell/**",
+ extends: ["plugin:mozilla/xpcshell-test"],
+ },
+ {
+ files: "test/browser/**",
+ extends: ["plugin:mozilla/browser-test"],
+ },
+ {
+ // Exempt all files without a 'test' string in their path name since no-insecure-url
+ // is focussing on the test base
+ files: "*",
+ excludedFiles: ["**/test**", "**/test*/**", "Test*/**"],
+ rules: {
+ "@microsoft/sdl/no-insecure-url": "off",
+ },
+ },
+ {
+ // That are all files in browser/component/newtab/test that produces warnings in the existing test infrastructure.
+ // Since our focus is that new tests won't use http without thinking twice we exempt
+ // these test files for now.
+ // TODO gradually check and remove from here bug 1758951.
+ files: [
+ "browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js",
+ "browser/components/newtab/test/browser/browser_aboutwelcome_observer.js",
+ "browser/components/newtab/test/browser/browser_asrouter_cfr.js",
+ "browser/components/newtab/test/browser/browser_asrouter_group_frequency.js",
+ "browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js",
+ "browser/components/newtab/test/browser/browser_trigger_listeners.js",
+ ],
+ rules: {
+ "@microsoft/sdl/no-insecure-url": "off",
+ },
+ },
+ ],
+ rules: {
+ "fetch-options/no-fetch-credentials": "error",
+
+ "react/jsx-boolean-value": ["error", "always"],
+ "react/jsx-key": "error",
+ "react/jsx-no-bind": "error",
+ "react/jsx-no-comment-textnodes": "error",
+ "react/jsx-no-duplicate-props": "error",
+ "react/jsx-no-target-blank": "error",
+ "react/jsx-no-undef": "error",
+ "react/jsx-pascal-case": "error",
+ "react/jsx-uses-react": "error",
+ "react/jsx-uses-vars": "error",
+ "react/no-access-state-in-setstate": "error",
+ "react/no-danger": "error",
+ "react/no-deprecated": "error",
+ "react/no-did-mount-set-state": "error",
+ "react/no-did-update-set-state": "error",
+ "react/no-direct-mutation-state": "error",
+ "react/no-is-mounted": "error",
+ "react/no-unknown-property": "error",
+ "react/require-render-return": "error",
+
+ "accessor-pairs": ["error", { setWithoutGet: true, getWithoutSet: false }],
+ "array-callback-return": "error",
+ "block-scoped-var": "error",
+ "consistent-this": ["error", "use-bind"],
+ eqeqeq: "error",
+ "for-direction": "error",
+ "func-name-matching": "error",
+ "getter-return": "error",
+ "guard-for-in": "error",
+ "handle-callback-err": "error",
+ "lines-between-class-members": "error",
+ "max-depth": ["error", 4],
+ "max-nested-callbacks": ["error", 4],
+ "max-params": ["error", 6],
+ "max-statements": ["error", 50],
+ "max-statements-per-line": ["error", { max: 2 }],
+ "new-cap": ["error", { newIsCap: true, capIsNew: false }],
+ "no-alert": "error",
+ "no-buffer-constructor": "error",
+ "no-console": ["error", { allow: ["error"] }],
+ "no-div-regex": "error",
+ "no-duplicate-imports": "error",
+ "no-eq-null": "error",
+ "no-extend-native": "error",
+ "no-extra-label": "error",
+ "no-implicit-coercion": ["error", { allow: ["!!"] }],
+ "no-implicit-globals": "error",
+ "no-loop-func": "error",
+ "no-mixed-requires": "error",
+ "no-multi-assign": "error",
+ "no-multi-str": "error",
+ "no-new": "error",
+ "no-new-func": "error",
+ "no-new-require": "error",
+ "no-octal-escape": "error",
+ "no-param-reassign": "error",
+ "no-path-concat": "error",
+ "no-process-exit": "error",
+ "no-proto": "error",
+ "no-prototype-builtins": "error",
+ "no-return-assign": ["error", "except-parens"],
+ "no-script-url": "error",
+ "no-shadow": "error",
+ "no-template-curly-in-string": "error",
+ "no-undef-init": "error",
+ "no-unmodified-loop-condition": "error",
+ "no-unused-expressions": "error",
+ "no-use-before-define": "error",
+ "no-useless-computed-key": "error",
+ "no-useless-constructor": "error",
+ "no-useless-rename": "error",
+ "no-var": "error",
+ "no-void": ["error", { allowAsStatement: true }],
+ "one-var": ["error", "never"],
+ "operator-assignment": ["error", "always"],
+ "prefer-destructuring": [
+ "error",
+ {
+ AssignmentExpression: { array: true },
+ VariableDeclarator: { array: true, object: true },
+ },
+ ],
+ "prefer-numeric-literals": "error",
+ "prefer-promise-reject-errors": "error",
+ "prefer-rest-params": "error",
+ "prefer-spread": "error",
+ "prefer-template": "error",
+ radix: ["error", "always"],
+ "require-await": "error",
+ "sort-vars": "error",
+ "symbol-description": "error",
+ "vars-on-top": "error",
+ yoda: ["error", "never"],
+ },
+};
diff --git a/browser/components/newtab/.nvmrc b/browser/components/newtab/.nvmrc
new file mode 100644
index 0000000000..e65243f2ea
--- /dev/null
+++ b/browser/components/newtab/.nvmrc
@@ -0,0 +1 @@
+16.19.0
diff --git a/browser/components/newtab/AboutNewTabService.jsm b/browser/components/newtab/AboutNewTabService.jsm
new file mode 100644
index 0000000000..5b9eb478df
--- /dev/null
+++ b/browser/components/newtab/AboutNewTabService.jsm
@@ -0,0 +1,523 @@
+/**
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const { E10SUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/E10SUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ BasePromiseWorker: "resource://gre/modules/PromiseWorker.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+});
+
+/**
+ * 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_TESTING =
+ "browser.startup.homepage.abouthome_cache.testing";
+const ABOUT_WELCOME_URL =
+ "resource://activity-stream/aboutwelcome/aboutwelcome.html";
+
+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,
+ DISQUALIFIED: 5,
+ },
+ 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 (!lazy.NimbusFeatures.abouthomecache.getVariable("enabled")) {
+ 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 lazy.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
+ );
+ }
+ },
+
+ /**
+ * If the cache hasn't been used, transitions it into the DISQUALIFIED
+ * state so that it cannot be used. This should be called if it's been
+ * determined that about:newtab is going to be loaded, which doesn't
+ * use the cache.
+ */
+ disqualifyCache() {
+ if (this._state === this.STATES.UNCONSUMED) {
+ this.setState(this.STATES.DISQUALIFIED);
+ this.reportUsageResult(false /* success */);
+ }
+ },
+};
+
+/**
+ * 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,
+ "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.
+ */
+
+ lazy.NimbusFeatures.aboutwelcome.recordExposureEvent({ once: true });
+ if (lazy.NimbusFeatures.aboutwelcome.getVariable("enabled") ?? 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;
+ }
+
+ get defaultURL() {
+ if (IS_PRIVILEGED_PROCESS) {
+ // This is a bit of a hack, but attempting to load about:newtab will
+ // enter this code path in order to get at the expected URL, and we
+ // can use that to disqualify the about:home cache, since we don't
+ // use it for about:newtab loads, and we don't want the about:home
+ // cache to be wildly out of date when about:home is eventually
+ // loaded (for example, in the first new window).
+ AboutHomeStartupCacheChild.disqualifyCache();
+ }
+
+ return super.defaultURL;
+ }
+}
+
+/**
+ * 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..eef6c75b37
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm
@@ -0,0 +1,339 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ AboutWelcomeDefaults:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeDefaults.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(lazy, "log", () => {
+ const { Logger } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/Logger.sys.mjs"
+ );
+ return new Logger("AboutWelcomeChild");
+});
+
+async function getSelectedTheme(child) {
+ let activeThemeId = await child.sendQuery("AWPage:GET_SELECTED_THEME");
+ return activeThemeId;
+}
+
+class AboutWelcomeChild extends JSWindowActorChild {
+ actorCreated() {
+ this.exportFunctions();
+ }
+
+ /**
+ * Send event that can be handled by the page
+ * @param {{type: string, data?: any}} action
+ */
+ sendToPage(action) {
+ lazy.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.AWAddScreenImpression.bind(this), window, {
+ defineAs: "AWAddScreenImpression",
+ });
+
+ Cu.exportFunction(this.AWGetFeatureConfig.bind(this), window, {
+ defineAs: "AWGetFeatureConfig",
+ });
+
+ Cu.exportFunction(this.AWGetFxAMetricsFlowURI.bind(this), window, {
+ defineAs: "AWGetFxAMetricsFlowURI",
+ });
+
+ Cu.exportFunction(this.AWGetSelectedTheme.bind(this), window, {
+ defineAs: "AWGetSelectedTheme",
+ });
+
+ Cu.exportFunction(this.AWSelectTheme.bind(this), window, {
+ defineAs: "AWSelectTheme",
+ });
+
+ Cu.exportFunction(this.AWEvaluateScreenTargeting.bind(this), window, {
+ defineAs: "AWEvaluateScreenTargeting",
+ });
+
+ 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",
+ });
+
+ Cu.exportFunction(this.AWFinish.bind(this), window, {
+ defineAs: "AWFinish",
+ });
+
+ Cu.exportFunction(this.AWEnsureLangPackInstalled.bind(this), window, {
+ defineAs: "AWEnsureLangPackInstalled",
+ });
+
+ Cu.exportFunction(
+ this.AWNegotiateLangPackForLanguageMismatch.bind(this),
+ window,
+ {
+ defineAs: "AWNegotiateLangPackForLanguageMismatch",
+ }
+ );
+
+ Cu.exportFunction(this.AWSetRequestedLocales.bind(this), window, {
+ defineAs: "AWSetRequestedLocales",
+ });
+
+ Cu.exportFunction(this.AWSendToDeviceEmailsSupported.bind(this), window, {
+ defineAs: "AWSendToDeviceEmailsSupported",
+ });
+
+ Cu.exportFunction(this.AWNewScreen.bind(this), window, {
+ defineAs: "AWNewScreen",
+ });
+ }
+
+ /**
+ * Wrap a promise so content can use Promise methods.
+ */
+ wrapPromise(promise) {
+ return new this.contentWindow.Promise((resolve, reject) =>
+ promise.then(resolve, reject)
+ );
+ }
+
+ /**
+ * Clones the result of the query into the content window.
+ */
+ sendQueryAndCloneForContent(...sendQueryArgs) {
+ return this.wrapPromise(
+ (async () => {
+ return Cu.cloneInto(
+ await this.sendQuery(...sendQueryArgs),
+ this.contentWindow
+ );
+ })()
+ );
+ }
+
+ AWSelectTheme(data) {
+ return this.wrapPromise(
+ this.sendQuery("AWPage:SELECT_THEME", data.toUpperCase())
+ );
+ }
+
+ AWEvaluateScreenTargeting(data) {
+ return this.sendQueryAndCloneForContent(
+ "AWPage:EVALUATE_SCREEN_TARGETING",
+ data
+ );
+ }
+
+ AWAddScreenImpression(screen) {
+ return this.wrapPromise(
+ this.sendQuery("AWPage:ADD_SCREEN_IMPRESSION", screen)
+ );
+ }
+
+ /**
+ * Send initial data to page including experiment information
+ */
+ async getAWContent() {
+ let attributionData = await this.sendQuery("AWPage:GET_ATTRIBUTION_DATA");
+
+ // Return to AMO gets returned early.
+ if (attributionData?.template) {
+ lazy.log.debug("Loading about:welcome with RTAMO attribution data");
+ return Cu.cloneInto(attributionData, this.contentWindow);
+ } else if (attributionData?.ua) {
+ lazy.log.debug("Loading about:welcome with UA attribution");
+ }
+
+ let experimentMetadata =
+ lazy.ExperimentAPI.getExperimentMetaData({
+ featureId: "aboutwelcome",
+ }) || {};
+
+ lazy.log.debug(
+ `Loading about:welcome with ${
+ experimentMetadata?.slug ?? "no"
+ } experiment`
+ );
+
+ let featureConfig = lazy.NimbusFeatures.aboutwelcome.getAllVariables();
+ featureConfig.needDefault = await this.sendQuery("AWPage:NEED_DEFAULT");
+ featureConfig.needPin = await this.sendQuery("AWPage:DOES_APP_NEED_PIN");
+ if (featureConfig.languageMismatchEnabled) {
+ featureConfig.appAndSystemLocaleInfo = await this.sendQuery(
+ "AWPage:GET_APP_AND_SYSTEM_LOCALE_INFO"
+ );
+ }
+
+ // FeatureConfig (from experiments) has higher precendence
+ // to defaults. But the `screens` property isn't defined we shouldn't
+ // override the default with `null`
+ let defaults = lazy.AboutWelcomeDefaults.getDefaults();
+
+ const content = await lazy.AboutWelcomeDefaults.prepareContentForReact({
+ ...attributionData,
+ ...experimentMetadata,
+ ...defaults,
+ ...featureConfig,
+ screens: featureConfig.screens ?? defaults.screens,
+ backdrop: featureConfig.backdrop ?? defaults.backdrop,
+ });
+
+ return Cu.cloneInto(content, this.contentWindow);
+ }
+
+ AWGetFeatureConfig() {
+ return this.wrapPromise(this.getAWContent());
+ }
+
+ AWGetFxAMetricsFlowURI() {
+ return this.wrapPromise(this.sendQuery("AWPage:FXA_METRICS_FLOW_URI"));
+ }
+
+ AWGetSelectedTheme() {
+ return this.wrapPromise(getSelectedTheme(this));
+ }
+
+ /**
+ * Send Event Telemetry
+ * @param {object} eventData
+ */
+ AWSendEventTelemetry(eventData) {
+ this.AWSendToParent("TELEMETRY_EVENT", {
+ ...eventData,
+ event_context: {
+ ...eventData.event_context,
+ },
+ });
+ }
+
+ /**
+ * Send message that can be handled by AboutWelcomeParent.jsm
+ * @param {string} type
+ * @param {any=} data
+ * @returns {Promise<unknown>}
+ */
+ AWSendToParent(type, data) {
+ return this.sendQueryAndCloneForContent(`AWPage:${type}`, data);
+ }
+
+ AWWaitForMigrationClose() {
+ return this.wrapPromise(this.sendQuery("AWPage:WAIT_FOR_MIGRATION_CLOSE"));
+ }
+
+ AWFinish() {
+ this.contentWindow.location.href = "about:home";
+ }
+
+ AWEnsureLangPackInstalled(negotiated, screenContent) {
+ const content = Cu.cloneInto(screenContent, {});
+ return this.wrapPromise(
+ this.sendQuery(
+ "AWPage:ENSURE_LANG_PACK_INSTALLED",
+ negotiated.langPack
+ ).then(() => {
+ const formatting = [];
+ const l10n = new Localization(
+ ["branding/brand.ftl", "browser/newtab/onboarding.ftl"],
+ false,
+ undefined,
+ // Use the system-ish then app then default locale.
+ [...negotiated.requestSystemLocales, "en-US"]
+ );
+
+ // Add the negotiated language name as args.
+ function addMessageArgsAndUseLangPack(obj) {
+ for (const value of Object.values(obj)) {
+ if (value?.string_id) {
+ value.args = {
+ ...value.args,
+ negotiatedLanguage: negotiated.langPackDisplayName,
+ };
+
+ // Expose fluent strings wanting lang pack as raw.
+ if (value.useLangPack) {
+ formatting.push(
+ l10n.formatValue(value.string_id, value.args).then(raw => {
+ delete value.string_id;
+ value.raw = raw;
+ })
+ );
+ }
+ }
+ }
+ }
+ addMessageArgsAndUseLangPack(content.languageSwitcher);
+ addMessageArgsAndUseLangPack(content);
+ return Promise.all(formatting).then(() =>
+ Cu.cloneInto(content, this.contentWindow)
+ );
+ })
+ );
+ }
+
+ AWSetRequestedLocales(requestSystemLocales) {
+ return this.sendQueryAndCloneForContent(
+ "AWPage:SET_REQUESTED_LOCALES",
+ requestSystemLocales
+ );
+ }
+
+ AWNegotiateLangPackForLanguageMismatch(appAndSystemLocaleInfo) {
+ return this.sendQueryAndCloneForContent(
+ "AWPage:NEGOTIATE_LANGPACK",
+ appAndSystemLocaleInfo
+ );
+ }
+
+ AWSendToDeviceEmailsSupported() {
+ return this.wrapPromise(
+ this.sendQuery("AWPage:SEND_TO_DEVICE_EMAILS_SUPPORTED")
+ );
+ }
+
+ AWNewScreen(screenId) {
+ return this.wrapPromise(this.sendQuery("AWPage:NEW_SCREEN", screenId));
+ }
+
+ /**
+ * @param {{type: string, detail?: any}} event
+ * @override
+ */
+ handleEvent(event) {
+ lazy.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..2c9ff90eb2
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm
@@ -0,0 +1,266 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
+ BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
+ BuiltInThemes: "resource:///modules/BuiltInThemes.sys.mjs",
+ FxAccounts: "resource://gre/modules/FxAccounts.sys.mjs",
+ LangPackMatcher: "resource://gre/modules/LangPackMatcher.sys.mjs",
+ ShellService: "resource:///modules/ShellService.sys.mjs",
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ AboutWelcomeTelemetry:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm",
+ AboutWelcomeDefaults:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeDefaults.jsm",
+ AWScreenUtils: "resource://activity-stream/lib/AWScreenUtils.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(lazy, "log", () => {
+ const { Logger } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/Logger.sys.mjs"
+ );
+ return new Logger("AboutWelcomeParent");
+});
+
+XPCOMUtils.defineLazyGetter(
+ lazy,
+ "Telemetry",
+ () => new lazy.AboutWelcomeTelemetry()
+);
+
+const DID_SEE_ABOUT_WELCOME_PREF = "trailhead.firstrun.didSeeAboutWelcome";
+const AWTerminate = {
+ 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 = {
+ AUTOMATIC: "default-theme@mozilla.org",
+ DARK: "firefox-compact-dark@mozilla.org",
+ LIGHT: "firefox-compact-light@mozilla.org",
+ ALPENGLOW: "firefox-alpenglow@mozilla.org",
+ "PLAYMAKER-SOFT": "playmaker-soft-colorway@mozilla.org",
+ "PLAYMAKER-BALANCED": "playmaker-balanced-colorway@mozilla.org",
+ "PLAYMAKER-BOLD": "playmaker-bold-colorway@mozilla.org",
+ "EXPRESSIONIST-SOFT": "expressionist-soft-colorway@mozilla.org",
+ "EXPRESSIONIST-BALANCED": "expressionist-balanced-colorway@mozilla.org",
+ "EXPRESSIONIST-BOLD": "expressionist-bold-colorway@mozilla.org",
+ "VISIONARY-SOFT": "visionary-soft-colorway@mozilla.org",
+ "VISIONARY-BALANCED": "visionary-balanced-colorway@mozilla.org",
+ "VISIONARY-BOLD": "visionary-bold-colorway@mozilla.org",
+ "ACTIVIST-SOFT": "activist-soft-colorway@mozilla.org",
+ "ACTIVIST-BALANCED": "activist-balanced-colorway@mozilla.org",
+ "ACTIVIST-BOLD": "activist-bold-colorway@mozilla.org",
+ "DREAMER-SOFT": "dreamer-soft-colorway@mozilla.org",
+ "DREAMER-BALANCED": "dreamer-balanced-colorway@mozilla.org",
+ "DREAMER-BOLD": "dreamer-bold-colorway@mozilla.org",
+ "INNOVATOR-SOFT": "innovator-soft-colorway@mozilla.org",
+ "INNOVATOR-BALANCED": "innovator-balanced-colorway@mozilla.org",
+ "INNOVATOR-BOLD": "innovator-bold-colorway@mozilla.org",
+};
+
+class AboutWelcomeObserver {
+ constructor() {
+ Services.obs.addObserver(this, "quit-application");
+
+ this.win = Services.focus.activeWindow;
+ if (!this.win) {
+ return;
+ }
+
+ this.terminateReason = AWTerminate.ADDRESS_BAR_NAVIGATED;
+
+ 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() {
+ lazy.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 AboutWelcomeParent extends JSWindowActorParent {
+ constructor() {
+ super();
+ this.AboutWelcomeObserver = new AboutWelcomeObserver(this);
+ }
+
+ // Static methods that calls into ShellService to check
+ // if Firefox is pinned or already default
+ static doesAppNeedPin() {
+ return lazy.ShellService.doesAppNeedPin();
+ }
+
+ static isDefaultBrowser() {
+ return lazy.ShellService.isDefaultBrowser();
+ }
+
+ didDestroy() {
+ if (this.AboutWelcomeObserver) {
+ this.AboutWelcomeObserver.stop();
+ }
+ this.RegionHomeObserver?.stop();
+
+ lazy.Telemetry.sendTelemetry({
+ event: "SESSION_END",
+ event_context: {
+ reason: this.AboutWelcomeObserver.terminateReason,
+ page: "about:welcome",
+ },
+ message_id: this.AWMessageId,
+ });
+ }
+
+ /**
+ * Handle messages from AboutWelcomeChild.jsm
+ *
+ * @param {string} type
+ * @param {any=} data
+ * @param {Browser} the xul:browser rendering the page
+ */
+ async onContentMessage(type, data, browser) {
+ lazy.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) {
+ lazy.log.debug(`Fails to set ${DID_SEE_ABOUT_WELCOME_PREF}.`);
+ }
+ break;
+ case "AWPage:SPECIAL_ACTION":
+ return lazy.SpecialMessageActions.handleAction(data, browser);
+ case "AWPage:FXA_METRICS_FLOW_URI":
+ return lazy.FxAccounts.config.promiseMetricsFlowURI("aboutwelcome");
+ case "AWPage:TELEMETRY_EVENT":
+ lazy.Telemetry.sendTelemetry(data);
+ break;
+ case "AWPage:GET_ATTRIBUTION_DATA":
+ let attributionData =
+ await lazy.AboutWelcomeDefaults.getAttributionContent();
+ return attributionData;
+ case "AWPage:SELECT_THEME":
+ await lazy.BuiltInThemes.ensureBuiltInThemes();
+ return lazy.AddonManager.getAddonByID(LIGHT_WEIGHT_THEMES[data]).then(
+ addon => addon.enable()
+ );
+ case "AWPage:GET_SELECTED_THEME":
+ let themes = await lazy.AddonManager.getAddonsByTypes(["theme"]);
+ let activeTheme = themes.find(addon => addon.isActive);
+ // Store the current theme ID so user can restore their previous theme.
+ if (activeTheme?.id) {
+ LIGHT_WEIGHT_THEMES.AUTOMATIC = activeTheme.id;
+ }
+ // 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:DOES_APP_NEED_PIN":
+ return AboutWelcomeParent.doesAppNeedPin();
+ case "AWPage:NEED_DEFAULT":
+ // Only need to set default if we're supposed to check and not default.
+ return (
+ Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser") &&
+ !AboutWelcomeParent.isDefaultBrowser()
+ );
+ case "AWPage:WAIT_FOR_MIGRATION_CLOSE":
+ // Support multiples types of migration: 1) content modal 2) old
+ // migration modal 3) standalone content modal
+ return new Promise(resolve => {
+ const topics = [
+ "MigrationWizard:Closed",
+ "MigrationWizard:Destroyed",
+ ];
+ const observer = () => {
+ topics.forEach(t => Services.obs.removeObserver(observer, t));
+ resolve();
+ };
+ topics.forEach(t => Services.obs.addObserver(observer, t));
+ });
+ case "AWPage:GET_APP_AND_SYSTEM_LOCALE_INFO":
+ return lazy.LangPackMatcher.getAppAndSystemLocaleInfo();
+ case "AWPage:EVALUATE_SCREEN_TARGETING":
+ return lazy.AWScreenUtils.evaluateTargetingAndRemoveScreens(data);
+ case "AWPage:ADD_SCREEN_IMPRESSION":
+ return lazy.AWScreenUtils.addScreenImpression(data);
+ case "AWPage:NEGOTIATE_LANGPACK":
+ return lazy.LangPackMatcher.negotiateLangPackForLanguageMismatch(data);
+ case "AWPage:ENSURE_LANG_PACK_INSTALLED":
+ return lazy.LangPackMatcher.ensureLangPackInstalled(data);
+ case "AWPage:SET_REQUESTED_LOCALES":
+ return lazy.LangPackMatcher.setRequestedAppLocales(data);
+ case "AWPage:SEND_TO_DEVICE_EMAILS_SUPPORTED": {
+ return lazy.BrowserUtils.sendToDeviceEmailsSupported();
+ }
+ default:
+ lazy.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;
+
+ if (this.manager.rootFrameLoader) {
+ browser = this.manager.rootFrameLoader.ownerElement;
+ return this.onContentMessage(name, data, browser);
+ }
+
+ lazy.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..fd52cc91e0
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js
@@ -0,0 +1,2321 @@
+/*!
+ *
+ * NOTE: This file is generated by webpack from aboutwelcome.jsx
+ * using the npm bundle task.
+ *
+ */
+/******/ (() => { // webpackBootstrap
+/******/ "use strict";
+/******/ var __webpack_modules__ = ([
+/* 0 */,
+/* 1 */
+/***/ ((module) => {
+
+module.exports = React;
+
+/***/ }),
+/* 2 */
+/***/ ((module) => {
+
+module.exports = ReactDOM;
+
+/***/ }),
+/* 3 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "AboutWelcomeUtils": () => (/* binding */ AboutWelcomeUtils),
+/* harmony export */ "DEFAULT_RTAMO_CONTENT": () => (/* binding */ DEFAULT_RTAMO_CONTENT)
+/* harmony export */ });
+var _document$querySelect;
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+// If the container has a "page" data attribute, then this is
+// a Spotlight modal or Feature Callout. Otherwise, this is
+// about:welcome and we should return the current page.
+const page = ((_document$querySelect = document.querySelector("#multi-stage-message-root.onboardingContainer[data-page]")) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.dataset.page) || document.location.href;
+const AboutWelcomeUtils = {
+ handleUserAction(action) {
+ return window.AWSendToParent("SPECIAL_ACTION", action);
+ },
+
+ sendImpressionTelemetry(messageId, context) {
+ var _window$AWSendEventTe, _window;
+
+ (_window$AWSendEventTe = (_window = window).AWSendEventTelemetry) === null || _window$AWSendEventTe === void 0 ? void 0 : _window$AWSendEventTe.call(_window, {
+ event: "IMPRESSION",
+ event_context: { ...context,
+ page
+ },
+ message_id: messageId
+ });
+ },
+
+ sendActionTelemetry(messageId, elementId, eventName = "CLICK_BUTTON") {
+ var _window$AWSendEventTe2, _window2;
+
+ const ping = {
+ event: eventName,
+ event_context: {
+ source: elementId,
+ page
+ },
+ message_id: messageId
+ };
+ (_window$AWSendEventTe2 = (_window2 = window).AWSendEventTelemetry) === null || _window$AWSendEventTe2 === void 0 ? void 0 : _window$AWSendEventTe2.call(_window2, ping);
+ },
+
+ sendDismissTelemetry(messageId, elementId) {
+ // Don't send DISMISS telemetry in spotlight modals since they already send
+ // their own equivalent telemetry.
+ if (page !== "spotlight") {
+ this.sendActionTelemetry(messageId, elementId, "DISMISS");
+ }
+ },
+
+ 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);
+ }
+ } catch (e) {
+ flowParams = null;
+ }
+
+ return flowParams;
+ },
+
+ sendEvent(type, detail) {
+ document.dispatchEvent(new CustomEvent(`AWPage:${type}`, {
+ bubbles: true,
+ detail
+ }));
+ }
+
+};
+const DEFAULT_RTAMO_CONTENT = {
+ template: "return_to_amo",
+ utm_term: "rtamo",
+ content: {
+ position: "split",
+ title: {
+ string_id: "mr1-return-to-amo-subtitle"
+ },
+ has_noodles: false,
+ subtitle: {
+ string_id: "mr1-return-to-amo-addon-title"
+ },
+ backdrop: "var(--mr-welcome-background-color) var(--mr-welcome-background-gradient)",
+ background: "url('chrome://activity-stream/content/data/content/assets/mr-rtamo-background-image.svg') no-repeat center",
+ progress_bar: true,
+ primary_button: {
+ label: {
+ string_id: "mr1-return-to-amo-add-extension-label"
+ },
+ source_id: "ADD_EXTENSION_BUTTON",
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: {
+ url: null,
+ telemetrySource: "rtamo"
+ }
+ }
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label"
+ },
+ source_id: "RTAMO_START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR"
+ }
+ },
+ secondary_button_top: {
+ label: {
+ string_id: "mr1-onboarding-sign-in-button-label"
+ },
+ source_id: "RTAMO_FXA_SIGNIN_BUTTON",
+ action: {
+ data: {
+ entrypoint: "activity-stream-firstrun",
+ where: "tab"
+ },
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: true
+ }
+ }
+ }
+};
+
+/***/ }),
+/* 4 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "MultiStageAboutWelcome": () => (/* binding */ MultiStageAboutWelcome),
+/* harmony export */ "SecondaryCTA": () => (/* binding */ SecondaryCTA),
+/* harmony export */ "StepsIndicator": () => (/* binding */ StepsIndicator),
+/* harmony export */ "ProgressBar": () => (/* binding */ ProgressBar),
+/* harmony export */ "WelcomeScreen": () => (/* binding */ WelcomeScreen)
+/* harmony export */ });
+/* 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__(5);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
+/* harmony import */ var _MultiStageProtonScreen__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
+/* harmony import */ var _LanguageSwitcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11);
+/* harmony import */ var _asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(17);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+ // Amount of milliseconds for all transitions to complete (including delays).
+
+const TRANSITION_OUT_TIME = 1000;
+const LANGUAGE_MISMATCH_SCREEN_ID = "AW_LANGUAGE_MISMATCH";
+const MultiStageAboutWelcome = props => {
+ let {
+ defaultScreens
+ } = props;
+ const didFilter = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false);
+ const [didMount, setDidMount] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
+ const [screens, setScreens] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(defaultScreens);
+ const [index, setScreenIndex] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(props.startScreen);
+ const [previousOrder, setPreviousOrder] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(props.startScreen - 1);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ (async () => {
+ // If we want to load index from history state, we don't want to send impression yet
+ if (!didMount) {
+ return;
+ } // On about:welcome first load, screensVisited should be empty
+
+
+ let screensVisited = didFilter.current ? screens.slice(0, index) : [];
+ let upcomingScreens = defaultScreens.filter(s => !screensVisited.find(v => v.id === s.id)) // Filter out Language Mismatch screen from upcoming
+ // screens if screens set from useLanguageSwitcher hook
+ // has filtered language screen
+ .filter(upcomingScreen => !(!screens.find(s => s.id === LANGUAGE_MISMATCH_SCREEN_ID) && upcomingScreen.id === LANGUAGE_MISMATCH_SCREEN_ID));
+ let filteredScreens = screensVisited.concat((await window.AWEvaluateScreenTargeting(upcomingScreens)) ?? upcomingScreens); // Use existing screen for the filtered screen to carry over any modification
+ // e.g. if AW_LANGUAGE_MISMATCH exists, use it from existing screens
+
+ setScreens(filteredScreens.map(filtered => screens.find(s => s.id === filtered.id) ?? filtered));
+ didFilter.current = true;
+ const screenInitials = filteredScreens.map(({
+ id
+ }) => {
+ var _id$split$;
+
+ return id === null || id === void 0 ? void 0 : (_id$split$ = id.split("_")[1]) === null || _id$split$ === void 0 ? void 0 : _id$split$[0];
+ }).join(""); // Send impression ping when respective screen first renders
+
+ filteredScreens.forEach((screen, order) => {
+ if (index === order) {
+ var _window$AWAddScreenIm, _window;
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendImpressionTelemetry(`${props.message_id}_${order}_${screen.id}_${screenInitials}`);
+ (_window$AWAddScreenIm = (_window = window).AWAddScreenImpression) === null || _window$AWAddScreenIm === void 0 ? void 0 : _window$AWAddScreenIm.call(_window, screen);
+ }
+ }); // Remember that a new screen has loaded for browser navigation
+
+ if (props.updateHistory && index > window.history.state) {
+ window.history.pushState(index, "");
+ } // Remember the previous screen index so we can animate the transition
+
+
+ setPreviousOrder(index);
+ })();
+ }, [index, didMount]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const [flowParams, setFlowParams] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
+ const {
+ metricsFlowUri
+ } = props;
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ (async () => {
+ if (metricsFlowUri) {
+ setFlowParams(await _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.fetchFlowParams(metricsFlowUri));
+ }
+ })();
+ }, [metricsFlowUri]); // Allow "in" style to render to actually transition towards regular state,
+ // which also makes using browser back/forward navigation skip transitions.
+
+ const [transition, setTransition] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(props.transitions ? "in" : "");
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ if (transition === "in") {
+ requestAnimationFrame(() => requestAnimationFrame(() => setTransition("")));
+ }
+ }, [transition]); // Transition to next screen, opening about:home on last screen button CTA
+
+ const handleTransition = () => {
+ // Only handle transitioning out from a screen once.
+ if (transition === "out") {
+ return;
+ } // Start transitioning things "out" immediately when moving forwards.
+
+
+ setTransition(props.transitions ? "out" : ""); // Actually move forwards after all transitions finish.
+
+ setTimeout(() => {
+ if (index < screens.length - 1) {
+ setTransition(props.transitions ? "in" : "");
+ setScreenIndex(prevState => prevState + 1);
+ } else {
+ window.AWFinish();
+ }
+ }, props.transitions ? TRANSITION_OUT_TIME : 0);
+ };
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ // When about:welcome loads (on refresh or pressing back button
+ // from about:home), ensure history state usEffect runs before
+ // useEffect hook that send impression telemetry
+ setDidMount(true);
+
+ if (props.updateHistory) {
+ // Switch to the screen tracked in state (null for initial state)
+ // or last screen index if a user navigates by pressing back
+ // button from about:home
+ const handler = ({
+ state
+ }) => {
+ if (transition === "out") {
+ return;
+ }
+
+ setTransition(props.transitions ? "out" : "");
+ setTimeout(() => {
+ setTransition(props.transitions ? "in" : "");
+ setScreenIndex(Math.min(state, screens.length - 1));
+ }, props.transitions ? TRANSITION_OUT_TIME : 0);
+ }; // Handle page load, e.g., going back to about:welcome from about:home
+
+
+ const {
+ state
+ } = window.history;
+
+ if (state) {
+ setScreenIndex(Math.min(state, screens.length - 1));
+ setPreviousOrder(Math.min(state, screens.length - 1));
+ } // Watch for browser back/forward button navigation events
+
+
+ window.addEventListener("popstate", handler);
+ return () => window.removeEventListener("popstate", handler);
+ }
+
+ return false;
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ // Save the active multi select state containing array of checkbox ids
+ // used in handleAction to update MULTI_ACTION data
+
+ const [activeMultiSelect, setActiveMultiSelect] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); // Get the active theme so the rendering code can make it selected
+ // by default.
+
+ const [activeTheme, setActiveTheme] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
+ const [initialTheme, setInitialTheme] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ (async () => {
+ let theme = await window.AWGetSelectedTheme();
+ setInitialTheme(theme);
+ setActiveTheme(theme);
+ })();
+ }, []);
+ const {
+ negotiatedLanguage,
+ langPackInstallPhase,
+ languageFilteredScreens
+ } = (0,_LanguageSwitcher__WEBPACK_IMPORTED_MODULE_4__.useLanguageSwitcher)(props.appAndSystemLocaleInfo, screens, index, setScreenIndex);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ setScreens(languageFilteredScreens);
+ }, [languageFilteredScreens]);
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `outer-wrapper onboardingContainer proton transition-${transition}`,
+ style: props.backdrop ? {
+ background: props.backdrop
+ } : {}
+ }, screens.map((screen, order) => {
+ const isFirstScreen = screen === screens[0];
+ const isLastScreen = screen === screens[screens.length - 1];
+ const totalNumberOfScreens = screens.length;
+ const isSingleScreen = totalNumberOfScreens === 1;
+ return index === order ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(WelcomeScreen, {
+ key: screen.id + order,
+ id: screen.id,
+ totalNumberOfScreens: totalNumberOfScreens,
+ isFirstScreen: isFirstScreen,
+ isLastScreen: isLastScreen,
+ isSingleScreen: isSingleScreen,
+ order: order,
+ previousOrder: previousOrder,
+ content: screen.content,
+ navigate: handleTransition,
+ messageId: `${props.message_id}_${order}_${screen.id}`,
+ UTMTerm: props.utm_term,
+ flowParams: flowParams,
+ activeTheme: activeTheme,
+ initialTheme: initialTheme,
+ setActiveTheme: setActiveTheme,
+ setInitialTheme: setInitialTheme,
+ activeMultiSelect: activeMultiSelect,
+ setActiveMultiSelect: setActiveMultiSelect,
+ autoAdvance: screen.auto_advance,
+ negotiatedLanguage: negotiatedLanguage,
+ langPackInstallPhase: langPackInstallPhase
+ }) : null;
+ })));
+};
+const SecondaryCTA = props => {
+ var _props$content$second;
+
+ let targetElement = props.position ? `secondary_button_${props.position}` : `secondary_button`;
+ const buttonStyling = (_props$content$second = props.content.secondary_button) !== null && _props$content$second !== void 0 && _props$content$second.has_arrow_icon ? `secondary text-link arrow-icon` : `secondary text-link`;
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: props.position ? `secondary-cta ${props.position}` : "secondary-cta"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: props.content[targetElement].text
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", null)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: props.content[targetElement].label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: buttonStyling,
+ value: targetElement,
+ onClick: props.handleAction
+ })));
+};
+const StepsIndicator = props => {
+ let steps = [];
+
+ for (let i = 0; i < props.totalNumberOfScreens; i++) {
+ let className = `${i === props.order ? "current" : ""} ${i < props.order ? "complete" : ""}`;
+ steps.push( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ key: i,
+ className: `indicator ${className}`,
+ role: "presentation"
+ }));
+ }
+
+ return steps;
+};
+const ProgressBar = ({
+ step,
+ previousStep,
+ totalNumberOfScreens
+}) => {
+ const [progress, setProgress] = react__WEBPACK_IMPORTED_MODULE_0___default().useState(previousStep / totalNumberOfScreens);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ // We don't need to hook any dependencies because any time the step changes,
+ // the screen's entire DOM tree will be re-rendered.
+ setProgress(step / totalNumberOfScreens);
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "indicator",
+ role: "presentation",
+ style: {
+ "--progress-bar-progress": `${progress * 100}%`
+ }
+ });
+};
+class WelcomeScreen extends (react__WEBPACK_IMPORTED_MODULE_0___default().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_5__.BASE_PARAMS,
+ utm_term: `${UTMTerm}-screen`
+ };
+
+ if (action.addFlowParams && flowParams) {
+ params = { ...params,
+ ...flowParams
+ };
+ }
+
+ data = { ...data,
+ extraParams: params
+ };
+ } else if (type === "OPEN_URL") {
+ let url = new URL(data.args);
+ (0,_asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_5__.addUtmParams)(url, `${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()
+ };
+ }
+
+ return _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.handleUserAction({
+ type,
+ data
+ });
+ }
+
+ async handleAction(event) {
+ let {
+ props
+ } = this;
+ const value = event.currentTarget.value ?? event.currentTarget.getAttribute("value");
+ const source = event.source || value;
+ let targetContent = props.content[value] || props.content.tiles || props.content.languageSwitcher;
+
+ if (!(targetContent && targetContent.action)) {
+ return;
+ } // Send telemetry before waiting on actions
+
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendActionTelemetry(props.messageId, source, event.name); // Send additional telemetry if a messaging surface like feature callout is
+ // dismissed via the dismiss button. Other causes of dismissal will be
+ // handled separately by the messaging surface's own code.
+
+ if (value === "dismiss_button" && !event.name) {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendDismissTelemetry(props.messageId, source);
+ }
+
+ let {
+ action
+ } = targetContent;
+
+ if (action.collectSelect) {
+ // Populate MULTI_ACTION data actions property with selected checkbox actions from tiles data
+ action.data = {
+ actions: []
+ };
+
+ for (const checkbox of ((_props$content = props.content) === null || _props$content === void 0 ? void 0 : (_props$content$tiles = _props$content.tiles) === null || _props$content$tiles === void 0 ? void 0 : _props$content$tiles.data) ?? []) {
+ var _props$content, _props$content$tiles;
+
+ let checkboxAction;
+
+ if (this.props.activeMultiSelect.includes(checkbox.id)) {
+ checkboxAction = checkbox.checkedAction ?? checkbox.action;
+ } else {
+ checkboxAction = checkbox.uncheckedAction;
+ }
+
+ if (checkboxAction) {
+ action.data.actions.push(checkboxAction);
+ }
+ } // Send telemetry with selected checkbox ids
+
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendActionTelemetry(props.messageId, props.activeMultiSelect, "SELECT_CHECKBOX");
+ }
+
+ let actionResult;
+
+ if (["OPEN_URL", "SHOW_FIREFOX_ACCOUNTS"].includes(action.type)) {
+ actionResult = await this.handleOpenURL(action, props.flowParams, props.UTMTerm);
+ } else if (action.type) {
+ actionResult = await _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.handleUserAction(action);
+
+ if (action.type === "FXA_SIGNIN_FLOW") {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendActionTelemetry(props.messageId, actionResult ? "sign_in" : "sign_in_cancel", "FXA_SIGNIN_FLOW");
+ } // Wait until migration closes to complete the action
+
+
+ const hasMigrate = a => {
+ var _a$data, _a$data$actions;
+
+ return a.type === "SHOW_MIGRATION_WIZARD" || a.type === "MULTI_ACTION" && ((_a$data = a.data) === null || _a$data === void 0 ? void 0 : (_a$data$actions = _a$data.actions) === null || _a$data$actions === void 0 ? void 0 : _a$data$actions.some(hasMigrate));
+ };
+
+ if (hasMigrate(action)) {
+ await window.AWWaitForMigrationClose();
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.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 the action has persistActiveTheme: true, we set the initial theme to the currently active theme
+ // so that it can be reverted to in the event that the user navigates away from the screen
+
+
+ if (action.persistActiveTheme) {
+ this.props.setInitialTheme(this.props.activeTheme);
+ } // `navigate` and `dismiss` can be true/false/undefined, or they can be a
+ // string "actionResult" in which case we should use the actionResult
+ // (boolean resolved by handleUserAction)
+
+
+ const shouldDoBehavior = behavior => behavior === "actionResult" ? actionResult : behavior;
+
+ if (shouldDoBehavior(action.navigate)) {
+ props.navigate();
+ }
+
+ if (shouldDoBehavior(action.dismiss)) {
+ window.AWFinish();
+ }
+ }
+
+ render() {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageProtonScreen__WEBPACK_IMPORTED_MODULE_3__.MultiStageProtonScreen, {
+ content: this.props.content,
+ id: this.props.id,
+ order: this.props.order,
+ previousOrder: this.props.previousOrder,
+ activeTheme: this.props.activeTheme,
+ activeMultiSelect: this.props.activeMultiSelect,
+ setActiveMultiSelect: this.props.setActiveMultiSelect,
+ totalNumberOfScreens: this.props.totalNumberOfScreens,
+ appAndSystemLocaleInfo: this.props.appAndSystemLocaleInfo,
+ negotiatedLanguage: this.props.negotiatedLanguage,
+ langPackInstallPhase: this.props.langPackInstallPhase,
+ handleAction: this.handleAction,
+ messageId: this.props.messageId,
+ isFirstScreen: this.props.isFirstScreen,
+ isLastScreen: this.props.isLastScreen,
+ isSingleScreen: this.props.isSingleScreen,
+ startsWithCorner: this.props.startsWithCorner,
+ autoAdvance: this.props.autoAdvance
+ });
+ }
+
+}
+
+/***/ }),
+/* 5 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "Localized": () => (/* binding */ Localized)
+/* harmony export */ });
+/* 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 CONFIGURABLE_STYLES = ["color", "fontSize", "fontWeight", "letterSpacing", "lineHeight", "marginBlock", "marginInline", "paddingBlock", "paddingInline"];
+const ZAP_SIZE_THRESHOLD = 160;
+/**
+ * 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.
+ * Allows configuring of some styles including zap underline and color.
+ *
+ * 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>
+ * <Localized text={{raw: "Welcome"}}><h1 /></Localized>
+ * output:
+ * <h1>Welcome</h1>
+ */
+
+const Localized = ({
+ text,
+ children
+}) => {
+ // Dynamically determine the size of the zap style.
+ const zapRef = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createRef();
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ const {
+ current
+ } = zapRef;
+ if (current) requestAnimationFrame(() => current === null || current === void 0 ? void 0 : current.classList.replace("short", current.getBoundingClientRect().width > ZAP_SIZE_THRESHOLD ? "long" : "short"));
+ }); // Skip rendering of children with no text.
+
+ if (!text) {
+ return null;
+ } // Allow augmenting existing child container properties.
+
+
+ const props = {
+ children: [],
+ className: "",
+ style: {},
+ ...(children === null || children === void 0 ? void 0 : children.props)
+ }; // Support nested Localized by starting with their children.
+
+ const textNodes = Array.isArray(props.children) ? props.children : [props.children]; // Pick desired fluent or raw/plain text to render.
+
+ if (text.string_id) {
+ // Set the key so React knows not to reuse when switching to plain text.
+ props.key = text.string_id;
+ props["data-l10n-id"] = text.string_id;
+ if (text.args) props["data-l10n-args"] = JSON.stringify(text.args);
+ } else if (text.raw) {
+ textNodes.push(text.raw);
+ } else if (typeof text === "string") {
+ textNodes.push(text);
+ } // Add zap style and content in a way that allows fluent to insert too.
+
+
+ if (text.zap) {
+ props.className += " welcomeZap";
+ textNodes.push( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", {
+ className: "short zap",
+ "data-l10n-name": "zap",
+ ref: zapRef
+ }, text.zap));
+ }
+
+ if (text.aria_label) {
+ props["aria-label"] = text.aria_label;
+ } // Apply certain configurable styles.
+
+
+ CONFIGURABLE_STYLES.forEach(style => {
+ if (text[style] !== undefined) props.style[style] = text[style];
+ });
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().cloneElement( // Provide a default container for the text if necessary.
+ children ?? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", null), props, // Conditionally pass in as void elements can't accept empty array.
+ textNodes.length ? textNodes : null);
+};
+
+/***/ }),
+/* 6 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "MultiStageProtonScreen": () => (/* binding */ MultiStageProtonScreen),
+/* harmony export */ "ProtonScreenActionButtons": () => (/* binding */ ProtonScreenActionButtons),
+/* harmony export */ "ProtonScreen": () => (/* binding */ ProtonScreen)
+/* harmony export */ });
+/* 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__(5);
+/* harmony import */ var _MRColorways__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
+/* harmony import */ var _MobileDownloads__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var _MultiSelect__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9);
+/* harmony import */ var _Themes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(10);
+/* harmony import */ var _MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
+/* harmony import */ var _LanguageSwitcher__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(11);
+/* harmony import */ var _CTAParagraph__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(12);
+/* harmony import */ var _HeroImage__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(13);
+/* harmony import */ var _OnboardingVideo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(14);
+/* harmony import */ var _AdditionalCTA__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(15);
+/* harmony import */ var _EmbeddedMigrationWizard__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(16);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 MultiStageProtonScreen = props => {
+ const {
+ autoAdvance,
+ handleAction,
+ order
+ } = props;
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ if (autoAdvance) {
+ const timer = setTimeout(() => {
+ handleAction({
+ currentTarget: {
+ value: autoAdvance
+ },
+ name: "AUTO_ADVANCE"
+ });
+ }, 20000);
+ return () => clearTimeout(timer);
+ }
+
+ return () => {};
+ }, [autoAdvance, handleAction, order]);
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(ProtonScreen, {
+ content: props.content,
+ id: props.id,
+ order: props.order,
+ activeTheme: props.activeTheme,
+ activeMultiSelect: props.activeMultiSelect,
+ setActiveMultiSelect: props.setActiveMultiSelect,
+ totalNumberOfScreens: props.totalNumberOfScreens,
+ handleAction: props.handleAction,
+ isFirstScreen: props.isFirstScreen,
+ isLastScreen: props.isLastScreen,
+ isSingleScreen: props.isSingleScreen,
+ previousOrder: props.previousOrder,
+ autoAdvance: props.autoAdvance,
+ isRtamo: props.isRtamo,
+ addonName: props.addonName,
+ isTheme: props.isTheme,
+ iconURL: props.iconURL,
+ messageId: props.messageId,
+ negotiatedLanguage: props.negotiatedLanguage,
+ langPackInstallPhase: props.langPackInstallPhase
+ });
+};
+const ProtonScreenActionButtons = props => {
+ var _content$checkbox, _content$additional_b, _content$primary_butt, _content$primary_butt2;
+
+ const {
+ content,
+ addonName
+ } = props;
+ const defaultValue = (_content$checkbox = content.checkbox) === null || _content$checkbox === void 0 ? void 0 : _content$checkbox.defaultValue;
+ const [isChecked, setIsChecked] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(defaultValue || false);
+
+ if (!content.primary_button && !content.secondary_button && !content.additional_button) {
+ return null;
+ }
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `action-buttons ${content.additional_button ? "additional-cta-container" : ""}`,
+ flow: (_content$additional_b = content.additional_button) === null || _content$additional_b === void 0 ? void 0 : _content$additional_b.flow
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: (_content$primary_butt = content.primary_button) === null || _content$primary_butt === void 0 ? void 0 : _content$primary_butt.label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "primary" // Whether or not the checkbox is checked determines which action
+ // should be handled. By setting value here, we indicate to
+ // this.handleAction() where in the content tree it should take
+ // the action to execute from.
+ ,
+ value: isChecked ? "checkbox" : "primary_button",
+ disabled: ((_content$primary_butt2 = content.primary_button) === null || _content$primary_butt2 === void 0 ? void 0 : _content$primary_butt2.disabled) === true,
+ onClick: props.handleAction,
+ "data-l10n-args": addonName ? JSON.stringify({
+ "addon-name": addonName
+ }) : ""
+ })), content.additional_button ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_AdditionalCTA__WEBPACK_IMPORTED_MODULE_11__.AdditionalCTA, {
+ content: content,
+ handleAction: props.handleAction
+ }) : null, content.checkbox ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "checkbox-container"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", {
+ type: "checkbox",
+ id: "action-checkbox",
+ checked: isChecked,
+ onChange: () => {
+ setIsChecked(!isChecked);
+ }
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.checkbox.label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", {
+ htmlFor: "action-checkbox"
+ }))) : null, content.secondary_button ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_6__.SecondaryCTA, {
+ content: content,
+ handleAction: props.handleAction
+ }) : null);
+};
+class ProtonScreen extends (react__WEBPACK_IMPORTED_MODULE_0___default().PureComponent) {
+ componentDidMount() {
+ this.mainContentHeader.focus();
+ }
+
+ getScreenClassName(isFirstScreen, isLastScreen, includeNoodles, isVideoOnboarding) {
+ const screenClass = `screen-${this.props.order % 2 !== 0 ? 1 : 2}`;
+ if (isVideoOnboarding) return "with-video";
+ return `${isFirstScreen ? `dialog-initial` : ``} ${isLastScreen ? `dialog-last` : ``} ${includeNoodles ? `with-noodles` : ``} ${screenClass}`;
+ }
+
+ renderLogo({
+ imageURL = "chrome://branding/content/about-logo.svg",
+ darkModeImageURL,
+ reducedMotionImageURL,
+ darkModeReducedMotionImageURL,
+ alt = "",
+ height
+ }) {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("picture", {
+ className: "logo-container"
+ }, darkModeReducedMotionImageURL ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("source", {
+ srcSet: darkModeReducedMotionImageURL,
+ media: "(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)"
+ }) : null, darkModeImageURL ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("source", {
+ srcSet: darkModeImageURL,
+ media: "(prefers-color-scheme: dark)"
+ }) : null, reducedMotionImageURL ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("source", {
+ srcSet: reducedMotionImageURL,
+ media: "(prefers-reduced-motion: reduce)"
+ }) : null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ className: "brand-logo",
+ style: {
+ height
+ },
+ src: imageURL,
+ alt: alt,
+ role: alt ? null : "presentation"
+ }));
+ }
+
+ renderContentTiles() {
+ const {
+ content
+ } = this.props;
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, content.tiles && content.tiles.type === "colorway" && content.tiles.colorways ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MRColorways__WEBPACK_IMPORTED_MODULE_2__.Colorways, {
+ content: content,
+ activeTheme: this.props.activeTheme,
+ handleAction: this.props.handleAction
+ }) : null, content.tiles && content.tiles.type === "theme" && content.tiles.data ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Themes__WEBPACK_IMPORTED_MODULE_5__.Themes, {
+ content: content,
+ activeTheme: this.props.activeTheme,
+ handleAction: this.props.handleAction
+ }) : null, content.tiles && content.tiles.type === "mobile_downloads" && content.tiles.data ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MobileDownloads__WEBPACK_IMPORTED_MODULE_3__.MobileDownloads, {
+ data: content.tiles.data,
+ handleAction: this.props.handleAction
+ }) : null, content.tiles && content.tiles.type === "multiselect" && content.tiles.data ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiSelect__WEBPACK_IMPORTED_MODULE_4__.MultiSelect, {
+ content: content,
+ activeMultiSelect: this.props.activeMultiSelect,
+ setActiveMultiSelect: this.props.setActiveMultiSelect,
+ handleAction: this.props.handleAction
+ }) : null, content.tiles && content.tiles.type === "migration-wizard" ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_EmbeddedMigrationWizard__WEBPACK_IMPORTED_MODULE_12__.EmbeddedMigrationWizard, {
+ handleAction: this.props.handleAction
+ }) : null);
+ }
+
+ renderNoodles() {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "noodle orange-L"
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "noodle purple-C"
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "noodle solid-L"
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "noodle outline-L"
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "noodle yellow-circle"
+ }));
+ }
+
+ renderLanguageSwitcher() {
+ return this.props.content.languageSwitcher ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_LanguageSwitcher__WEBPACK_IMPORTED_MODULE_7__.LanguageSwitcher, {
+ content: this.props.content,
+ handleAction: this.props.handleAction,
+ negotiatedLanguage: this.props.negotiatedLanguage,
+ langPackInstallPhase: this.props.langPackInstallPhase,
+ messageId: this.props.messageId
+ }) : null;
+ }
+
+ renderDismissButton() {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "dismiss-button",
+ onClick: this.props.handleAction,
+ value: "dismiss_button",
+ "data-l10n-id": "spotlight-dialog-close-button"
+ });
+ }
+
+ renderStepsIndicator() {
+ const currentStep = (this.props.order ?? 0) + 1;
+ const previousStep = (this.props.previousOrder ?? -1) + 1;
+ const {
+ content,
+ totalNumberOfScreens: total
+ } = this.props;
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ id: "steps",
+ className: `steps${content.progress_bar ? " progress-bar" : ""}`,
+ "data-l10n-id": "onboarding-welcome-steps-indicator-label",
+ "data-l10n-args": JSON.stringify({
+ current: currentStep,
+ total: total ?? 0
+ }),
+ "data-l10n-attrs": "aria-label",
+ role: "progressbar",
+ "aria-valuenow": currentStep,
+ "aria-valuemin": 1,
+ "aria-valuemax": total
+ }, content.progress_bar ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_6__.ProgressBar, {
+ step: currentStep,
+ previousStep: previousStep,
+ totalNumberOfScreens: total
+ }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_6__.StepsIndicator, {
+ order: this.props.order,
+ totalNumberOfScreens: total
+ }));
+ }
+
+ renderSecondarySection(content) {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "section-secondary",
+ style: content.background ? {
+ background: content.background,
+ "--mr-secondary-background-position-y": content.split_narrow_bkg_position
+ } : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.image_alt_text
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "sr-only image-alt",
+ role: "img"
+ })), content.hero_image ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_HeroImage__WEBPACK_IMPORTED_MODULE_9__.HeroImage, {
+ url: content.hero_image.url
+ }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "message-text"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "spacer-top"
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.hero_text
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h1", null)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "spacer-bottom"
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.help_text
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", {
+ className: "attrib-text"
+ }))));
+ }
+
+ render() {
+ var _content$tiles, _this$props$appAndSys, _this$props$messageId;
+
+ const {
+ autoAdvance,
+ content,
+ isRtamo,
+ isTheme,
+ isFirstScreen,
+ isLastScreen,
+ isSingleScreen
+ } = this.props;
+ const includeNoodles = content.has_noodles; // The default screen position is "center"
+
+ const isCenterPosition = content.position === "center" || !content.position;
+ const hideStepsIndicator = autoAdvance || (content === null || content === void 0 ? void 0 : content.video_container) || isSingleScreen;
+ const textColorClass = content.text_color ? `${content.text_color}-text` : ""; // Assign proton screen style 'screen-1' or 'screen-2' to centered screens
+ // by checking if screen order is even or odd.
+
+ const screenClassName = isCenterPosition ? this.getScreenClassName(isFirstScreen, isLastScreen, includeNoodles, content === null || content === void 0 ? void 0 : content.video_container) : "";
+ const isEmbeddedMigration = ((_content$tiles = content.tiles) === null || _content$tiles === void 0 ? void 0 : _content$tiles.type) === "migration-wizard";
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("main", {
+ className: `screen ${this.props.id || ""}
+ ${screenClassName} ${textColorClass}`,
+ role: "alertdialog",
+ pos: content.position || "center",
+ tabIndex: "-1",
+ "aria-labelledby": "mainContentHeader",
+ ref: input => {
+ this.mainContentHeader = input;
+ }
+ }, isCenterPosition ? null : this.renderSecondarySection(content), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `section-main ${isEmbeddedMigration ? "embedded-migration" : ""}`,
+ role: "document"
+ }, content.secondary_button_top ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_6__.SecondaryCTA, {
+ content: content,
+ handleAction: this.props.handleAction,
+ position: "top"
+ }) : null, includeNoodles ? this.renderNoodles() : null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `main-content ${hideStepsIndicator ? "no-steps" : ""}`,
+ style: content.background && isCenterPosition ? {
+ background: content.background
+ } : {}
+ }, content.logo ? this.renderLogo(content.logo) : null, isRtamo ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "rtamo-icon"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ className: `${isTheme ? "rtamo-theme-icon" : "brand-logo"}`,
+ src: this.props.iconURL,
+ role: "presentation",
+ alt: ""
+ })) : null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "main-content-inner"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `welcome-text ${content.title_style || ""}`
+ }, content.title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.title
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h1", {
+ id: "mainContentHeader"
+ })) : null, content.subtitle ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.subtitle
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h2", {
+ "data-l10n-args": JSON.stringify({
+ "addon-name": this.props.addonName,
+ ...((_this$props$appAndSys = this.props.appAndSystemLocaleInfo) === null || _this$props$appAndSys === void 0 ? void 0 : _this$props$appAndSys.displayNames)
+ }),
+ "aria-flowto": (_this$props$messageId = this.props.messageId) !== null && _this$props$messageId !== void 0 && _this$props$messageId.includes("FEATURE_TOUR") ? "steps" : ""
+ })) : null, content.cta_paragraph ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_CTAParagraph__WEBPACK_IMPORTED_MODULE_8__.CTAParagraph, {
+ content: content.cta_paragraph,
+ handleAction: this.props.handleAction
+ }) : null), content.video_container ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_OnboardingVideo__WEBPACK_IMPORTED_MODULE_10__.OnboardingVideo, {
+ content: content.video_container,
+ handleAction: this.props.handleAction
+ }) : null, this.renderContentTiles(), this.renderLanguageSwitcher(), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(ProtonScreenActionButtons, {
+ content: content,
+ addonName: this.props.addonName,
+ handleAction: this.props.handleAction
+ })), !hideStepsIndicator ? this.renderStepsIndicator() : null), content.dismiss_button ? this.renderDismissButton() : null));
+ }
+
+}
+
+/***/ }),
+/* 7 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "ColorwayDescription": () => (/* binding */ ColorwayDescription),
+/* harmony export */ "computeColorWay": () => (/* binding */ computeColorWay),
+/* harmony export */ "computeVariationIndex": () => (/* binding */ computeVariationIndex),
+/* harmony export */ "Colorways": () => (/* binding */ Colorways)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const ColorwayDescription = props => {
+ const {
+ colorway
+ } = props;
+
+ if (!colorway) {
+ return null;
+ }
+
+ const {
+ label,
+ description
+ } = colorway;
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: description
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "colorway-text",
+ "data-l10n-args": JSON.stringify({
+ colorwayName: label
+ })
+ }));
+}; // Return colorway as "default" for default theme variations Automatic, Light, Dark,
+// Alpenglow theme and legacy colorways which is not supported in Colorway picker.
+// For themes other then default, theme names exist in
+// format colorway-variationId inside LIGHT_WEIGHT_THEMES in AboutWelcomeParent
+
+function computeColorWay(themeName, systemVariations) {
+ return !themeName || themeName === "alpenglow" || systemVariations.includes(themeName) ? "default" : themeName.split("-")[0];
+} // Set variationIndex based off activetheme value e.g. 'light', 'expressionist-soft'
+
+function computeVariationIndex(themeName, systemVariations, variations, defaultVariationIndex) {
+ // Check if themeName is in systemVariations, if yes choose variationIndex by themeName
+ let index = systemVariations.findIndex(theme => theme === themeName);
+
+ if (index >= 0) {
+ return index;
+ } // If themeName is one of the colorways, select variation index from colorways
+
+
+ let variation = themeName === null || themeName === void 0 ? void 0 : themeName.split("-")[1];
+ index = variations.findIndex(element => element === variation);
+
+ if (index >= 0) {
+ return index;
+ }
+
+ return defaultVariationIndex;
+}
+function Colorways(props) {
+ let {
+ colorways,
+ darkVariation,
+ defaultVariationIndex,
+ systemVariations,
+ variations
+ } = props.content.tiles;
+ let hasReverted = false; // Active theme id from JSON e.g. "expressionist"
+
+ const activeId = computeColorWay(props.activeTheme, systemVariations);
+ const [colorwayId, setState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(activeId);
+ const [variationIndex, setVariationIndex] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(defaultVariationIndex);
+
+ function revertToDefaultTheme() {
+ if (hasReverted) return; // Spoofing an event with current target value of "navigate_away"
+ // helps the handleAction method to read the colorways theme as "revert"
+ // which causes the initial theme to be activated.
+ // The "navigate_away" action is set in content in the colorways screen JSON config.
+ // Any value in the JSON for theme will work, provided it is not `<event>`.
+
+ const event = {
+ currentTarget: {
+ value: "navigate_away"
+ }
+ };
+ props.handleAction(event);
+ hasReverted = true;
+ } // Revert to default theme if the user navigates away from the page or spotlight modal
+ // before clicking on the primary button to officially set theme.
+
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ addEventListener("beforeunload", revertToDefaultTheme);
+ addEventListener("pagehide", revertToDefaultTheme);
+ return () => {
+ removeEventListener("beforeunload", revertToDefaultTheme);
+ removeEventListener("pagehide", revertToDefaultTheme);
+ };
+ }); // Update state any time activeTheme changes.
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ setState(computeColorWay(props.activeTheme, systemVariations));
+ setVariationIndex(computeVariationIndex(props.activeTheme, systemVariations, variations, defaultVariationIndex)); // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [props.activeTheme]); //select a random colorway
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ //We don't want the default theme to be selected
+ const randomIndex = Math.floor(Math.random() * (colorways.length - 1)) + 1;
+ const randomColorwayId = colorways[randomIndex].id; // Change the variation to be the dark variation if configured and dark.
+ // Additional colorway changes will remain dark while system is unchanged.
+
+ if (darkVariation !== undefined && window.matchMedia("(prefers-color-scheme: dark)").matches) {
+ variations[variationIndex] = variations[darkVariation];
+ }
+
+ const value = `${randomColorwayId}-${variations[variationIndex]}`;
+ props.handleAction({
+ currentTarget: {
+ value
+ }
+ }); // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "tiles-theme-container"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("fieldset", {
+ className: "tiles-theme-section"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: props.content.subtitle
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("legend", {
+ className: "sr-only"
+ })), colorways.map(({
+ id,
+ label,
+ tooltip
+ }) => /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ key: id + label,
+ text: typeof tooltip === "object" ? tooltip : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", {
+ className: "theme",
+ title: label,
+ "data-l10n-args": JSON.stringify({
+ colorwayName: label
+ })
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: typeof tooltip === "object" ? tooltip : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", {
+ className: "sr-only colorway label",
+ id: `${id}-label`,
+ "data-l10n-args": JSON.stringify({
+ colorwayName: tooltip
+ })
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: typeof label === "object" ? label : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", {
+ type: "radio",
+ "data-colorway": id,
+ name: "theme",
+ value: id === "default" ? systemVariations[variationIndex] : `${id}-${variations[variationIndex]}`,
+ checked: colorwayId === id,
+ className: "sr-only input",
+ onClick: props.handleAction,
+ "data-l10n-args": JSON.stringify({
+ colorwayName: label
+ }),
+ "aria-labelledby": `${id}-label`
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `icon colorway ${colorwayId === id ? "selected" : ""} ${id}`
+ })))))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(ColorwayDescription, {
+ colorway: colorways.find(colorway => colorway.id === activeId)
+ }));
+}
+
+/***/ }),
+/* 8 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "MarketplaceButtons": () => (/* binding */ MarketplaceButtons),
+/* harmony export */ "MobileDownloads": () => (/* binding */ MobileDownloads)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const MarketplaceButtons = props => {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("ul", {
+ className: "mobile-download-buttons"
+ }, props.buttons.includes("ios") ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", {
+ className: "ios"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ "data-l10n-id": "spotlight-ios-marketplace-button",
+ value: "ios",
+ onClick: props.handleAction
+ })) : null, props.buttons.includes("android") ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("li", {
+ className: "android"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ "data-l10n-id": "spotlight-android-marketplace-button",
+ value: "android",
+ onClick: props.handleAction
+ })) : null);
+};
+const MobileDownloads = props => {
+ const {
+ QR_code: QRCode
+ } = props.data;
+ const showEmailLink = props.data.email && window.AWSendToDeviceEmailsSupported();
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "mobile-downloads"
+ }, QRCode ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ "data-l10n-id": QRCode.alt_text.string_id ? QRCode.alt_text.string_id : null,
+ className: "qr-code-image",
+ alt: typeof QRCode.alt_text === "string" ? QRCode.alt_text : "",
+ src: QRCode.image_url
+ }) : null, showEmailLink ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: props.data.email.link_text
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "email-link",
+ value: "email_link",
+ onClick: props.handleAction
+ }))) : null, props.data.marketplace_buttons ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(MarketplaceButtons, {
+ buttons: props.data.marketplace_buttons,
+ handleAction: props.handleAction
+ }) : null);
+};
+
+/***/ }),
+/* 9 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "MultiSelect": () => (/* binding */ MultiSelect)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const MultiSelect = props => {
+ let handleChange = event => {
+ if (event.currentTarget.checked) {
+ props.setActiveMultiSelect([...props.activeMultiSelect, event.currentTarget.value]);
+ } else {
+ props.setActiveMultiSelect(props.activeMultiSelect.filter(id => id !== event.currentTarget.value));
+ }
+ };
+
+ let {
+ data
+ } = props.content.tiles; // When screen renders for first time, update state
+ // with checkbox ids that has defaultvalue true
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ if (!props.activeMultiSelect) {
+ props.setActiveMultiSelect(data.map(item => item.defaultValue && item.id).filter(item => !!item));
+ } // eslint-disable-next-line react-hooks/exhaustive-deps
+
+ }, []);
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "multi-select-container"
+ }, props.content.tiles.data.map(({
+ label,
+ id
+ }) => {
+ var _props$activeMultiSel;
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ key: id + label,
+ className: "checkbox-container multi-select-item"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", {
+ type: "checkbox",
+ id: id,
+ value: id,
+ checked: (_props$activeMultiSel = props.activeMultiSelect) === null || _props$activeMultiSel === void 0 ? void 0 : _props$activeMultiSel.includes(id),
+ onChange: handleChange
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", {
+ htmlFor: id
+ })));
+ }));
+};
+
+/***/ }),
+/* 10 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "Themes": () => (/* binding */ Themes)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const Themes = props => {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "tiles-theme-container"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("fieldset", {
+ className: "tiles-theme-section"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: props.content.subtitle
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("legend", {
+ className: "sr-only"
+ })), props.content.tiles.data.map(({
+ theme,
+ label,
+ tooltip,
+ description
+ }) => /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ key: theme + label,
+ text: typeof tooltip === "object" ? tooltip : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("label", {
+ className: "theme",
+ title: theme + label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: typeof description === "object" ? description : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", {
+ type: "radio",
+ value: theme,
+ name: "theme",
+ checked: theme === props.activeTheme,
+ className: "sr-only input",
+ onClick: props.handleAction
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: `icon ${theme === props.activeTheme ? " selected" : ""} ${theme}`
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "text"
+ }))))))));
+};
+
+/***/ }),
+/* 11 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "useLanguageSwitcher": () => (/* binding */ useLanguageSwitcher),
+/* harmony export */ "LanguageSwitcher": () => (/* binding */ LanguageSwitcher)
+/* harmony export */ });
+/* 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__(5);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(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/. */
+
+
+
+/**
+ * The language switcher implements a hook that should be placed at a higher level
+ * than the actual language switcher component, as it needs to preemptively fetch
+ * and install langpacks for the user if there is a language mismatch screen.
+ */
+
+function useLanguageSwitcher(appAndSystemLocaleInfo, screens, screenIndex, setScreenIndex) {
+ const languageMismatchScreenIndex = screens.findIndex(({
+ id
+ }) => id === "AW_LANGUAGE_MISMATCH");
+ const screen = screens[languageMismatchScreenIndex]; // Ensure fluent messages have the negotiatedLanguage args set, as they are rendered
+ // before the negotiatedLanguage is known. If the arg isn't present then Firefox will
+ // crash in development mode.
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ var _screen$content;
+
+ if (screen !== null && screen !== void 0 && (_screen$content = screen.content) !== null && _screen$content !== void 0 && _screen$content.languageSwitcher) {
+ for (const text of Object.values(screen.content.languageSwitcher)) {
+ if (text !== null && text !== void 0 && text.args && text.args.negotiatedLanguage === undefined) {
+ text.args.negotiatedLanguage = "";
+ }
+ }
+ }
+ }, [screen]); // If there is a mismatch, then Firefox can negotiate a better langpack to offer
+ // the user.
+
+ const [negotiatedLanguage, setNegotiatedLanguage] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function getNegotiatedLanguage() {
+ if (!appAndSystemLocaleInfo) {
+ return;
+ }
+
+ if (appAndSystemLocaleInfo.matchType !== "language-mismatch") {
+ // There is no language mismatch, so there is no need to negotiate a langpack.
+ return;
+ }
+
+ (async () => {
+ const {
+ langPack,
+ langPackDisplayName
+ } = await window.AWNegotiateLangPackForLanguageMismatch(appAndSystemLocaleInfo);
+
+ if (langPack) {
+ setNegotiatedLanguage({
+ langPackDisplayName,
+ appDisplayName: appAndSystemLocaleInfo.displayNames.appLanguage,
+ langPack,
+ requestSystemLocales: [langPack.target_locale, appAndSystemLocaleInfo.appLocaleRaw],
+ originalAppLocales: [appAndSystemLocaleInfo.appLocaleRaw]
+ });
+ } else {
+ setNegotiatedLanguage({
+ langPackDisplayName: null,
+ appDisplayName: null,
+ langPack: null,
+ requestSystemLocales: null
+ });
+ }
+ })();
+ }, [appAndSystemLocaleInfo]);
+ /**
+ * @type {
+ * "before-installation"
+ * | "installing"
+ * | "installed"
+ * | "installation-error"
+ * | "none-available"
+ * }
+ */
+
+ const [langPackInstallPhase, setLangPackInstallPhase] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)("before-installation");
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function ensureLangPackInstalled() {
+ if (!negotiatedLanguage) {
+ // There are no negotiated languages to download yet.
+ return;
+ }
+
+ setLangPackInstallPhase("installing");
+ window.AWEnsureLangPackInstalled(negotiatedLanguage, screen === null || screen === void 0 ? void 0 : screen.content).then(content => {
+ // Update screen content with strings that might have changed.
+ screen.content = content;
+ setLangPackInstallPhase("installed");
+ }, error => {
+ console.error(error);
+ setLangPackInstallPhase("installation-error");
+ });
+ }, [negotiatedLanguage]);
+ const [languageFilteredScreens, setLanguageFilteredScreens] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(screens);
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function filterScreen() {
+ // Remove the language screen if it exists (already removed for no live
+ // reload) and we either don't-need-to or can't switch.
+ if (screen && ((appAndSystemLocaleInfo === null || appAndSystemLocaleInfo === void 0 ? void 0 : appAndSystemLocaleInfo.matchType) !== "language-mismatch" || (negotiatedLanguage === null || negotiatedLanguage === void 0 ? void 0 : negotiatedLanguage.langPack) === null)) {
+ if (screenIndex > languageMismatchScreenIndex) {
+ setScreenIndex(screenIndex - 1);
+ }
+
+ setLanguageFilteredScreens(screens.filter(s => s.id !== "AW_LANGUAGE_MISMATCH"));
+ } else {
+ setLanguageFilteredScreens(screens);
+ }
+ }, [screens, negotiatedLanguage]);
+ return {
+ negotiatedLanguage,
+ langPackInstallPhase,
+ languageFilteredScreens
+ };
+}
+/**
+ * The language switcher is a separate component as it needs to perform some asynchronous
+ * network actions such as retrieving the list of langpacks available, and downloading
+ * a new langpack. On a fast connection, this won't be noticeable, but on slow or unreliable
+ * internet this may fail for a user.
+ */
+
+function LanguageSwitcher(props) {
+ const {
+ content,
+ handleAction,
+ negotiatedLanguage,
+ langPackInstallPhase,
+ messageId
+ } = props;
+ const [isAwaitingLangpack, setIsAwaitingLangpack] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false); // Determine the status of the langpack installation.
+
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ if (isAwaitingLangpack && langPackInstallPhase !== "installing") {
+ window.AWSetRequestedLocales(negotiatedLanguage.requestSystemLocales);
+ requestAnimationFrame(() => {
+ handleAction( // Simulate the click event.
+ {
+ currentTarget: {
+ value: "download_complete"
+ }
+ });
+ });
+ }
+ }, [isAwaitingLangpack, langPackInstallPhase]);
+ let showWaitingScreen = false;
+ let showPreloadingScreen = false;
+ let showReadyScreen = false;
+
+ if (isAwaitingLangpack && langPackInstallPhase !== "installed") {
+ showWaitingScreen = true;
+ } else if (langPackInstallPhase === "before-installation") {
+ showPreloadingScreen = true;
+ } else {
+ showReadyScreen = true;
+ } // Use {display: "none"} rather than if statements to prevent layout thrashing with
+ // the localized text elements rendering as blank, then filling in the text.
+
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "action-buttons language-switcher-container"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ style: {
+ display: showPreloadingScreen ? "block" : "none"
+ }
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "primary",
+ value: "primary_button",
+ disabled: true,
+ type: "button"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ className: "language-loader",
+ src: "chrome://browser/skin/tabbrowser/tab-connecting.png",
+ alt: ""
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.waiting
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "secondary-cta"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.skip
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ value: "decline_waiting",
+ type: "button",
+ className: "secondary text-link arrow-icon",
+ onClick: handleAction
+ })))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ style: {
+ display: showWaitingScreen ? "block" : "none"
+ }
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "primary",
+ value: "primary_button",
+ disabled: true,
+ type: "button"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ className: "language-loader",
+ src: "chrome://browser/skin/tabbrowser/tab-connecting.png",
+ alt: ""
+ }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.downloading
+ })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "secondary-cta"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.cancel
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ type: "button",
+ className: "secondary text-link",
+ onClick: () => {
+ setIsAwaitingLangpack(false);
+ handleAction({
+ currentTarget: {
+ value: "cancel_waiting"
+ }
+ });
+ }
+ })))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ style: {
+ display: showReadyScreen ? "block" : "none"
+ }
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: "primary",
+ value: "primary_button",
+ onClick: () => {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendActionTelemetry(messageId, "download_langpack");
+ setIsAwaitingLangpack(true);
+ }
+ }, content.languageSwitcher.switch ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.switch
+ }) : // This is the localized name from the Intl.DisplayNames API.
+ negotiatedLanguage === null || negotiatedLanguage === void 0 ? void 0 : negotiatedLanguage.langPackDisplayName)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ type: "button",
+ className: "primary",
+ value: "decline",
+ onClick: event => {
+ window.AWSetRequestedLocales(negotiatedLanguage.originalAppLocales);
+ handleAction(event);
+ }
+ }, content.languageSwitcher.continue ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.languageSwitcher.continue
+ }) : // This is the localized name from the Intl.DisplayNames API.
+ negotiatedLanguage === null || negotiatedLanguage === void 0 ? void 0 : negotiatedLanguage.appDisplayName))));
+}
+
+/***/ }),
+/* 12 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "CTAParagraph": () => (/* binding */ CTAParagraph)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const CTAParagraph = props => {
+ const {
+ content,
+ handleAction
+ } = props;
+
+ if (!(content !== null && content !== void 0 && content.text)) {
+ return null;
+ }
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("h2", {
+ className: "cta-paragraph"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: content.text
+ }, content.text.string_name && typeof handleAction === "function" ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("span", {
+ "data-l10n-id": content.text.string_id,
+ onClick: handleAction,
+ onKeyUp: event => ["Enter", " "].includes(event.key) ? handleAction(event) : null,
+ value: "cta_paragraph",
+ role: "button",
+ tabIndex: "0"
+ }, " ", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("a", {
+ role: "button",
+ tabIndex: "0",
+ "data-l10n-name": content.text.string_name
+ }, " ")) : null));
+};
+
+/***/ }),
+/* 13 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "HeroImage": () => (/* binding */ HeroImage)
+/* harmony export */ });
+/* 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 HeroImage = props => {
+ const {
+ height,
+ url,
+ alt
+ } = props;
+
+ if (!url) {
+ return null;
+ }
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "hero-image"
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("img", {
+ style: height ? {
+ height
+ } : null,
+ src: url,
+ alt: alt || "",
+ role: alt ? null : "presentation"
+ }));
+};
+
+/***/ }),
+/* 14 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "OnboardingVideo": () => (/* binding */ OnboardingVideo)
+/* harmony export */ });
+/* 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 OnboardingVideo = props => {
+ const vidUrl = props.content.video_url;
+ const autoplay = props.content.autoPlay;
+
+ const handleVideoAction = event => {
+ props.handleAction({
+ currentTarget: {
+ value: event
+ }
+ });
+ };
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("video", {
+ // eslint-disable-line jsx-a11y/media-has-caption
+ controls: true,
+ autoPlay: autoplay,
+ src: vidUrl,
+ width: "604px",
+ height: "340px",
+ onPlay: () => handleVideoAction("video_start"),
+ onEnded: () => handleVideoAction("video_end")
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("source", {
+ src: vidUrl
+ })));
+};
+
+/***/ }),
+/* 15 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "AdditionalCTA": () => (/* binding */ AdditionalCTA)
+/* harmony export */ });
+/* 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__(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/. */
+
+
+const AdditionalCTA = ({
+ content,
+ handleAction
+}) => {
+ var _content$additional_b, _content$additional_b4, _content$additional_b5;
+
+ let buttonStyle = "";
+
+ if (!((_content$additional_b = content.additional_button) !== null && _content$additional_b !== void 0 && _content$additional_b.style)) {
+ buttonStyle = "primary";
+ } else {
+ var _content$additional_b2, _content$additional_b3;
+
+ buttonStyle = ((_content$additional_b2 = content.additional_button) === null || _content$additional_b2 === void 0 ? void 0 : _content$additional_b2.style) === "link" ? "cta-link" : (_content$additional_b3 = content.additional_button) === null || _content$additional_b3 === void 0 ? void 0 : _content$additional_b3.style;
+ }
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__.Localized, {
+ text: (_content$additional_b4 = content.additional_button) === null || _content$additional_b4 === void 0 ? void 0 : _content$additional_b4.label
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", {
+ className: `${buttonStyle} additional-cta`,
+ onClick: handleAction,
+ value: "additional_button",
+ disabled: ((_content$additional_b5 = content.additional_button) === null || _content$additional_b5 === void 0 ? void 0 : _content$additional_b5.disabled) === true
+ }));
+};
+
+/***/ }),
+/* 16 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "EmbeddedMigrationWizard": () => (/* binding */ EmbeddedMigrationWizard)
+/* harmony export */ });
+/* 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 EmbeddedMigrationWizard = ({
+ handleAction
+}) => {
+ const ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)();
+ (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
+ const handleBeginMigration = () => {
+ handleAction({
+ currentTarget: {
+ value: "migrate_start"
+ },
+ source: "primary_button"
+ });
+ };
+
+ const handleClose = () => {
+ handleAction({
+ currentTarget: {
+ value: "migrate_close"
+ }
+ });
+ };
+
+ const {
+ current
+ } = ref;
+ current === null || current === void 0 ? void 0 : current.addEventListener("MigrationWizard:BeginMigration", handleBeginMigration);
+ current === null || current === void 0 ? void 0 : current.addEventListener("MigrationWizard:Close", handleClose);
+ return () => {
+ current === null || current === void 0 ? void 0 : current.removeEventListener("MigrationWizard:BeginMigration", handleBeginMigration);
+ current === null || current === void 0 ? void 0 : current.removeEventListener("MigrationWizard:Close", handleClose);
+ };
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("migration-wizard", {
+ "auto-request-state": "",
+ ref: ref
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("panel-list", null));
+};
+
+/***/ }),
+/* 17 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "BASE_PARAMS": () => (/* binding */ BASE_PARAMS),
+/* harmony export */ "addUtmParams": () => (/* binding */ addUtmParams)
+/* harmony export */ });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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);
+ }
+
+ for (let [key, value] of Object.entries(BASE_PARAMS)) {
+ if (!returnUrl.searchParams.has(key)) {
+ returnUrl.searchParams.append(key, value);
+ }
+ }
+
+ returnUrl.searchParams.append("utm_term", utmTerm);
+ return returnUrl;
+}
+
+/***/ }),
+/* 18 */
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "ReturnToAMO": () => (/* binding */ ReturnToAMO)
+/* harmony export */ });
+/* 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__(3);
+/* harmony import */ var _MultiStageProtonScreen__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6);
+/* harmony import */ var _asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(17);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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().PureComponent) {
+ constructor(props) {
+ super(props);
+ this.fetchFlowParams = this.fetchFlowParams.bind(this);
+ this.handleAction = this.handleAction.bind(this);
+ }
+
+ async fetchFlowParams() {
+ if (this.props.metricsFlowUri) {
+ this.setState({
+ flowParams: await _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__.AboutWelcomeUtils.fetchFlowParams(this.props.metricsFlowUri)
+ });
+ }
+ }
+
+ componentDidUpdate() {
+ this.fetchFlowParams();
+ }
+
+ handleAction(event) {
+ const {
+ content,
+ message_id,
+ url,
+ utm_term
+ } = this.props;
+ let {
+ action,
+ source_id
+ } = content[event.currentTarget.value];
+ let {
+ type,
+ data
+ } = action;
+
+ if (type === "INSTALL_ADDON_FROM_URL") {
+ if (!data) {
+ return;
+ } // Set add-on url in action.data.url property from JSON
+
+
+ data = { ...data,
+ url
+ };
+ } else if (type === "SHOW_FIREFOX_ACCOUNTS") {
+ let params = { ..._asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_3__.BASE_PARAMS,
+ utm_term: `aboutwelcome-${utm_term}-screen`
+ };
+
+ if (action.addFlowParams && this.state.flowParams) {
+ params = { ...params,
+ ...this.state.flowParams
+ };
+ }
+
+ data = { ...data,
+ extraParams: params
+ };
+ }
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__.AboutWelcomeUtils.handleUserAction({
+ type,
+ data
+ });
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__.AboutWelcomeUtils.sendActionTelemetry(message_id, source_id);
+ }
+
+ render() {
+ var _this$props$themeScre;
+
+ const {
+ content,
+ type
+ } = this.props;
+
+ if (!content) {
+ return null;
+ }
+
+ if (content !== null && content !== void 0 && content.primary_button.label) {
+ content.primary_button.label.string_id = type.includes("theme") ? "return-to-amo-add-theme-label" : "mr1-return-to-amo-add-extension-label";
+ } // 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 /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", {
+ className: "outer-wrapper onboardingContainer proton",
+ style: content.backdrop ? {
+ background: content.backdrop
+ } : {}
+ }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_MultiStageProtonScreen__WEBPACK_IMPORTED_MODULE_2__.MultiStageProtonScreen, {
+ content: content,
+ isRtamo: true,
+ isTheme: type.includes("theme"),
+ id: this.props.message_id,
+ order: this.props.order || 0,
+ totalNumberOfScreens: 1,
+ isSingleScreen: true,
+ autoAdvance: this.props.auto_advance,
+ iconURL: type.includes("theme") ? (_this$props$themeScre = this.props.themeScreenshots[0]) === null || _this$props$themeScre === void 0 ? void 0 : _this$props$themeScre.url : this.props.iconURL,
+ addonName: this.props.name,
+ handleAction: this.handleAction
+ }));
+ }
+
+}
+ReturnToAMO.defaultProps = _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_RTAMO_CONTENT;
+
+/***/ })
+/******/ ]);
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ var cachedModule = __webpack_module_cache__[moduleId];
+/******/ if (cachedModule !== undefined) {
+/******/ return cachedModule.exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/ /* webpack/runtime/compat get default export */
+/******/ (() => {
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = (module) => {
+/******/ var getter = module && module.__esModule ?
+/******/ () => (module['default']) :
+/******/ () => (module);
+/******/ __webpack_require__.d(getter, { a: getter });
+/******/ return getter;
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/define property getters */
+/******/ (() => {
+/******/ // define getter functions for harmony exports
+/******/ __webpack_require__.d = (exports, definition) => {
+/******/ for(var key in definition) {
+/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
+/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
+/******/ }
+/******/ }
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/hasOwnProperty shorthand */
+/******/ (() => {
+/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
+/******/ })();
+/******/
+/******/ /* webpack/runtime/make namespace object */
+/******/ (() => {
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = (exports) => {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/ })();
+/******/
+/************************************************************************/
+var __webpack_exports__ = {};
+// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
+(() => {
+__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 _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
+/* harmony import */ var _components_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
+/* harmony import */ var _components_ReturnToAMO__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(18);
+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().PureComponent) {
+ constructor(props) {
+ super(props);
+ this.state = {
+ metricsFlowUri: null
+ };
+ this.fetchFxAFlowUri = this.fetchFxAFlowUri.bind(this);
+ }
+
+ async fetchFxAFlowUri() {
+ var _window$AWGetFxAMetri, _window;
+
+ this.setState({
+ metricsFlowUri: await ((_window$AWGetFxAMetri = (_window = window).AWGetFxAMetricsFlowURI) === null || _window$AWGetFxAMetri === void 0 ? void 0 : _window$AWGetFxAMetri.call(_window))
+ });
+ }
+
+ componentDidMount() {
+ if (!this.props.skipFxA) {
+ this.fetchFxAFlowUri();
+ } // Record impression with performance data after allowing the page to load
+
+
+ const recordImpression = domState => {
+ const {
+ domComplete,
+ domInteractive
+ } = performance.getEntriesByType("navigation").pop();
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_2__.AboutWelcomeUtils.sendImpressionTelemetry(this.props.messageId, {
+ domComplete,
+ domInteractive,
+ mountStart: performance.getEntriesByName("mount").pop().startTime,
+ domState,
+ source: this.props.UTMTerm
+ });
+ };
+
+ 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);
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+
+ if (props.template === "return_to_amo") {
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ReturnToAMO__WEBPACK_IMPORTED_MODULE_4__.ReturnToAMO, {
+ message_id: props.messageId,
+ type: props.type,
+ name: props.name,
+ url: props.url,
+ iconURL: props.iconURL,
+ themeScreenshots: props.screenshots,
+ metricsFlowUri: this.state.metricsFlowUri
+ });
+ }
+
+ return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_3__.MultiStageAboutWelcome, {
+ message_id: props.messageId,
+ defaultScreens: props.screens,
+ updateHistory: !props.disableHistoryUpdates,
+ metricsFlowUri: this.state.metricsFlowUri,
+ utm_term: props.UTMTerm,
+ transitions: props.transitions,
+ backdrop: props.backdrop,
+ startScreen: props.startScreen || 0,
+ appAndSystemLocaleInfo: props.appAndSystemLocaleInfo
+ });
+ }
+
+} // Computes messageId and UTMTerm info used in telemetry
+
+
+function ComputeTelemetryInfo(welcomeContent, experimentId, branchId) {
+ let messageId = welcomeContent.template === "return_to_amo" ? `RTAMO_DEFAULT_WELCOME_${welcomeContent.type.toUpperCase()}` : "DEFAULT_ID";
+ let UTMTerm = "aboutwelcome-default";
+
+ if (welcomeContent.id) {
+ messageId = welcomeContent.id.toUpperCase();
+ }
+
+ if (experimentId && branchId) {
+ UTMTerm = `aboutwelcome-${experimentId}-${branchId}`.toLowerCase();
+ }
+
+ return {
+ messageId,
+ UTMTerm
+ };
+}
+
+async function retrieveRenderContent() {
+ // Feature config includes RTAMO attribution data if exists
+ // else below data in order specified
+ // user prefs
+ // experiment data
+ // defaults
+ let featureConfig = await window.AWGetFeatureConfig();
+ let {
+ messageId,
+ UTMTerm
+ } = ComputeTelemetryInfo(featureConfig, featureConfig.slug, featureConfig.branch && featureConfig.branch.slug);
+ return {
+ featureConfig,
+ messageId,
+ UTMTerm
+ };
+}
+
+async function mount() {
+ let {
+ featureConfig: aboutWelcomeProps,
+ messageId,
+ UTMTerm
+ } = await retrieveRenderContent();
+ react_dom__WEBPACK_IMPORTED_MODULE_1___default().render( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default().createElement(AboutWelcome, _extends({
+ messageId: messageId,
+ UTMTerm: UTMTerm
+ }, aboutWelcomeProps)), document.getElementById("multi-stage-message-root"));
+}
+
+performance.mark("mount");
+mount();
+})();
+
+/******/ })()
+; \ 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..ba9c835693
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.css
@@ -0,0 +1,1644 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+.onboardingContainer.featureCallout {
+ --fc-background: var(--fc-background-light, #FFF);
+ --fc-color: var(--fc-color-light, #15141A);
+ --fc-border: var(--fc-border-light, #CFCFD8);
+ --fc-accent-color: var(--fc-accent-color-light, #0061E0);
+ --fc-button-background: var(--fc-button-background-light, #F0F0F4);
+ --fc-button-color: var(--fc-button-color-light, #15141A);
+ --fc-button-border: var(--fc-button-border-light, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-light, #E0E0E6);
+ --fc-button-color-hover: var(--fc-button-color-hover-light, #15141A);
+ --fc-button-border-hover: var(--fc-button-border-hover-light, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-light, #CFCFD8);
+ --fc-button-color-active: var(--fc-button-color-active-light, #15141A);
+ --fc-button-border-active: var(--fc-button-border-active-light, transparent);
+ --fc-step-color: color-mix(in srgb, currentColor 50%, transparent);
+ position: absolute;
+ transition: opacity 0.5s ease;
+ z-index: 2147483645;
+ outline: none;
+ color: var(--fc-color);
+}
+@media (prefers-color-scheme: dark) {
+ .onboardingContainer.featureCallout {
+ --fc-background: var(--fc-background-dark, #42414D);
+ --fc-color: var(--fc-color-dark, #FBFBFE);
+ --fc-border: var(--fc-border-dark, #3A3944);
+ --fc-accent-color: var(--fc-accent-color-dark, #00DDFF);
+ --fc-button-background: var(--fc-button-background-dark, #2B2A33);
+ --fc-button-color: var(--fc-button-color-dark, #FBFBFE);
+ --fc-button-border: var(--fc-button-border-dark, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-dark, #52525E);
+ --fc-button-color-hover: var(--fc-button-color-hover-dark, #FBFBFE);
+ --fc-button-border-hover: var(--fc-button-border-hover-dark, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-dark, #5B5B66);
+ --fc-button-color-active: var(--fc-button-color-active-dark, #FBFBFE);
+ --fc-button-border-active: var(--fc-button-border-active-dark, transparent);
+ }
+}
+@media (prefers-contrast) {
+ .onboardingContainer.featureCallout {
+ --fc-background: var(--fc-background-hcm, -moz-dialog);
+ --fc-color: var(--fc-color-hcm, -moz-dialogtext);
+ --fc-border: var(--fc-border-hcm, -moz-dialogtext);
+ --fc-accent-color: var(--fc-accent-color-hcm, LinkText);
+ --fc-button-background: var(--fc-button-background-hcm, ButtonFace);
+ --fc-button-color: var(--fc-button-color-hcm, ButtonText);
+ --fc-button-border: var(--fc-button-border-hcm, ButtonText);
+ --fc-button-background-hover: var(--fc-button-background-hover-hcm, ButtonText);
+ --fc-button-color-hover: var(--fc-button-color-hover-hcm, ButtonFace);
+ --fc-button-border-hover: var(--fc-button-border-hover-hcm, ButtonText);
+ --fc-button-background-active: var(--fc-button-background-active-hcm, ButtonText);
+ --fc-button-color-active: var(--fc-button-color-active-hcm, ButtonFace);
+ --fc-button-border-active: var(--fc-button-border-active-hcm, ButtonText);
+ --fc-step-color: var(--fc-accent-color-hcm, LinkText);
+ }
+}
+@media (-moz-content-prefers-color-scheme: light) {
+ .onboardingContainer.featureCallout.simulateContent {
+ --fc-background: var(--fc-background-light, #FFF);
+ --fc-color: var(--fc-color-light, #15141A);
+ --fc-border: var(--fc-border-light, #CFCFD8);
+ --fc-accent-color: var(--fc-accent-color-light, #0061E0);
+ --fc-button-background: var(--fc-button-background-light, #F0F0F4);
+ --fc-button-color: var(--fc-button-color-light, #15141A);
+ --fc-button-border: var(--fc-button-border-light, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-light, #E0E0E6);
+ --fc-button-color-hover: var(--fc-button-color-hover-light, #15141A);
+ --fc-button-border-hover: var(--fc-button-border-hover-light, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-light, #CFCFD8);
+ --fc-button-color-active: var(--fc-button-color-active-light, #15141A);
+ --fc-button-border-active: var(--fc-button-border-active-light, transparent);
+ --fc-step-color: color-mix(in srgb, currentColor 50%, transparent);
+ }
+}
+@media (-moz-content-prefers-color-scheme: dark) {
+ .onboardingContainer.featureCallout.simulateContent {
+ --fc-background: var(--fc-background-dark, #42414D);
+ --fc-color: var(--fc-color-dark, #FBFBFE);
+ --fc-border: var(--fc-border-dark, #3A3944);
+ --fc-accent-color: var(--fc-accent-color-dark, #00DDFF);
+ --fc-button-background: var(--fc-button-background-dark, #2B2A33);
+ --fc-button-color: var(--fc-button-color-dark, #FBFBFE);
+ --fc-button-border: var(--fc-button-border-dark, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-dark, #52525E);
+ --fc-button-color-hover: var(--fc-button-color-hover-dark, #FBFBFE);
+ --fc-button-border-hover: var(--fc-button-border-hover-dark, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-dark, #5B5B66);
+ --fc-button-color-active: var(--fc-button-color-active-dark, #FBFBFE);
+ --fc-button-border-active: var(--fc-button-border-active-dark, transparent);
+ }
+}
+@media (prefers-contrast) {
+ .onboardingContainer.featureCallout.simulateContent {
+ --fc-background: var(--fc-background-hcm, -moz-dialog);
+ --fc-color: var(--fc-color-hcm, -moz-dialogtext);
+ --fc-border: var(--fc-border-hcm, -moz-dialogtext);
+ --fc-accent-color: var(--fc-accent-color-hcm, LinkText);
+ --fc-button-background: var(--fc-button-background-hcm, ButtonFace);
+ --fc-button-color: var(--fc-button-color-hcm, ButtonText);
+ --fc-button-border: var(--fc-button-border-hcm, ButtonText);
+ --fc-button-background-hover: var(--fc-button-background-hover-hcm, ButtonText);
+ --fc-button-color-hover: var(--fc-button-color-hover-hcm, ButtonFace);
+ --fc-button-border-hover: var(--fc-button-border-hover-hcm, ButtonText);
+ --fc-button-background-active: var(--fc-button-background-active-hcm, ButtonText);
+ --fc-button-color-active: var(--fc-button-color-active-hcm, ButtonFace);
+ --fc-button-border-active: var(--fc-button-border-active-hcm, ButtonText);
+ --fc-step-color: var(--fc-accent-color-hcm, LinkText);
+ }
+}
+.onboardingContainer.featureCallout.hidden {
+ opacity: 0;
+ pointer-events: none;
+}
+.onboardingContainer.featureCallout, .onboardingContainer.featureCallout .outer-wrapper {
+ height: auto;
+}
+.onboardingContainer.featureCallout .screen:dir(rtl) {
+ transform: none;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] {
+ height: fit-content;
+ min-height: unset;
+ overflow: visible;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .logo-container {
+ display: flex;
+ justify-content: center;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .logo-container .brand-logo {
+ margin: 30px 45px 0;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .logo-container .brand-logo:dir(rtl) {
+ transform: rotateY(180deg);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .welcome-text {
+ align-items: baseline;
+ text-align: start;
+ margin-inline: 30px;
+ padding: 20px 0 0;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .welcome-text h1,
+.onboardingContainer.featureCallout .screen[pos=callout] .welcome-text h2 {
+ font-size: 0.8em;
+ margin: 0;
+ color: inherit;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .welcome-text h1 {
+ font-weight: bold;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .welcome-text h2 {
+ margin-block: 10px;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-secondary {
+ display: none;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main {
+ height: fit-content;
+ width: fit-content;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content {
+ position: relative;
+ overflow: hidden;
+ border: 1px solid var(--fc-border);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ padding-top: 0;
+ padding-bottom: 26px;
+ width: 25em;
+ background-color: var(--fc-background);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content .steps {
+ height: auto;
+ position: absolute;
+ bottom: 42px;
+ margin: 0 30px;
+ padding-block: 0;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content .steps .indicator {
+ border: 4px solid var(--fc-step-color);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content .steps .indicator.current {
+ border-color: var(--fc-accent-color);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content .steps .indicator.current, .onboardingContainer.featureCallout .screen[pos=callout] .section-main .main-content .steps.progress-bar .indicator.complete {
+ border-color: var(--fc-accent-color);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .section-main .dismiss-button {
+ font-size: 1em;
+ top: 0;
+ margin-block: 15px 0;
+ margin-inline: 0 15px;
+ z-index: 2147483647;
+ background-color: var(--fc-background);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary,
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta .secondary {
+ padding: 4px 16px;
+ font-size: 0.8em;
+ height: 2em;
+ background-color: var(--fc-button-background);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary {
+ font-weight: bold;
+ float: inline-end;
+ margin-inline: 10px 30px;
+ padding: 4px 16px;
+ font-size: 0.8em;
+ line-height: 16px;
+ min-height: 32px;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta {
+ float: inline-end;
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary,
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta .secondary,
+.onboardingContainer.featureCallout .screen[pos=callout] .dismiss-button {
+ border-radius: 4px;
+ border: 1px solid var(--fc-button-border);
+ cursor: pointer;
+ color: var(--fc-button-color);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary:hover,
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta .secondary:hover,
+.onboardingContainer.featureCallout .screen[pos=callout] .dismiss-button:hover {
+ background-color: var(--fc-button-background-hover);
+ color: var(--fc-button-color-hover);
+ border: 1px solid var(--fc-button-border-hover);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary:hover:active,
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta .secondary:hover:active,
+.onboardingContainer.featureCallout .screen[pos=callout] .dismiss-button:hover:active {
+ background-color: var(--fc-button-background-active);
+ color: var(--fc-button-color-active);
+ border: 1px solid var(--fc-button-border-active);
+}
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .primary:focus-visible,
+.onboardingContainer.featureCallout .screen[pos=callout] .action-buttons .secondary-cta .secondary:focus-visible,
+.onboardingContainer.featureCallout .screen[pos=callout] .dismiss-button:focus-visible {
+ box-shadow: none;
+ outline: 2px solid var(--fc-accent-color);
+ outline-offset: 2px;
+}
+.onboardingContainer.featureCallout.callout-arrow::before, .onboardingContainer.featureCallout.callout-arrow::after {
+ content: "";
+ position: absolute;
+ width: 24px;
+ height: 24px;
+ transform: rotate(45deg);
+ transform-style: preserve-3d;
+}
+.onboardingContainer.featureCallout.callout-arrow::before {
+ z-index: 2147483647;
+ background-color: var(--fc-background);
+}
+.onboardingContainer.featureCallout.callout-arrow::after {
+ background: transparent;
+ outline: 1px solid var(--fc-border);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ z-index: -1;
+}
+.onboardingContainer.featureCallout.arrow-top::before, .onboardingContainer.featureCallout.arrow-top::after {
+ top: -11px;
+ inset-inline-start: calc(50% - 12px);
+}
+.onboardingContainer.featureCallout.arrow-bottom::before, .onboardingContainer.featureCallout.arrow-bottom::after {
+ bottom: -11px;
+ inset-inline-start: calc(50% - 12px);
+}
+.onboardingContainer.featureCallout.arrow-inline-end::before, .onboardingContainer.featureCallout.arrow-inline-end::after {
+ top: calc(50% - 12px);
+ inset-inline-end: -11px;
+}
+.onboardingContainer.featureCallout.arrow-inline-start::before, .onboardingContainer.featureCallout.arrow-inline-start::after {
+ top: calc(50% - 12px);
+ inset-inline-start: -11px;
+}
+.onboardingContainer.featureCallout.arrow-top-end::before, .onboardingContainer.featureCallout.arrow-top-end::after {
+ top: -11px;
+ inset-inline-end: 12px;
+}
+.onboardingContainer.featureCallout.arrow-top-start::before, .onboardingContainer.featureCallout.arrow-top-start::after {
+ top: -11px;
+ inset-inline-start: 12px;
+}
+.onboardingContainer.featureCallout.hidden-arrow::before, .onboardingContainer.featureCallout.hidden-arrow::after {
+ display: none;
+}
+.onboardingContainer.featureCallout:focus-visible .screen[pos=callout] .section-main .main-content {
+ outline: 2px solid var(--fc-accent-color);
+ border-color: transparent;
+}
+@media (prefers-contrast) {
+ .onboardingContainer.featureCallout:focus-visible .screen[pos=callout] .section-main .main-content {
+ border-color: var(--fc-background);
+ }
+}
+.onboardingContainer.featureCallout:focus-visible.callout-arrow::after {
+ outline: 2px solid var(--fc-accent-color);
+}
+
+html {
+ height: 100%;
+}
+
+.dummy {
+ background: var(--mr-welcome-background-color) var(--mr-welcome-background-gradient) var(--mr-secondary-position) var(--mr-screen-background-color);
+}
+
+:root[dialogroot] {
+ background-color: transparent;
+}
+:root[dialogroot] body {
+ padding: 0;
+}
+:root[dialogroot] .onboardingContainer {
+ height: 100%;
+ background-color: transparent;
+}
+:root[dialogroot] .onboardingContainer:dir(rtl) {
+ transform: unset;
+}
+:root[dialogroot] .onboardingContainer .logo-container {
+ pointer-events: none;
+}
+:root[dialogroot] .onboardingContainer .screen:dir(rtl) {
+ transform: unset;
+}
+
+.welcome-container .onboardingContainer {
+ min-height: 610px;
+ min-width: fit-content;
+}
+
+.onboardingContainer {
+ --grey-subtitle-1: #696977;
+ --mr-welcome-background-color: #F8F6F4;
+ --mr-screen-heading-color: var(--in-content-text-color);
+ --mr-welcome-background-gradient: linear-gradient(0deg, rgba(144, 89, 255, 20%) 0%, rgba(2, 144, 238, 20%) 100%);
+ --mr-screen-background-color: #F8F6F4;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Ubuntu, "Helvetica Neue", sans-serif;
+ font-size: 16px;
+ position: relative;
+ text-align: center;
+ height: 100vh;
+ --transition: 0.6s opacity, 0.6s scale, 0.6s rotate, 0.6s translate;
+}
+@media (prefers-color-scheme: dark) {
+ .onboardingContainer {
+ --grey-subtitle-1: #FFF;
+ --mr-welcome-background-color: #333336;
+ --mr-welcome-background-gradient: linear-gradient(0deg, rgba(144, 89, 255, 30%) 0%, rgba(2, 144, 238, 30%) 100%);
+ --mr-screen-background-color: #62697A;
+ }
+}
+@media (prefers-contrast) {
+ .onboardingContainer {
+ --mr-screen-background-color: buttontext;
+ --mr-screen-heading-color: buttonface;
+ background-color: var(--in-content-page-background);
+ }
+}
+@media (prefers-reduced-motion: no-preference) {
+ .onboardingContainer {
+ --translate: 30px;
+ --rotate: 20deg;
+ --scale: 0.4;
+ --progress-bar-transition: 0.6s translate;
+ }
+ .onboardingContainer:dir(rtl) {
+ --scale: -0.4 0.4;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .onboardingContainer {
+ --translate: 0;
+ --rotate: 0deg;
+ --scale: 1;
+ --progress-bar-transition: none;
+ }
+ .onboardingContainer:dir(rtl) {
+ --scale: -1 1;
+ }
+}
+.onboardingContainer:dir(rtl) {
+ transform: rotateY(180deg);
+}
+.onboardingContainer .section-main {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ width: 504px;
+ flex-shrink: 0;
+}
+.onboardingContainer .section-main:not(.embedded-migration) {
+ position: relative;
+}
+.onboardingContainer .main-content {
+ background-color: var(--in-content-page-background);
+ border-radius: 20px;
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ padding: 0;
+ transition: var(--transition);
+ z-index: 1;
+ box-sizing: border-box;
+}
+.onboardingContainer .main-content.no-steps {
+ padding-bottom: 48px;
+}
+.onboardingContainer .main-content .main-content-inner {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ justify-content: space-around;
+}
+.onboardingContainer .main-content .no-steps .main-content {
+ padding-bottom: 48px;
+}
+.onboardingContainer .main-content .no-steps .steps {
+ display: none;
+}
+.onboardingContainer .screen {
+ display: flex;
+ position: relative;
+ flex-flow: row nowrap;
+ height: 100%;
+ min-height: 500px;
+ overflow: hidden;
+ --in-content-link-color: var(--in-content-primary-button-background);
+ --in-content-link-color-hover: var(--in-content-primary-button-background-hover);
+ --in-content-link-color-active: var(--in-content-primary-button-background-active);
+ --in-content-link-color-visited: var(--in-content-link-color);
+}
+.onboardingContainer .screen.light-text {
+ --in-content-page-color: rgb(251, 251, 254);
+ --in-content-primary-button-text-color: rgb(43, 42, 51);
+ --in-content-primary-button-text-color-hover: rgb(43, 42, 51);
+ --in-content-primary-button-background: rgb(0, 221, 255);
+ --in-content-primary-button-background-hover: rgb(128, 235, 255);
+ --in-content-primary-button-background-active: rgb(170, 242, 255);
+ --checkbox-checked-bgcolor: var(--in-content-primary-button-background);
+ --in-content-button-text-color: var(--in-content-page-color);
+}
+.onboardingContainer .screen.dark-text {
+ --in-content-page-color: rgb(21, 20, 26);
+ --in-content-primary-button-text-color: rgb(251, 251, 254);
+ --in-content-primary-button-text-color-hover: rgb(251, 251, 254);
+ --in-content-primary-button-background: #0061E0;
+ --in-content-primary-button-background-hover: #0250BB;
+ --in-content-primary-button-background-active: #053E94;
+ --in-content-primary-button-border-color: transparent;
+ --in-content-primary-button-border-hover: transparent;
+ --checkbox-checked-bgcolor: var(--in-content-primary-button-background);
+ --in-content-button-text-color: var(--in-content-page-color);
+}
+.onboardingContainer .screen:dir(rtl) {
+ transform: rotateY(180deg);
+}
+.onboardingContainer .screen[pos=center] {
+ background-color: rgba(21, 20, 26, 0.5);
+ min-width: 504px;
+}
+.onboardingContainer .screen[pos=center].with-noodles {
+ min-width: 610px;
+ min-height: 610px;
+}
+.onboardingContainer .screen[pos=center].with-noodles .section-main {
+ height: 504px;
+}
+.onboardingContainer .screen[pos=center].with-video {
+ justify-content: center;
+ background: none;
+ align-items: center;
+}
+.onboardingContainer .screen[pos=center].with-video .section-main {
+ width: 800px;
+ height: 550px;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content {
+ background-color: var(--mr-welcome-background-color);
+ border-radius: 8px;
+ box-shadow: 0 2px 14px rgba(58, 57, 68, 0.2);
+ padding: 44px 85px 20px;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .welcome-text {
+ margin: 0;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .main-content-inner {
+ justify-content: space-between;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content h1,
+.onboardingContainer .screen[pos=center].with-video .main-content h2 {
+ align-self: start;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content h1 {
+ font-size: 24px;
+ line-height: 28.8px;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content h2 {
+ font-size: 15px;
+ line-height: 22px;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta {
+ justify-content: end;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta .arrow-icon {
+ -moz-context-properties: fill;
+ fill: currentColor;
+ text-decoration: none;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta .arrow-icon::after {
+ content: "";
+ padding-inline-end: 12px;
+ margin-inline-start: 4px;
+ background: url("chrome://browser/skin/forward.svg") no-repeat center/12px;
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta .arrow-icon:dir(rtl)::after {
+ background-image: url("chrome://browser/skin/back.svg");
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta .secondary {
+ background-color: var(--in-content-button-background) !important;
+ border: 1px solid var(--in-content-button-border-color);
+ line-height: 12px;
+ font-size: 0.72em;
+ font-weight: 600;
+ padding: 8px 16px;
+ text-decoration: none;
+ color: var(--in-content-button-text-color);
+}
+.onboardingContainer .screen[pos=center].with-video .main-content .secondary-cta .secondary:hover {
+ background-color: var(--in-content-button-background-hover) !important;
+ color: var(--in-content-button-text-color-hover);
+}
+.onboardingContainer .screen:not([pos=split]) .secondary-cta .secondary {
+ background: none;
+ color: var(--in-content-link-color);
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 20px;
+}
+.onboardingContainer .screen:not([pos=split]) .secondary-cta.top button {
+ color: #FFF;
+}
+.onboardingContainer .screen:not([pos=split]) .secondary-cta.top button:hover {
+ color: #E0E0E6;
+}
+.onboardingContainer .screen[pos=split] {
+ margin: auto;
+ min-height: 550px;
+}
+.onboardingContainer .screen[pos=split]::before {
+ content: "";
+ position: absolute;
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ width: 800px;
+ height: 550px;
+ border-radius: 8px;
+ inset: 0;
+ margin: auto;
+ pointer-events: none;
+}
+.onboardingContainer .screen[pos=split] .section-secondary,
+.onboardingContainer .screen[pos=split] .section-main {
+ width: 400px;
+ height: 550px;
+}
+.onboardingContainer .screen[pos=split] .secondary-cta.top {
+ position: fixed;
+ padding-inline-end: 0;
+}
+.onboardingContainer .screen[pos=split] .secondary-cta.top button {
+ color: var(--in-content-page-color);
+}
+.onboardingContainer .screen[pos=split] .section-main {
+ flex-direction: row;
+ display: block;
+ margin: auto auto auto 0;
+}
+.onboardingContainer .screen[pos=split] .section-main:dir(rtl) {
+ margin: auto 0 auto auto;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content {
+ border-radius: 0 8px 8px 0;
+ overflow: hidden;
+ padding-inline: 35px 20px;
+ padding-block: 120px 0;
+ box-shadow: none;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content.no-steps {
+ padding-bottom: 48px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content:dir(rtl) {
+ border-radius: 8px 0 0 8px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .main-content-inner {
+ min-height: 330px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .main-content-inner .language-switcher-container .primary {
+ margin-bottom: 5px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons {
+ position: relative;
+ text-align: initial;
+ height: 100%;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .checkbox-container {
+ font-size: 13px;
+ margin-block: 1em;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .checkbox-container:not(.multi-select-item) {
+ transition: var(--transition);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .checkbox-container input,
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .checkbox-container label {
+ vertical-align: middle;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .additional-cta {
+ margin: 8px 0;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .additional-cta.cta-link {
+ background: none;
+ padding: 0;
+ font-weight: normal;
+ text-decoration: underline;
+ cursor: pointer;
+ color: var(--in-content-link-color);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .additional-cta.cta-link:hover {
+ text-decoration: none;
+ color: var(--in-content-link-color-hover);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .additional-cta.cta-link:active {
+ text-decoration: none;
+ color: var(--in-content-link-color-active);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .additional-cta.secondary:hover {
+ background-color: var(--in-content-button-background-hover);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons.additional-cta-container {
+ flex-wrap: nowrap;
+ align-items: start;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta {
+ position: absolute;
+ bottom: -30px;
+ inset-inline-end: 0;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta .secondary {
+ background-color: var(--in-content-button-background) !important;
+ border: 1px solid var(--in-content-button-border-color);
+ line-height: 12px;
+ font-size: 0.72em;
+ font-weight: 600;
+ padding: 8px 16px;
+ text-decoration: none;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta .secondary:hover {
+ background-color: var(--in-content-button-background-hover) !important;
+ color: var(--in-content-button-text-color-hover);
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta .arrow-icon {
+ -moz-context-properties: fill;
+ fill: currentColor;
+ text-decoration: none;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta .arrow-icon::after {
+ content: "";
+ padding-inline-end: 12px;
+ margin-inline-start: 4px;
+ background: url("chrome://browser/skin/forward.svg") no-repeat center/12px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta .arrow-icon:dir(rtl)::after {
+ background-image: url("chrome://browser/skin/back.svg");
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .logo-container {
+ text-align: start;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .brand-logo {
+ height: 25px;
+ margin-block: 0;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text {
+ margin-inline: 0 10px;
+ margin-block: 10px 35px;
+ text-align: initial;
+ align-items: initial;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text:empty {
+ margin: 0;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text h1 {
+ font-size: 24px;
+ line-height: 1.2;
+ width: 300px;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text h2 {
+ margin: 10px 0 0;
+ min-height: 1em;
+ font-size: 15px;
+ line-height: 1.5;
+}
+@media (prefers-contrast: no-preference) {
+ .onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text h2 {
+ color: #5B5B66;
+ }
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text h1,
+.onboardingContainer .screen[pos=split] .section-main .main-content .primary {
+ margin: 0;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .steps {
+ z-index: 1;
+}
+.onboardingContainer .screen[pos=split] .section-main .main-content .steps.progress-bar {
+ width: 400px;
+ margin-inline: -35px;
+}
+@media (prefers-contrast) {
+ .onboardingContainer .screen[pos=split] .section-main .main-content {
+ border: 1px solid var(--in-content-page-color);
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .steps.progress-bar {
+ border-top: 1px solid var(--in-content-page-color);
+ background-color: var(--in-content-page-background);
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .steps.progress-bar .indicator {
+ background-color: var(--in-content-accent-color);
+ }
+}
+.onboardingContainer .screen[pos=split] .section-secondary {
+ --mr-secondary-position: center center / auto 350px;
+ border-radius: 8px 0 0 8px;
+ margin: auto 0 auto auto;
+ display: flex;
+ align-items: center;
+ -moz-context-properties: fill, stroke, fill-opacity, stroke-opacity;
+ stroke: currentColor;
+}
+.onboardingContainer .screen[pos=split] .section-secondary:dir(rtl) {
+ border-radius: 0 8px 8px 0;
+ margin: auto auto auto 0;
+}
+.onboardingContainer .screen[pos=split] .section-secondary h1 {
+ color: var(--mr-screen-heading-color);
+ font-weight: 700;
+ font-size: 47px;
+ line-height: 110%;
+ max-width: 340px;
+ text-align: initial;
+ white-space: pre-wrap;
+ text-shadow: none;
+ margin-inline: 40px 0;
+}
+.onboardingContainer .screen[pos=split] .section-secondary .image-alt {
+ width: inherit;
+ height: inherit;
+}
+.onboardingContainer .screen[pos=split] .section-secondary .hero-image {
+ flex: 1;
+ display: flex;
+ justify-content: center;
+ max-height: 100%;
+}
+.onboardingContainer .screen[pos=split] .section-secondary .hero-image img {
+ width: 100%;
+ max-width: 180px;
+ margin: 25px 0;
+ padding-bottom: 30px;
+}
+@media only screen and (max-width: 800px) {
+ .onboardingContainer .screen[pos=split] .section-secondary .hero-image img {
+ padding-bottom: unset;
+ }
+}
+.onboardingContainer .screen[pos=split] .tiles-theme-container {
+ margin-block: -20px auto;
+ align-items: initial;
+}
+.onboardingContainer .screen[pos=split] .tiles-theme-container .colorway-text {
+ text-align: initial;
+ transition: var(--transition);
+ font-size: 13px;
+ line-height: 1.5;
+ min-height: 4.5em;
+ margin-block: 10px 20px;
+}
+.onboardingContainer .screen[pos=split] .tiles-theme-container .theme {
+ min-width: 38px;
+}
+@media (prefers-contrast: no-preference) and (prefers-color-scheme: dark) {
+ .onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text h2 {
+ color: #CFCFD8;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary {
+ background-color: #2B2A33;
+ }
+}
+@media only screen and (min-width: 800px) {
+ .onboardingContainer .screen[pos=split] .tiles-theme-section {
+ margin-inline-start: -10px;
+ }
+}
+@media only screen and (max-width: 800px) {
+ .onboardingContainer .screen[pos=split] {
+ flex-direction: column;
+ min-height: 550px;
+ }
+ .onboardingContainer .screen[pos=split]::before {
+ width: 400px;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary,
+.onboardingContainer .screen[pos=split] .section-main {
+ width: 400px;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary {
+ --mr-secondary-background-position-y: top;
+ --mr-secondary-position: center var(--mr-secondary-background-position-y) / 75%;
+ border-radius: 8px 8px 0 0;
+ margin: auto auto 0;
+ height: 100px;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary .hero-image img {
+ margin: 6px 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary .message-text {
+ margin-inline: auto;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary h1 {
+ font-size: 35px;
+ text-align: center;
+ white-space: normal;
+ margin-inline: auto;
+ margin-block: 14px 6px;
+ }
+ .onboardingContainer .screen[pos=split] .section-secondary:dir(rtl) {
+ margin: auto auto 0;
+ border-radius: 8px 8px 0 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-main {
+ margin: 0 auto auto;
+ height: 450px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content {
+ border-radius: 0 0 8px 8px;
+ padding: 30px 0 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .main-content-inner {
+ align-items: center;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .logo-container {
+ text-align: center;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .logo-container .brand-logo {
+ min-height: 25px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .logo-container .brand-logo, .onboardingContainer .screen[pos=split] .section-main .main-content .logo-container .brand-logo:dir(rtl) {
+ background-position: center;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text {
+ align-items: center;
+ text-align: center;
+ margin-inline: 0;
+ padding-inline: 30px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text .spacer-bottom,
+.onboardingContainer .screen[pos=split] .section-main .main-content .welcome-text .spacer-top {
+ display: none;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons {
+ text-align: center;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .checkbox-container {
+ display: none;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .action-buttons .secondary-cta {
+ position: relative;
+ margin-block: 10px 0;
+ bottom: 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .primary,
+.onboardingContainer .screen[pos=split] .section-main .main-content .secondary {
+ min-width: 240px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .colorway-text {
+ text-align: center;
+ margin-inline: 30px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .steps {
+ padding-block: 0;
+ margin: 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .main-content .steps.progress-bar {
+ margin-inline: 0;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .additional-cta.cta-link {
+ align-self: center;
+ }
+ .onboardingContainer .screen[pos=split] .section-main .dismiss-button {
+ top: -100px;
+ }
+ .onboardingContainer .screen[pos=split] .section-main:dir(rtl) {
+ margin: 0 auto auto;
+ }
+ .onboardingContainer .screen[pos=split] .section-main:dir(rtl) .main-content {
+ border-radius: 0 0 8px 8px;
+ }
+}
+@media only screen and (max-height: 650px) and (min-width: 800px) and (max-width: 990px) {
+ .onboardingContainer .screen[pos=split] .section-main .secondary-cta.top {
+ display: none;
+ }
+}
+@media only screen and (max-height: 650px) and (max-width: 590px) {
+ .onboardingContainer .screen[pos=split] .section-main .secondary-cta.top {
+ position: absolute;
+ padding: 0;
+ top: 0;
+ inset-inline-end: 0;
+ }
+}
+.onboardingContainer .brand-logo {
+ margin-block: 60px 10px;
+ transition: var(--transition);
+ height: 80px;
+}
+.onboardingContainer .brand-logo.cta-top {
+ margin-top: 25px;
+}
+.onboardingContainer .brand-logo.hide {
+ visibility: hidden;
+ padding: unset;
+ margin-top: 50px;
+}
+.onboardingContainer .rtamo-theme-icon {
+ max-height: 30px;
+ border-radius: 2px;
+ margin-bottom: 10px;
+ margin-top: 24px;
+}
+.onboardingContainer .rtamo-icon {
+ text-align: start;
+}
+@media only screen and (max-width: 800px) {
+ .onboardingContainer .rtamo-icon {
+ text-align: center;
+ }
+}
+.onboardingContainer .text-link {
+ text-decoration: underline;
+ cursor: pointer;
+ color: var(--in-content-link-color);
+}
+.onboardingContainer .text-link:hover {
+ text-decoration: none;
+ color: var(--in-content-link-color-hover);
+}
+.onboardingContainer .text-link:active {
+ text-decoration: none;
+ color: var(--in-content-link-color-active);
+}
+.onboardingContainer .welcome-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ margin: 0.5em 1em;
+ transition: var(--transition);
+}
+.onboardingContainer .welcome-text h1,
+.onboardingContainer .welcome-text h2 {
+ color: var(--in-content-page-color);
+ line-height: 1.5;
+}
+.onboardingContainer .welcome-text h1 {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 6px;
+ letter-spacing: -0.02em;
+ outline: none;
+}
+.onboardingContainer .welcome-text h2 {
+ font-size: 16px;
+ font-weight: normal;
+ margin: 10px 6px 0;
+ max-width: 750px;
+ letter-spacing: -0.01em;
+}
+.onboardingContainer .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #9059FF, #FF4AA2, #FF8C00, #FF4AA2, #9059FF);
+ background-clip: text;
+ background-size: 200%;
+}
+@media (prefers-contrast: no-preference) {
+ .onboardingContainer .welcome-text.fancy h1 {
+ color: transparent;
+ }
+}
+@media (prefers-color-scheme: dark) {
+ .onboardingContainer .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #C688FF, #FF84C0, #FFBD4F, #FF84C0, #C688FF);
+ }
+ .onboardingContainer .welcome-text.fancy h1::selection {
+ color: #FFF;
+ background-color: #696977;
+ }
+}
+.onboardingContainer .welcome-text.shine h1 {
+ animation: shine 50s linear infinite;
+ background-size: 400%;
+}
+@keyframes shine {
+ to {
+ background-position: 400%;
+ }
+}
+.onboardingContainer .welcome-text .cta-paragraph a {
+ margin: 0;
+ text-decoration: underline;
+ cursor: pointer;
+}
+.onboardingContainer .screen.light-text .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #C688FF, #FF84C0, #FFBD4F, #FF84C0, #C688FF);
+}
+.onboardingContainer .screen.dark-text .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #9059FF, #FF4AA2, #FF8C00, #FF4AA2, #9059FF);
+}
+.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;
+ transform: scaleY(3);
+}
+.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 .language-loader {
+ filter: invert(1);
+ margin-inline-end: 10px;
+ position: relative;
+ top: 3px;
+ width: 16px;
+ height: 16px;
+ margin-top: -6px;
+}
+@media (prefers-color-scheme: dark) {
+ .onboardingContainer .language-loader {
+ filter: invert(0);
+ }
+}
+.onboardingContainer .tiles-theme-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ margin: 10px auto;
+}
+.onboardingContainer .sr-only {
+ opacity: 0;
+ overflow: hidden;
+ position: absolute;
+}
+.onboardingContainer .sr-only.input {
+ height: 1px;
+ width: 1px;
+}
+.onboardingContainer .tiles-theme-section {
+ border: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ justify-content: space-evenly;
+ margin-inline: 10px;
+ padding: 10px;
+ transition: var(--transition);
+}
+.onboardingContainer .tiles-theme-section:hover, .onboardingContainer .tiles-theme-section:active, .onboardingContainer .tiles-theme-section:focus-within {
+ border-radius: 8px;
+ outline: 2px solid var(--in-content-primary-button-background);
+}
+.onboardingContainer .tiles-theme-section .theme {
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ padding: 0;
+ min-width: 50px;
+ width: 180px;
+ color: #000;
+ box-shadow: none;
+ border-radius: 4px;
+ cursor: pointer;
+ z-index: 0;
+}
+.onboardingContainer .tiles-theme-section .theme.colorway {
+ width: auto;
+}
+.onboardingContainer .tiles-theme-section .theme:focus, .onboardingContainer .tiles-theme-section .theme:active {
+ outline: initial;
+ outline-offset: initial;
+}
+.onboardingContainer .tiles-theme-section .theme .icon.colorway,
+.onboardingContainer .tiles-theme-section .theme .label.colorway {
+ width: 20px;
+ height: 20px;
+}
+.onboardingContainer .tiles-theme-section .theme .icon {
+ background-size: cover;
+ width: 40px;
+ height: 40px;
+ border-radius: 40px;
+ outline: 1px solid var(--in-content-border-color);
+ outline-offset: -0.5px;
+ z-index: -1;
+}
+.onboardingContainer .tiles-theme-section .theme .icon:dir(rtl) {
+ transform: scaleX(-1);
+}
+.onboardingContainer .tiles-theme-section .theme .icon:focus, .onboardingContainer .tiles-theme-section .theme .icon:active, .onboardingContainer .tiles-theme-section .theme .icon.selected {
+ outline: 2px solid var(--in-content-primary-button-background);
+ outline-offset: 2px;
+}
+.onboardingContainer .tiles-theme-section .theme .icon.light {
+ background-image: url("resource://builtin-themes/light/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.dark {
+ background-image: url("resource://builtin-themes/dark/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.alpenglow {
+ background-image: url("resource://builtin-themes/alpenglow/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.default, .onboardingContainer .tiles-theme-section .theme .icon.automatic {
+ background-image: url("resource://default-theme/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.default.colorway, .onboardingContainer .tiles-theme-section .theme .icon.automatic.colorway {
+ background-image: url("chrome://activity-stream/content/data/content/assets/default.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.playmaker {
+ background-image: url("resource://builtin-themes/colorways/2022playmaker/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.expressionist {
+ background-image: url("resource://builtin-themes/colorways/2022expressionist/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.visionary {
+ background-image: url("resource://builtin-themes/colorways/2022visionary/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.dreamer {
+ background-image: url("resource://builtin-themes/colorways/2022dreamer/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.innovator {
+ background-image: url("resource://builtin-themes/colorways/2022innovator/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .icon.activist {
+ background-image: url("resource://builtin-themes/colorways/2022activist/balanced/icon.svg");
+}
+.onboardingContainer .tiles-theme-section .theme .text {
+ display: flex;
+ color: var(--in-content-page-color);
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 20px;
+ margin-inline-start: 0;
+ margin-top: 9px;
+}
+.onboardingContainer .tiles-theme-section legend {
+ cursor: default;
+}
+.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-delayed {
+ animation: fadein 0.4s;
+}
+.onboardingContainer .multi-select-container {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ margin-block: -1em 1em;
+ color: #5B5B66;
+ font-weight: 400;
+ font-size: 14px;
+ text-align: initial;
+ transition: var(--transition);
+ z-index: 1;
+}
+.onboardingContainer .multi-select-container .checkbox-container {
+ display: flex;
+ margin-bottom: 16px;
+}
+@media (prefers-color-scheme: dark) {
+ .onboardingContainer .multi-select-container {
+ color: #CFCFD8;
+ }
+}
+@media only screen and (max-width: 800px) {
+ .onboardingContainer .multi-select-container {
+ padding: 0 30px;
+ }
+}
+.onboardingContainer .mobile-downloads .qr-code-image {
+ margin: 24px 0 10px;
+ width: 113px;
+ height: 113px;
+}
+.onboardingContainer .mobile-downloads .email-link {
+ font-size: 16px;
+ font-weight: 400;
+ background: none;
+ text-decoration: underline;
+ cursor: pointer;
+ color: var(--in-content-link-color);
+}
+.onboardingContainer .mobile-downloads .email-link:hover {
+ text-decoration: none;
+ color: var(--in-content-link-color-hover);
+}
+.onboardingContainer .mobile-downloads .email-link:active {
+ text-decoration: none;
+ color: var(--in-content-link-color-active);
+}
+.onboardingContainer .mobile-downloads .email-link:hover {
+ background: none;
+}
+.onboardingContainer .mobile-downloads .ios button {
+ background-image: url("chrome://app-marketplace-icons/locale/ios.svg");
+}
+.onboardingContainer .mobile-downloads .android button {
+ background-image: url("chrome://app-marketplace-icons/locale/android.png");
+}
+.onboardingContainer .mobile-download-buttons {
+ list-style: none;
+ padding: 10px 0;
+ margin: 0;
+}
+.onboardingContainer .mobile-download-buttons li {
+ display: inline-block;
+}
+.onboardingContainer .mobile-download-buttons li button {
+ display: inline-block;
+ height: 45px;
+ width: 152px;
+ background-repeat: no-repeat;
+ background-size: contain;
+ background-position: center;
+ box-shadow: none;
+ border: 0;
+}
+.onboardingContainer .mobile-download-buttons li:not(:first-child) {
+ margin-inline: 5px 0;
+}
+.onboardingContainer .dismiss-button {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ left: auto;
+ right: 0;
+ box-sizing: border-box;
+ padding: 0;
+ margin: 16px;
+ display: block;
+ float: inline-end;
+ background: url("chrome://global/skin/icons/close.svg") no-repeat center/16px;
+ height: 32px;
+ width: 32px;
+ align-self: end;
+ min-height: 32px;
+ min-width: 32px;
+ -moz-context-properties: fill;
+ fill: currentColor;
+ transition: var(--transition);
+}
+.onboardingContainer .dismiss-button:dir(rtl) {
+ left: 0;
+ right: auto;
+}
+@keyframes fadein {
+ from {
+ opacity: 0;
+ }
+}
+.onboardingContainer .secondary-cta {
+ display: flex;
+ align-items: end;
+ flex-direction: row;
+ justify-content: center;
+ font-size: 14px;
+ transition: var(--transition);
+}
+.onboardingContainer .secondary-cta.top {
+ justify-content: end;
+ padding-inline-end: min(150px, 500px - 70vh);
+ padding-top: 4px;
+ position: absolute;
+ top: 10px;
+ inset-inline-end: 20px;
+ z-index: 2;
+}
+.onboardingContainer .secondary-cta span {
+ color: var(--grey-subtitle-1);
+ margin: 0 4px;
+}
+.onboardingContainer .message-text,
+.onboardingContainer .attrib-text {
+ transition: var(--transition);
+}
+.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 .helptext span {
+ padding-inline-end: 4px;
+}
+.onboardingContainer .helptext-img {
+ height: 1.5em;
+ width: 1.5em;
+ margin-inline-end: 4px;
+ vertical-align: middle;
+}
+.onboardingContainer .helptext-img.end {
+ margin: 4px;
+}
+.onboardingContainer .helptext-img.footer {
+ vertical-align: bottom;
+}
+.onboardingContainer .steps {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ margin-top: 0;
+ padding-block: 16px 0;
+ transition: var(--transition);
+ z-index: -1;
+ height: 48px;
+ box-sizing: border-box;
+}
+.onboardingContainer .steps.has-helptext {
+ padding-bottom: 0;
+}
+.onboardingContainer .steps .indicator {
+ width: 0;
+ height: 0;
+ margin-inline-end: 4px;
+ margin-inline-start: 4px;
+ background: var(--grey-subtitle-1);
+ border-radius: 5px;
+ border: 3px solid var(--in-content-button-text-color);
+ opacity: 0.35;
+ box-sizing: inherit;
+}
+.onboardingContainer .steps .indicator.current {
+ opacity: 1;
+ border-color: var(--checkbox-checked-bgcolor);
+}
+.onboardingContainer .steps .indicator.current:last-of-type:first-of-type {
+ opacity: 0;
+}
+.onboardingContainer .steps.progress-bar {
+ height: 6px;
+ padding-block: 0;
+ margin-block: 42px 0;
+ background-color: color-mix(in srgb, var(--in-content-button-text-color) 25%, transparent);
+ justify-content: start;
+ opacity: 1;
+ transition: none;
+}
+.onboardingContainer .steps.progress-bar .indicator {
+ width: 100%;
+ height: 100%;
+ margin-inline: -1px;
+ background-color: var(--checkbox-checked-bgcolor);
+ border: 0;
+ border-radius: 0;
+ opacity: 1;
+ transition: var(--progress-bar-transition);
+ translate: calc(var(--progress-bar-progress, 0%) - 100%);
+}
+.onboardingContainer .steps.progress-bar .indicator:dir(rtl) {
+ translate: calc(var(--progress-bar-progress, 0%) * -1 + 100%);
+}
+.onboardingContainer .additional-cta-container[flow] {
+ display: flex;
+ flex-flow: column wrap;
+ align-items: center;
+}
+.onboardingContainer .additional-cta-container[flow][flow=row] {
+ flex-direction: row;
+ justify-content: center;
+}
+.onboardingContainer .additional-cta-container[flow][flow=row] .secondary-cta {
+ flex-basis: 100%;
+}
+.onboardingContainer .primary,
+.onboardingContainer .secondary,
+.onboardingContainer .additional-cta {
+ font-size: 13px;
+ line-height: 16px;
+ padding: 11px 15px;
+ transition: var(--transition);
+}
+.onboardingContainer .primary.rtamo,
+.onboardingContainer .secondary.rtamo,
+.onboardingContainer .additional-cta.rtamo {
+ margin-top: 24px;
+}
+.onboardingContainer .secondary {
+ background-color: var(--in-content-button-background);
+ color: var(--in-content-button-text-color);
+}
+.onboardingContainer .noodle {
+ display: block;
+ background-repeat: no-repeat;
+ background-size: 100% 100%;
+ position: absolute;
+ transition: var(--transition);
+}
+.onboardingContainer .noodle:dir(rtl) {
+ scale: -1 1;
+}
+.onboardingContainer .outline-L {
+ background-image: url("chrome://activity-stream/content/data/content/assets/noodle-outline-L.svg");
+}
+.onboardingContainer .solid-L {
+ background-image: url("chrome://activity-stream/content/data/content/assets/noodle-solid-L.svg");
+ -moz-context-properties: fill;
+ fill: var(--in-content-page-background);
+ display: none;
+}
+.onboardingContainer .purple-C {
+ background-image: url("chrome://activity-stream/content/data/content/assets/noodle-C.svg");
+ -moz-context-properties: fill;
+ fill: #E7258C;
+}
+.onboardingContainer .orange-L {
+ background-image: url("chrome://activity-stream/content/data/content/assets/noodle-solid-L.svg");
+ -moz-context-properties: fill;
+ fill: #FFA437;
+}
+.onboardingContainer .screen-1 .section-main {
+ z-index: 1;
+ margin: auto;
+}
+.onboardingContainer .screen-1 .outline-L {
+ width: 87px;
+ height: 80px;
+ transform: rotate(10deg) translate(-30%, 200%);
+ transition-delay: 0.4s;
+ z-index: 2;
+}
+.onboardingContainer .screen-1 .orange-L {
+ width: 550px;
+ height: 660px;
+ transform: rotate(-155deg) translate(11%, -18%);
+ transition-delay: 0.2s;
+}
+.onboardingContainer .screen-1 .purple-C {
+ width: 310px;
+ height: 260px;
+ transform: translate(-18%, -67%);
+}
+.onboardingContainer .screen-1 .yellow-circle {
+ width: 165px;
+ height: 165px;
+ border-radius: 50%;
+ transform: translate(230%, -5%);
+ background: #952BB9;
+ transition-delay: -0.2s;
+}
+.onboardingContainer .dialog-initial .brand-logo {
+ transition-delay: 0.6s;
+}
+.onboardingContainer .dialog-initial .welcome-text {
+ transition-delay: 0.8s;
+}
+.onboardingContainer .dialog-initial .tiles-theme-section,
+.onboardingContainer .dialog-initial .multi-select-container,
+.onboardingContainer .dialog-initial migration-wizard {
+ transition-delay: 0.9s;
+}
+.onboardingContainer .dialog-initial .primary,
+.onboardingContainer .dialog-initial .secondary,
+.onboardingContainer .dialog-initial .secondary-cta,
+.onboardingContainer .dialog-initial .steps,
+.onboardingContainer .dialog-initial .cta-link {
+ transition-delay: 1s;
+}
+.onboardingContainer .screen:not(.dialog-initial) .tiles-theme-section,
+.onboardingContainer .screen:not(.dialog-initial) .multi-select-container,
+.onboardingContainer .screen:not(.dialog-initial) .colorway-text {
+ transition-delay: 0.2s;
+}
+.onboardingContainer .screen:not(.dialog-initial) .primary,
+.onboardingContainer .screen:not(.dialog-initial) .secondary,
+.onboardingContainer .screen:not(.dialog-initial) .secondary-cta,
+.onboardingContainer .screen:not(.dialog-initial) .cta-link {
+ transition-delay: 0.4s;
+}
+.onboardingContainer .screen-2 .section-main {
+ z-index: 1;
+ margin: auto;
+}
+.onboardingContainer .screen-2 .outline-L {
+ width: 87px;
+ height: 80px;
+ transform: rotate(250deg) translate(-420%, 425%);
+ transition-delay: 0.2s;
+ z-index: 2;
+}
+.onboardingContainer .screen-2 .orange-L {
+ height: 800px;
+ width: 660px;
+ transform: rotate(35deg) translate(-10%, -7%);
+ transition-delay: -0.4s;
+}
+.onboardingContainer .screen-2 .purple-C {
+ width: 392px;
+ height: 394px;
+ transform: rotate(260deg) translate(-34%, -35%);
+ transition-delay: -0.2s;
+ fill: #952BB9;
+}
+.onboardingContainer .screen-2 .yellow-circle {
+ width: 165px;
+ height: 165px;
+ border-radius: 50%;
+ transform: translate(160%, 130%);
+ background: #E7258C;
+}
+.onboardingContainer.transition-in .noodle {
+ opacity: 0;
+ rotate: var(--rotate);
+ scale: var(--scale);
+}
+.onboardingContainer.transition-in .dialog-initial .main-content,
+.onboardingContainer.transition-in .dialog-initial .dismiss-button {
+ translate: 0 calc(-2 * var(--translate));
+}
+.onboardingContainer.transition-in .dialog-initial .brand-logo,
+.onboardingContainer.transition-in .dialog-initial .steps {
+ opacity: 0;
+ translate: 0 calc(-1 * var(--translate));
+}
+.onboardingContainer.transition-in .screen .welcome-text,
+.onboardingContainer.transition-in .screen .multi-select-container,
+.onboardingContainer.transition-in .screen .tiles-theme-section,
+.onboardingContainer.transition-in .screen .colorway-text,
+.onboardingContainer.transition-in .screen .primary,
+.onboardingContainer.transition-in .screen .checkbox-container:not(.multi-select-item),
+.onboardingContainer.transition-in .screen .secondary,
+.onboardingContainer.transition-in .screen .secondary-cta:not(.top),
+.onboardingContainer.transition-in .screen .cta-link,
+.onboardingContainer.transition-in .screen migration-wizard {
+ opacity: 0;
+ translate: 0 calc(-1 * var(--translate));
+}
+.onboardingContainer.transition-in .screen:not(.dialog-initial) .steps:not(.progress-bar) {
+ opacity: 0.2;
+}
+.onboardingContainer.transition-out .noodle {
+ opacity: 0;
+ rotate: var(--rotate);
+ scale: var(--scale);
+ transition-delay: 0.2s;
+}
+.onboardingContainer.transition-out .screen:not(.dialog-last) .main-content {
+ overflow: hidden;
+}
+.onboardingContainer.transition-out .screen:not(.dialog-last) .welcome-text,
+.onboardingContainer.transition-out .screen:not(.dialog-last) .multi-select-container {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.1s;
+}
+.onboardingContainer.transition-out .screen:not(.dialog-last) .tiles-theme-section,
+.onboardingContainer.transition-out .screen:not(.dialog-last) .colorway-text,
+.onboardingContainer.transition-out .screen:not(.dialog-last) migration-wizard {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.2s;
+}
+.onboardingContainer.transition-out .screen:not(.dialog-last) .primary,
+.onboardingContainer.transition-out .screen:not(.dialog-last) .checkbox-container:not(.multi-select-item),
+.onboardingContainer.transition-out .screen:not(.dialog-last) .secondary,
+.onboardingContainer.transition-out .screen:not(.dialog-last) .secondary-cta:not(.top),
+.onboardingContainer.transition-out .screen:not(.dialog-last) .cta-link {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.3s;
+}
+.onboardingContainer.transition-out .screen:not(.dialog-last) .steps:not(.progress-bar) {
+ opacity: 0.2;
+ transition-delay: 0.5s;
+}
+.onboardingContainer.transition-out .dialog-last .noodle {
+ transition-delay: 0s;
+}
+.onboardingContainer.transition-out .dialog-last .main-content,
+.onboardingContainer.transition-out .dialog-last .dismiss-button {
+ opacity: 0;
+ translate: 0 calc(2 * var(--translate));
+ transition-delay: 0.4s;
+}
+.onboardingContainer migration-wizard {
+ width: unset;
+ transition: var(--transition);
+}
+.onboardingContainer migration-wizard::part(buttons) {
+ margin-top: 32px;
+ justify-content: flex-start;
+}
+.onboardingContainer migration-wizard::part(deck) {
+ font-size: 0.83em;
+}
diff --git a/browser/components/newtab/aboutwelcome/content/aboutwelcome.html b/browser/components/newtab/aboutwelcome/content/aboutwelcome.html
new file mode 100644
index 0000000000..a14b563057
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.html
@@ -0,0 +1,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/. -->
+
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="color-scheme" content="light dark" />
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; object-src 'none'; script-src resource: chrome:; media-src resource: chrome: https://assets.mozilla.net https://www.mozilla.org; connect-src https:; img-src https: data: blob: chrome:; 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://global/skin/in-content/common.css" />
+ <link
+ rel="stylesheet"
+ href="chrome://activity-stream/content/aboutwelcome/aboutwelcome.css"
+ />
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/newtab/onboarding.ftl" />
+ <link rel="localization" href="browser/spotlight.ftl" />
+ <link rel="localization" href="browser/migrationWizard.ftl" />
+ <link rel="localization" href="toolkit/branding/accounts.ftl" />
+ <link rel="localization" href="toolkit/branding/brandings.ftl" />
+ </head>
+ <body>
+ <div
+ id="multi-stage-message-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>
+ <script src="chrome://global/content/elements/named-deck.js" async></script>
+ <script src="chrome://global/content/elements/panel-list.js" async></script>
+ <script
+ src="chrome://browser/content/migration/migration-wizard.mjs"
+ type="module"
+ ></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm
new file mode 100644
index 0000000000..0e17a0b3ae
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm
@@ -0,0 +1,707 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 = ["AboutWelcomeDefaults"];
+
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AddonRepository: "resource://gre/modules/addons/AddonRepository.sys.mjs",
+ AttributionCode: "resource:///modules/AttributionCode.sys.mjs",
+ BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ AWScreenUtils: "resource://activity-stream/lib/AWScreenUtils.jsm",
+});
+
+// Message to be updated based on finalized MR designs
+const MR_ABOUT_WELCOME_DEFAULT = {
+ id: "MR_WELCOME_DEFAULT",
+ template: "multistage",
+ // Allow tests to easily disable transitions.
+ transitions: Services.prefs.getBoolPref(
+ "browser.aboutwelcome.transitions",
+ true
+ ),
+ backdrop:
+ "var(--mr-welcome-background-color) var(--mr-welcome-background-gradient)",
+ screens: [
+ {
+ id: "AW_WELCOME_BACK",
+ targeting: "isDeviceMigration",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-100px",
+ image_alt_text: {
+ string_id: "onboarding-device-migration-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/device-migration.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "onboarding-device-migration-title",
+ },
+ subtitle: {
+ string_id: "onboarding-device-migration-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-device-migration-primary-button-label",
+ },
+ action: {
+ type: "FXA_SIGNIN_FLOW",
+ navigate: "actionResult",
+ data: {
+ entrypoint: "fx-device-migration-onboarding",
+ extraParams: {
+ utm_content: "migration-onboarding",
+ utm_source: "fx-new-device-sync",
+ utm_medium: "firefox-desktop",
+ utm_campaign: "migration",
+ },
+ },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_EASY_SETUP",
+ targeting:
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-60px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-default-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-settodefault.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-set-default-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-set-default-subtitle",
+ },
+ tiles: {
+ type: "multiselect",
+ data: [
+ {
+ id: "checkbox-1",
+ defaultValue: true,
+ label: {
+ string_id:
+ "mr2022-onboarding-easy-setup-set-default-checkbox-label",
+ },
+ action: {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ {
+ id: "checkbox-2",
+ defaultValue: true,
+ label: {
+ string_id: "mr2022-onboarding-easy-setup-import-checkbox-label",
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ },
+ ],
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-easy-setup-primary-button-label",
+ },
+ action: {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ navigate: true,
+ data: {
+ actions: [],
+ },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ secondary_button_top: {
+ label: {
+ string_id: "mr1-onboarding-sign-in-button-label",
+ },
+ action: {
+ data: {
+ entrypoint: "activity-stream-firstrun",
+ where: "tab",
+ },
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: true,
+ },
+ },
+ },
+ },
+ {
+ id: "AW_PIN_FIREFOX",
+ targeting:
+ "!(os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin)",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-155px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-pin-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-pintaskbar.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-welcome-pin-header",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-welcome-pin-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-pin-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ secondary_button_top: {
+ label: {
+ string_id: "mr1-onboarding-sign-in-button-label",
+ },
+ action: {
+ data: {
+ entrypoint: "activity-stream-firstrun",
+ where: "tab",
+ },
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: true,
+ },
+ },
+ },
+ },
+ {
+ id: "AW_LANGUAGE_MISMATCH",
+ content: {
+ position: "split",
+ background: "var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-live-language-text",
+ },
+ subtitle: {
+ string_id: "mr2022-language-mismatch-subtitle",
+ },
+ hero_text: {
+ string_id: "mr2022-onboarding-live-language-text",
+ useLangPack: true,
+ },
+ languageSwitcher: {
+ downloading: {
+ string_id: "onboarding-live-language-button-label-downloading",
+ },
+ cancel: {
+ string_id: "onboarding-live-language-secondary-cancel-download",
+ },
+ waiting: { string_id: "onboarding-live-language-waiting-button" },
+ skip: { string_id: "mr2022-onboarding-secondary-skip-button-label" },
+ action: {
+ navigate: true,
+ },
+ switch: {
+ string_id: "mr2022-onboarding-live-language-switch-to",
+ useLangPack: true,
+ },
+ continue: {
+ string_id: "mr2022-onboarding-live-language-continue-in",
+ },
+ },
+ },
+ },
+ {
+ id: "AW_SET_DEFAULT",
+ targeting:
+ "!(os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin)",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-60px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-default-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-settodefault.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-set-default-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-set-default-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-set-default-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_IMPORT_SETTINGS",
+ targeting:
+ "!(os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin) && !useEmbeddedMigrationWizard",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-42px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-import-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-import.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-import-header",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-import-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id:
+ "mr2022-onboarding-import-primary-button-label-no-attribution",
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_IMPORT_SETTINGS_EMBEDDED",
+ targeting:
+ "!(os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin) && useEmbeddedMigrationWizard",
+ content: {
+ tiles: { type: "migration-wizard" },
+ position: "split",
+ split_narrow_bkg_position: "-42px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-import-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-import.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ migrate_start: {
+ action: {},
+ },
+ migrate_close: {
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_MOBILE_DOWNLOAD",
+ // The mobile download screen should only be shown to users who
+ // are either not logged into FxA, or don't have any mobile devices syncing
+ targeting: "!isFxASignedIn || sync.mobileDevices == 0",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-160px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-mobile-download-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-mobilecrosspromo.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-mobile-download-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-mobile-download-subtitle",
+ },
+ hero_image: {
+ url: "chrome://activity-stream/content/data/content/assets/mobile-download-qr-new-user.svg",
+ },
+ cta_paragraph: {
+ text: {
+ string_id: "mr2022-onboarding-mobile-download-cta-text",
+ string_name: "download-label",
+ },
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://www.mozilla.org/firefox/mobile/get-app/?utm_medium=firefox-desktop&utm_source=onboarding-modal&utm_campaign=mr2022&utm_content=new-global",
+ where: "tab",
+ },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_GRATITUDE",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-228px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-gratitude-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-gratitude.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-gratitude-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-gratitude-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2-onboarding-start-browsing-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+};
+
+async function getAddonFromRepository(data) {
+ const [addonInfo] = await lazy.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"],
+ type: addonInfo.type,
+ screenshots: addonInfo.screenshots,
+ };
+}
+
+async function 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_to_amo embeds the addon id in the content
+ // param, prefixed with "rta:". Translating that
+ // happens in AddonRepository, however we can avoid
+ // an API call if we check up front here.
+ if (content.startsWith("rta:")) {
+ return await getAddonFromRepository(content);
+ }
+ } catch (e) {
+ console.error("Failed to get the latest add-on version for Return to AMO");
+ }
+ return null;
+}
+
+async function getAttributionContent() {
+ let attribution = await lazy.AttributionCode.getAttrDataAsync();
+ if (attribution?.source === "addons.mozilla.org") {
+ let addonInfo = await getAddonInfo(attribution);
+ if (addonInfo) {
+ return {
+ ...addonInfo,
+ template: "return_to_amo",
+ };
+ }
+ }
+ if (attribution?.ua) {
+ return {
+ ua: decodeURIComponent(attribution.ua),
+ };
+ }
+ return null;
+}
+
+// Return default multistage welcome content
+function getDefaults() {
+ return Cu.cloneInto(MR_ABOUT_WELCOME_DEFAULT, {});
+}
+
+let gSourceL10n = null;
+
+// Localize Firefox download source from user agent attribution to show inside
+// import primary button label such as 'Import from <localized browser name>'.
+// no firefox as import wizard doesn't show it
+const allowedUAs = ["chrome", "edge", "ie"];
+function getLocalizedUA(ua) {
+ if (!gSourceL10n) {
+ gSourceL10n = new Localization(["browser/migration.ftl"]);
+ }
+ if (allowedUAs.includes(ua)) {
+ return gSourceL10n.formatValue(`source-name-${ua.toLowerCase()}`);
+ }
+ return null;
+}
+
+// Function to evalute the appropriate string for the welcome screen button label
+function evaluateWelcomeScreenButtonLabel(removeDefault) {
+ return removeDefault
+ ? "mr2022-onboarding-get-started-primary-button-label"
+ : "mr2022-onboarding-set-default-primary-button-label";
+}
+
+function prepareMobileDownload(content) {
+ let mobileContent = content?.screens?.find(
+ screen => screen.id === "AW_MOBILE_DOWNLOAD"
+ )?.content;
+
+ if (!mobileContent) {
+ return content;
+ }
+ if (!lazy.BrowserUtils.sendToDeviceEmailsSupported()) {
+ // If send to device emails are not supported for a user's locale,
+ // remove the send to device link and update the screen text
+ delete mobileContent.cta_paragraph.action;
+ mobileContent.cta_paragraph.text = {
+ string_id: "mr2022-onboarding-no-mobile-download-cta-text",
+ };
+ }
+ // Update CN specific QRCode url
+ if (AppConstants.isChinaRepack()) {
+ mobileContent.hero_image.url = `${mobileContent.hero_image.url.slice(
+ 0,
+ mobileContent.hero_image.url.indexOf(".svg")
+ )}-cn.svg`;
+ }
+
+ return content;
+}
+
+async function prepareContentForReact(content) {
+ const { screens } = content;
+
+ if (content?.template === "return_to_amo") {
+ return content;
+ }
+
+ // Change content for Windows 7 because non-light themes aren't quite right.
+ if (AppConstants.isPlatformAndVersionAtMost("win", "6.1")) {
+ await lazy.AWScreenUtils.removeScreens(screens, screen =>
+ ["theme"].includes(screen.content?.tiles?.type)
+ );
+ }
+
+ // Set the primary import button source based on attribution.
+ if (content?.ua) {
+ // If available, add the browser source to action data
+ // and localized browser string args to primary button label
+ const { label, action } =
+ content?.screens?.find(
+ screen =>
+ screen?.content?.primary_button?.action?.type ===
+ "SHOW_MIGRATION_WIZARD"
+ )?.content?.primary_button ?? {};
+
+ if (action) {
+ action.data = { ...action.data, source: content.ua };
+ }
+
+ let browserStr = await getLocalizedUA(content.ua);
+
+ if (label?.string_id) {
+ label.string_id = browserStr
+ ? "mr1-onboarding-import-primary-button-label-attribution"
+ : "mr2022-onboarding-import-primary-button-label-no-attribution";
+
+ label.args = browserStr ? { previous: browserStr } : {};
+ }
+ }
+
+ // If already pinned, convert "pin" screen to "welcome" with desired action.
+ let removeDefault = !content.needDefault;
+ if (!content.needPin) {
+ const pinScreen = content.screens?.find(screen =>
+ screen.id?.startsWith("AW_PIN_FIREFOX")
+ );
+ if (pinScreen?.content) {
+ pinScreen.id = removeDefault ? "AW_GET_STARTED" : "AW_ONLY_DEFAULT";
+ pinScreen.content.title = {
+ string_id: "mr2022-onboarding-welcome-pin-header",
+ };
+
+ pinScreen.content.subtitle = {
+ string_id: removeDefault
+ ? "mr2022-onboarding-get-started-primary-subtitle"
+ : "mr2022-onboarding-set-default-only-subtitle",
+ };
+
+ pinScreen.content.primary_button = {
+ label: {
+ string_id: evaluateWelcomeScreenButtonLabel(removeDefault, content),
+ },
+ action: {
+ navigate: true,
+ },
+ };
+ // Get started content will navigate without action, so remove "Not now."
+ if (!removeDefault) {
+ // The "pin" screen will now handle "default" so remove other "default."
+ pinScreen.content.primary_button.action.type = "SET_DEFAULT_BROWSER";
+ removeDefault = true;
+ }
+ }
+ }
+ if (removeDefault) {
+ await lazy.AWScreenUtils.removeScreens(screens, screen =>
+ screen.id?.startsWith("AW_SET_DEFAULT")
+ );
+ }
+
+ // Remove Firefox Accounts related UI and prevent related metrics.
+ if (!Services.prefs.getBoolPref("identity.fxaccounts.enabled", false)) {
+ delete content.screens?.find(
+ screen =>
+ screen.content?.secondary_button_top?.action?.type ===
+ "SHOW_FIREFOX_ACCOUNTS"
+ )?.content.secondary_button_top;
+ content.skipFxA = true;
+ }
+
+ // Remove the English-only image caption.
+ if (Services.locale.appLocaleAsBCP47.split("-")[0] !== "en") {
+ delete content.screens?.find(
+ screen => screen.content?.help_text?.deleteIfNotEn
+ )?.content.help_text;
+ }
+
+ let shouldRemoveLanguageMismatchScreen = true;
+ if (content.languageMismatchEnabled) {
+ const screen = content?.screens?.find(s => s.id === "AW_LANGUAGE_MISMATCH");
+ if (screen && content.appAndSystemLocaleInfo.canLiveReload) {
+ // Add the display names for the OS and Firefox languages, like "American English".
+ function addMessageArgs(obj) {
+ for (const value of Object.values(obj)) {
+ if (value?.string_id) {
+ value.args = content.appAndSystemLocaleInfo.displayNames;
+ }
+ }
+ }
+
+ addMessageArgs(screen.content.languageSwitcher);
+ addMessageArgs(screen.content);
+ shouldRemoveLanguageMismatchScreen = false;
+ }
+ }
+
+ if (shouldRemoveLanguageMismatchScreen) {
+ await lazy.AWScreenUtils.removeScreens(
+ screens,
+ screen => screen.id === "AW_LANGUAGE_MISMATCH"
+ );
+ }
+
+ return prepareMobileDownload(content);
+}
+
+const AboutWelcomeDefaults = {
+ prepareContentForReact,
+ getDefaults,
+ getAttributionContent,
+};
diff --git a/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm
new file mode 100644
index 0000000000..b8bdd44794
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm
@@ -0,0 +1,242 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AttributionCode: "resource:///modules/AttributionCode.sys.mjs",
+ ClientID: "resource://gre/modules/ClientID.sys.mjs",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ PingCentre: "resource:///modules/PingCentre.jsm",
+});
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "structuredIngestionEndpointBase",
+ "browser.newtabpage.activity-stream.telemetry.structuredIngestion.endpoint",
+ ""
+);
+XPCOMUtils.defineLazyGetter(lazy, "telemetryClientId", () =>
+ lazy.ClientID.getClientID()
+);
+XPCOMUtils.defineLazyGetter(
+ lazy,
+ "browserSessionId",
+ () => lazy.TelemetrySession.getMetadata("").sessionId
+);
+
+XPCOMUtils.defineLazyGetter(lazy, "log", () => {
+ const { Logger } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/Logger.sys.mjs"
+ );
+ return new Logger("AboutWelcomeTelemetry");
+});
+
+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 lazy.PingCentre({ topic: TELEMETRY_TOPIC }),
+ });
+ return this.pingCentre;
+ }
+
+ _generateStructuredIngestionEndpoint() {
+ const uuid = Services.uuid.generateUUID().toString();
+ // Structured Ingestion does not support the UUID generated by Services.uuid,
+ // 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 `${lazy.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 = lazy.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 lazy.telemetryClientId,
+ browser_session_id: lazy.browserSessionId,
+ };
+
+ return this._maybeAttachAttribution(ping);
+ }
+
+ /**
+ * Augment the provided event with some metadata and then send it
+ * to the messaging-system's onboarding endpoint.
+ *
+ * Is sometimes used by non-onboarding events.
+ *
+ * @param event - an object almost certainly from an onboarding flow (though
+ * there is a case where spotlight may use this, too)
+ * containing a nested structure of data for reporting as
+ * telemetry, as documented in
+ * https://firefox-source-docs.mozilla.org/browser/components/newtab/docs/v2-system-addon/data_events.html
+ * Does not have all of its data (`_createPing` will augment
+ * with ids and attribution if available).
+ */
+ async sendTelemetry(event) {
+ if (!this.telemetryEnabled) {
+ return;
+ }
+
+ const ping = await this._createPing(event);
+
+ try {
+ this.submitGleanPingForPing(ping);
+ } catch (e) {
+ // Though Glean APIs are forbidden to throw, it may be possible that a
+ // mismatch between the shape of `ping` and the defined metrics is not
+ // adequately handled.
+ Glean.messagingSystem.gleanPingForPingFailures.add(1);
+ }
+
+ this.pingCentre.sendStructuredIngestionPing(
+ ping,
+ this._generateStructuredIngestionEndpoint(),
+ STRUCTURED_INGESTION_NAMESPACE_MS
+ );
+ }
+
+ /**
+ * Tries to infer appropriate Glean metrics on the "messaging-system" ping,
+ * sets them, and submits a "messaging-system" ping.
+ *
+ * Does not check if telemetry is enabled.
+ * (Though Glean will check the global prefs).
+ *
+ * Note: This is a very unusual use of Glean that is specific to the use-
+ * cases of Messaging System. Please do not copy this pattern.
+ */
+ submitGleanPingForPing(ping) {
+ lazy.log.debug(`Submitting Glean ping for ${JSON.stringify(ping)}`);
+ // event.event_context is an object, but it may have been stringified.
+ let event_context = ping?.event_context;
+ if (typeof event_context === "string") {
+ try {
+ event_context = JSON.parse(event_context);
+ } catch (e) {
+ Glean.messagingSystem.eventContextParseError.add(1);
+ }
+ }
+
+ // We echo certain properties from event_context into their own metrics
+ // to aid analysis.
+ if (event_context?.reason) {
+ Glean.messagingSystem.eventReason.set(event_context.reason);
+ }
+ if (event_context?.page) {
+ Glean.messagingSystem.eventPage.set(event_context.page);
+ }
+ if (event_context?.source) {
+ Glean.messagingSystem.eventSource.set(event_context.source);
+ }
+
+ // The event_context is also provided as-is as stringified JSON.
+ if (event_context) {
+ Glean.messagingSystem.eventContext.set(JSON.stringify(event_context));
+ }
+
+ if ("attribution" in ping) {
+ for (const [key, value] of Object.entries(ping.attribution)) {
+ const camelKey = this._snakeToCamelCase(key);
+ try {
+ Glean.messagingSystemAttribution[camelKey].set(value);
+ } catch (e) {
+ // We here acknowledge that we don't know the full breadth of data
+ // being collected. Ideally AttributionCode will later centralize
+ // definition and reporting of attribution data and we can be rid of
+ // this fail-safe for collecting the names of unknown keys.
+ Glean.messagingSystemAttribution.unknownKeys[camelKey].add(1);
+ }
+ }
+ }
+
+ // List of keys handled above.
+ const handledKeys = ["event_context", "attribution"];
+
+ for (const [key, value] of Object.entries(ping)) {
+ if (handledKeys.includes(key)) {
+ continue;
+ }
+ const camelKey = this._snakeToCamelCase(key);
+ try {
+ // We here acknowledge that even known keys might have non-scalar
+ // values. We're pretty sure we handled them all with handledKeys,
+ // but we might not have.
+ // Ideally this can later be removed after running for a version or two
+ // with no values seen in messaging_system.invalid_nested_data
+ if (typeof value === "object") {
+ Glean.messagingSystem.invalidNestedData[camelKey].add(1);
+ } else {
+ Glean.messagingSystem[camelKey].set(value);
+ }
+ } catch (e) {
+ // We here acknowledge that we don't know the full breadth of data being
+ // collected. Ideally we will later gain that confidence and can remove
+ // this fail-safe for collecting the names of unknown keys.
+ Glean.messagingSystem.unknownKeys[camelKey].add(1);
+ // TODO(bug 1600008): For testing, also record the overall count.
+ Glean.messagingSystem.unknownKeyCount.add(1);
+ }
+ }
+
+ // With all the metrics set, now it's time to submit this ping.
+ GleanPings.messagingSystem.submit();
+ }
+
+ _snakeToCamelCase(s) {
+ return s.toString().replace(/_([a-z])/gi, (_str, group) => {
+ return group.toUpperCase();
+ });
+ }
+}
diff --git a/browser/components/newtab/actors/ASRouterChild.sys.mjs b/browser/components/newtab/actors/ASRouterChild.sys.mjs
new file mode 100644
index 0000000000..bd2c030fab
--- /dev/null
+++ b/browser/components/newtab/actors/ASRouterChild.sys.mjs
@@ -0,0 +1,111 @@
+/* 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/. */
+
+import {
+ MESSAGE_TYPE_LIST,
+ MESSAGE_TYPE_HASH as msg,
+} from "resource://activity-stream/common/ActorConstants.sys.mjs";
+
+const VALID_TYPES = new Set(MESSAGE_TYPE_LIST);
+
+export class ASRouterChild extends JSWindowActorChild {
+ constructor() {
+ super();
+ this.observers = new Set();
+ }
+
+ didDestroy() {
+ this.observers.clear();
+ }
+
+ actorCreated() {
+ // NOTE: DOMDocElementInserted may be called multiple times per
+ // PWindowGlobal due to the initial about:blank document's window global
+ // being re-used.
+ 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",
+ });
+ }
+
+ handleEvent(event) {
+ // DOMDocElementCreated is only used to create the actor.
+ }
+
+ 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.FORCE_PRIVATE_BROWSING_WINDOW:
+ 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.sys.mjs b/browser/components/newtab/actors/ASRouterParent.sys.mjs
new file mode 100644
index 0000000000..9c785faaa5
--- /dev/null
+++ b/browser/components/newtab/actors/ASRouterParent.sys.mjs
@@ -0,0 +1,103 @@
+/* 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/. */
+
+import { MESSAGE_TYPE_HASH } from "resource://activity-stream/common/ActorConstants.sys.mjs";
+
+import { ASRouterNewTabHook } from "resource://activity-stream/lib/ASRouterNewTabHook.sys.mjs";
+
+const { ASRouterDefaultConfig } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterDefaultConfig.jsm"
+);
+
+export 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))
+ );
+ }
+
+ registerActor(actor) {
+ this.actors.add(actor);
+ }
+
+ unregisterActor(actor) {
+ this.actors.delete(actor);
+ }
+}
+
+const defaultTabsFactory = () =>
+ new ASRouterTabs({ asRouterNewTabHook: ASRouterNewTabHook });
+
+export 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 === MESSAGE_TYPE_HASH.BLOCK_MESSAGE_BY_ID) {
+ return Promise.all([
+ handler.handleMessage(name, data, this.getTab()),
+ // All tabs should clear messages not just preloaded, for example
+ // two different windows can display the same snippet.
+ // ASRouter blocks snippets by campaign not by id so we just tell
+ // other tabs that this specific campaign was blocked.
+ ASRouterParent.tabs.messageAll("ClearMessages", [data.campaign]),
+ ]).then(([handleMessageResult]) => handleMessageResult);
+ }
+ 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..d87c096b4c
--- /dev/null
+++ b/browser/components/newtab/bin/render-activity-stream-html.js
@@ -0,0 +1,146 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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")}`;
+
+ // The markup below needs to be formatted by Prettier. But any diff after
+ // running this script should be caught by try-runnner.js
+ 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: chrome:; style-src 'unsafe-inline';"
+ />
+ <meta name="color-scheme" content="light dark" />
+ <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="toolkit/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) {
+ fs.writeFileSync(path.join(destPath, file), templater({ options }));
+ console.log("\x1b[32m", `✓ ${file}`, "\x1b[0m");
+ }
+}
+
+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..78ee2c1be4
--- /dev/null
+++ b/browser/components/newtab/bin/try-runner.js
@@ -0,0 +1,193 @@
+/* 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/rev/c3453c7a0427eb27d467e1582f821f402aed9850/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}`);
+}
+
+const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
+
+function checkBundles() {
+ logStart("checkBundles");
+
+ const items = {
+ "Activity Stream bundle": {
+ path: path.join("data", "content", "activity-stream.bundle.js"),
+ },
+ "activity-stream.html": {
+ path: path.join("prerendered", "activity-stream.html"),
+ },
+ "activity-stream-debug.html": {
+ path: path.join("prerendered", "activity-stream-debug.html"),
+ },
+ "activity-stream-noscripts.html": {
+ path: path.join("prerendered", "activity-stream-noscripts.html"),
+ },
+ "activity-stream-linux.css": {
+ path: path.join("css", "activity-stream-linux.css"),
+ },
+ "activity-stream-mac.css": {
+ path: path.join("css", "activity-stream-mac.css"),
+ },
+ "activity-stream-windows.css": {
+ path: path.join("css", "activity-stream-windows.css"),
+ },
+ "About:welcome bundle": {
+ path: path.join("aboutwelcome", "content", "aboutwelcome.bundle.js"),
+ },
+ "aboutwelcome.css": {
+ path: path.join("aboutwelcome", "content", "aboutwelcome.css"),
+ },
+ };
+ const errors = [];
+
+ for (const name of Object.keys(items)) {
+ const item = items[name];
+ item.before = readFileSync(item.path, item.encoding || "utf8");
+ }
+
+ let bundleExitCode = execOut(npmCommand, ["run", "bundle"]).exitCode;
+
+ for (const name of Object.keys(items)) {
+ const item = items[name];
+ const after = readFileSync(item.path, item.encoding || "utf8");
+
+ if (item.before !== after) {
+ errors.push(`${name} out of date`);
+ }
+ }
+
+ if (bundleExitCode !== 0) {
+ errors.push("npm:bundle did not run successfully");
+ }
+
+ logErrors("checkBundles", errors);
+ return errors.length === 0;
+}
+
+function karma() {
+ logStart("karma");
+
+ const errors = [];
+ const { exitCode, out } = execOut(npmCommand, [
+ "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);
+
+ console.log("-----karma stdout below this line---");
+ console.log(out);
+ console.log("-----karma stdout above this line---");
+
+ // Pass if there's no detected errors and nothing unexpected.
+ return errors.length === 0 && !exitCode;
+}
+
+function zipCodeCoverage() {
+ logStart("zipCodeCoverage");
+ const { exitCode, out } = execOut("zip", [
+ "-j",
+ "logs/coverage/code-coverage-grcov",
+ "logs/coverage/lcov.info",
+ ]);
+
+ console.log("zipCodeCoverage log output: ", out);
+
+ if (!exitCode) {
+ return true;
+ }
+
+ return false;
+}
+
+const tests = {};
+const success = [checkBundles, karma, zipCodeCoverage].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.sys.mjs b/browser/components/newtab/common/Actions.sys.mjs
new file mode 100644
index 0000000000..16dfd5dabf
--- /dev/null
+++ b/browser/components/newtab/common/Actions.sys.mjs
@@ -0,0 +1,459 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 MAIN_MESSAGE_TYPE = "ActivityStream:Main";
+export const CONTENT_MESSAGE_TYPE = "ActivityStream:Content";
+export const PRELOAD_MESSAGE_TYPE = "ActivityStream:PreloadedBrowser";
+export const UI_CODE = 1;
+export const 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.
+ */
+export const globalImportContext =
+ typeof Window === "undefined" ? BACKGROUND_PROCESS : UI_CODE;
+
+// Create an object that avoids accidental differing key/value pairs:
+// {
+// INIT: "INIT",
+// UNINIT: "UNINIT"
+// }
+export 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",
+ "DISABLE_SEARCH",
+ "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_EXPERIMENT_DATA",
+ "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_TOGGLE",
+ "DISCOVERY_STREAM_POCKET_STATE_INIT",
+ "DISCOVERY_STREAM_POCKET_STATE_SET",
+ "DISCOVERY_STREAM_PREFS_SETUP",
+ "DISCOVERY_STREAM_RECENT_SAVES",
+ "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",
+ "DISCOVERY_STREAM_USER_EVENT",
+ "DOWNLOAD_CHANGED",
+ "FAKE_FOCUS_SEARCH",
+ "FILL_SEARCH_TERM",
+ "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ "HIDE_PERSONALIZE",
+ "HIDE_PRIVACY_INFO",
+ "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_BOOKMARKS_REMOVED",
+ "PLACES_BOOKMARK_ADDED",
+ "PLACES_HISTORY_CLEARED",
+ "PLACES_LINKS_CHANGED",
+ "PLACES_LINKS_DELETED",
+ "PLACES_LINK_BLOCKED",
+ "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_PERSONALIZE",
+ "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_ORGANIC_IMPRESSION_STATS",
+ "TOP_SITES_PIN",
+ "TOP_SITES_PREFS_UPDATED",
+ "TOP_SITES_SPONSORED_IMPRESSION_STATS",
+ "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,
+ });
+}
+
+/**
+ * DiscoveryStreamUserEvent - A telemetry ping indicating a user action from Discovery Stream. 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 DiscoveryStreamUserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.DISCOVERY_STREAM_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;
+}
+
+export const actionCreators = {
+ BroadcastToContent,
+ UserEvent,
+ DiscoveryStreamUserEvent,
+ ASRouterUserEvent,
+ ImpressionStats,
+ AlsoToOneContent,
+ OnlyToOneContent,
+ AlsoToMain,
+ OnlyToMain,
+ AlsoToPreloaded,
+ SetPref,
+ WebExtEvent,
+ DiscoveryStreamImpressionStats,
+ DiscoveryStreamLoadedContent,
+};
+
+// These are helpers to test for certain kinds of actions
+export const 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,
+};
diff --git a/browser/components/newtab/common/ActorConstants.sys.mjs b/browser/components/newtab/common/ActorConstants.sys.mjs
new file mode 100644
index 0000000000..c2874b53dd
--- /dev/null
+++ b/browser/components/newtab/common/ActorConstants.sys.mjs
@@ -0,0 +1,47 @@
+/* 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/. */
+
+export const MESSAGE_TYPE_LIST = [
+ "BLOCK_MESSAGE_BY_ID",
+ "USER_ACTION",
+ "IMPRESSION",
+ "TRIGGER",
+ "NEWTAB_MESSAGE_REQUEST",
+ // PB is Private Browsing
+ "PBNEWTAB_MESSAGE_REQUEST",
+ "DOORHANGER_TELEMETRY",
+ "TOOLBAR_BADGE_TELEMETRY",
+ "TOOLBAR_PANEL_TELEMETRY",
+ "MOMENTS_PAGE_TELEMETRY",
+ "INFOBAR_TELEMETRY",
+ "SPOTLIGHT_TELEMETRY",
+ "TOAST_NOTIFICATION_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",
+ "FORCE_PRIVATE_BROWSING_WINDOW",
+ "CLOSE_WHATSNEW_PANEL",
+ "OVERRIDE_MESSAGE",
+ "MODIFY_MESSAGE_JSON",
+ "RESET_PROVIDER_PREF",
+ "SET_PROVIDER_USER_PREF",
+ "RESET_GROUPS_STATE",
+];
+
+export const MESSAGE_TYPE_HASH = MESSAGE_TYPE_LIST.reduce((hash, value) => {
+ hash[value] = value;
+ return hash;
+}, {});
diff --git a/browser/components/newtab/common/Dedupe.sys.mjs b/browser/components/newtab/common/Dedupe.sys.mjs
new file mode 100644
index 0000000000..eedca8a0ee
--- /dev/null
+++ b/browser/components/newtab/common/Dedupe.sys.mjs
@@ -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/. */
+
+export 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()));
+ }
+}
diff --git a/browser/components/newtab/common/Reducers.sys.mjs b/browser/components/newtab/common/Reducers.sys.mjs
new file mode 100644
index 0000000000..f0c0de4c82
--- /dev/null
+++ b/browser/components/newtab/common/Reducers.sys.mjs
@@ -0,0 +1,864 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { actionTypes as at } from "resource://activity-stream/common/Actions.sys.mjs";
+import { Dedupe } from "resource://activity-stream/common/Dedupe.sys.mjs";
+
+export const TOP_SITES_DEFAULT_ROWS = 1;
+export const TOP_SITES_MAX_SITES_PER_ROW = 8;
+const PREF_COLLECTION_DISMISSIBLE = "discoverystream.isCollectionDismissible";
+
+const dedupe = new Dedupe(site => site && site.url);
+
+export const INITIAL_STATE = {
+ App: {
+ // Have we received real data from the app yet?
+ initialized: false,
+ locale: "",
+ isForStartupCache: false,
+ customizeMenuVisible: false,
+ },
+ 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: { featureConfig: {} },
+ },
+ 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: [],
+ },
+ experimentData: {
+ utmSource: "pocket-newtab",
+ utmCampaign: undefined,
+ utmContent: undefined,
+ },
+ recentSavesData: [],
+ isUserLoggedIn: false,
+ recentSavesEnabled: false,
+ },
+ Personalization: {
+ 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,
+ });
+ case at.TOP_SITES_UPDATED:
+ // Toggle `isForStartupCache` when receiving the `TOP_SITES_UPDATE` action
+ // so that sponsored tiles can be rendered as usual. See Bug 1826360.
+ return Object.assign({}, prevState, action.data || {}, {
+ isForStartupCache: false,
+ });
+ case at.SHOW_PERSONALIZE:
+ return Object.assign({}, prevState, {
+ customizeMenuVisible: true,
+ });
+ case at.HIDE_PERSONALIZE:
+ return Object.assign({}, prevState, {
+ customizeMenuVisible: false,
+ });
+ 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
+ */
+export 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_BOOKMARKS_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.map(site => {
+ if (site && action.data.urls.includes(site.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_LINKS_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.filter(
+ site => !action.data.urls.includes(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_BOOKMARKS_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 (action.data.urls.includes(item.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_LINKS_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.filter(
+ site => !action.data.urls.includes(site.url)
+ ),
+ })
+ );
+ 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_LAST_UPDATED:
+ return {
+ ...prevState,
+ lastUpdated: action.data.lastUpdated,
+ };
+ case at.DISCOVERY_STREAM_PERSONALIZATION_INIT:
+ return {
+ ...prevState,
+ initialized: true,
+ };
+ 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_EXPERIMENT_DATA:
+ return { ...prevState, experimentData: 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.DISCOVERY_STREAM_PREFS_SETUP:
+ return {
+ ...prevState,
+ recentSavesEnabled: action.data.recentSavesEnabled,
+ pocketButtonEnabled: action.data.pocketButtonEnabled,
+ saveToPocketCard: action.data.saveToPocketCard,
+ hideDescriptions: action.data.hideDescriptions,
+ compactImages: action.data.compactImages,
+ imageGradient: action.data.imageGradient,
+ newSponsoredLabel: action.data.newSponsoredLabel,
+ titleLines: action.data.titleLines,
+ descLines: action.data.descLines,
+ readTime: action.data.readTime,
+ };
+ case at.DISCOVERY_STREAM_RECENT_SAVES:
+ return {
+ ...prevState,
+ recentSavesData: action.data.recentSaves,
+ };
+ case at.DISCOVERY_STREAM_POCKET_STATE_SET:
+ return {
+ ...prevState,
+ isUserLoggedIn: action.data.isUserLoggedIn,
+ };
+ 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_BOOKMARKS_REMOVED:
+ const removeBookmarkInfo = item => {
+ if (action.data.urls.includes(item.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.DISABLE_SEARCH:
+ return Object.assign({ ...prevState, disable: true });
+ case at.FAKE_FOCUS_SEARCH:
+ return Object.assign({ ...prevState, fakeFocus: true });
+ case at.SHOW_SEARCH:
+ return Object.assign({ ...prevState, disable: false, fakeFocus: false });
+ default:
+ return prevState;
+ }
+}
+
+export const reducers = {
+ TopSites,
+ App,
+ ASRouter,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization,
+ DiscoveryStream,
+ Search,
+};
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..570183667e
--- /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.importESModule(
+ "resource://activity-stream/lib/RemoteL10n.sys.mjs"
+ );
+ 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..18ef140618
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.jsx
@@ -0,0 +1,140 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { AboutWelcomeUtils } from "../lib/aboutwelcome-utils";
+import { MultiStageAboutWelcome } from "./components/MultiStageAboutWelcome";
+import { ReturnToAMO } from "./components/ReturnToAMO";
+
+class AboutWelcome extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { metricsFlowUri: null };
+ this.fetchFxAFlowUri = this.fetchFxAFlowUri.bind(this);
+ }
+
+ async fetchFxAFlowUri() {
+ this.setState({ metricsFlowUri: await window.AWGetFxAMetricsFlowURI?.() });
+ }
+
+ componentDidMount() {
+ if (!this.props.skipFxA) {
+ this.fetchFxAFlowUri();
+ }
+ // Record impression with performance data after allowing the page to load
+ const recordImpression = domState => {
+ const { domComplete, domInteractive } = performance
+ .getEntriesByType("navigation")
+ .pop();
+ AboutWelcomeUtils.sendImpressionTelemetry(this.props.messageId, {
+ domComplete,
+ domInteractive,
+ mountStart: performance.getEntriesByName("mount").pop().startTime,
+ domState,
+ source: this.props.UTMTerm,
+ });
+ };
+ 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);
+ }
+
+ render() {
+ const { props } = this;
+ if (props.template === "return_to_amo") {
+ return (
+ <ReturnToAMO
+ message_id={props.messageId}
+ type={props.type}
+ name={props.name}
+ url={props.url}
+ iconURL={props.iconURL}
+ themeScreenshots={props.screenshots}
+ metricsFlowUri={this.state.metricsFlowUri}
+ />
+ );
+ }
+ return (
+ <MultiStageAboutWelcome
+ message_id={props.messageId}
+ defaultScreens={props.screens}
+ updateHistory={!props.disableHistoryUpdates}
+ metricsFlowUri={this.state.metricsFlowUri}
+ utm_term={props.UTMTerm}
+ transitions={props.transitions}
+ backdrop={props.backdrop}
+ startScreen={props.startScreen || 0}
+ appAndSystemLocaleInfo={props.appAndSystemLocaleInfo}
+ />
+ );
+ }
+}
+
+// Computes messageId and UTMTerm info used in telemetry
+function ComputeTelemetryInfo(welcomeContent, experimentId, branchId) {
+ let messageId =
+ welcomeContent.template === "return_to_amo"
+ ? `RTAMO_DEFAULT_WELCOME_${welcomeContent.type.toUpperCase()}`
+ : "DEFAULT_ID";
+ let UTMTerm = "aboutwelcome-default";
+
+ if (welcomeContent.id) {
+ messageId = welcomeContent.id.toUpperCase();
+ }
+
+ if (experimentId && branchId) {
+ UTMTerm = `aboutwelcome-${experimentId}-${branchId}`.toLowerCase();
+ }
+ return {
+ messageId,
+ UTMTerm,
+ };
+}
+
+async function retrieveRenderContent() {
+ // Feature config includes RTAMO attribution data if exists
+ // else below data in order specified
+ // user prefs
+ // experiment data
+ // defaults
+ let featureConfig = await window.AWGetFeatureConfig();
+
+ let { messageId, UTMTerm } = ComputeTelemetryInfo(
+ featureConfig,
+ featureConfig.slug,
+ featureConfig.branch && featureConfig.branch.slug
+ );
+ return { featureConfig, messageId, UTMTerm };
+}
+
+async function mount() {
+ let {
+ featureConfig: aboutWelcomeProps,
+ messageId,
+ UTMTerm,
+ } = await retrieveRenderContent();
+ ReactDOM.render(
+ <AboutWelcome
+ messageId={messageId}
+ UTMTerm={UTMTerm}
+ {...aboutWelcomeProps}
+ />,
+ document.getElementById("multi-stage-message-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..f4f756dfd0
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss
@@ -0,0 +1,1676 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 'sass:math';
+@import '../styles/feature-callout';
+
+$break-point-small: 570px;
+$break-point-medium: 610px;
+$break-point-large: 866px;
+$container-min-width: 700px;
+$logo-size: 80px;
+$main-section-width: 504px;
+$split-section-width: 400px;
+$split-screen-height: 550px;
+$small-main-section-height: 450px;
+$small-secondary-section-height: 100px;
+$noodle-buffer: 106px;
+$video-section-width: 800px;
+
+html {
+ height: 100%;
+}
+
+// Below variables are used via config JSON in AboutWelcomeDefaults
+// and referenced below inside dummy class to pass test browser_parsable_css
+.dummy {
+ background: var(--mr-welcome-background-color) var(--mr-welcome-background-gradient) var(--mr-secondary-position) var(--mr-screen-background-color);
+}
+
+// Styling for content rendered in a Spotlight messaging surface.
+:root {
+ &[dialogroot] {
+ background-color: transparent;
+
+ body {
+ padding: 0;
+ }
+
+ .onboardingContainer {
+ // Without this, the container will be 100vh in height. When the dialog
+ // overflows horizontally, the horizontal scrollbar will appear. If the
+ // scrollbars aren't overlay scrollbars (this is controlled by
+ // Theme::ScrollbarStyle), they will take up vertical space in the
+ // viewport, causing the dialog to overflow vertically. This causes the
+ // vertical scrollbar to appear, which takes up horizontal space, causing
+ // the horizontal scrollbar to appear, and so on.
+ height: 100%;
+ background-color: transparent;
+
+ &:dir(rtl) {
+ transform: unset;
+ }
+
+ .logo-container {
+ pointer-events: none;
+ }
+
+ .screen {
+ &:dir(rtl) {
+ transform: unset;
+ }
+ }
+ }
+ }
+}
+
+// Styling for about:welcome background container
+.welcome-container {
+ .onboardingContainer {
+ min-height: $break-point-medium;
+ min-width: fit-content;
+ }
+}
+
+.onboardingContainer {
+ --grey-subtitle-1: #696977;
+ --mr-welcome-background-color: #F8F6F4;
+ --mr-screen-heading-color: var(--in-content-text-color);
+ --mr-welcome-background-gradient: linear-gradient(0deg, rgba(144, 89, 255, 20%) 0%, rgba(2, 144, 238, 20%) 100%);
+ --mr-screen-background-color: #F8F6F4;
+
+ @media (prefers-color-scheme: dark) {
+ --grey-subtitle-1: #FFF;
+ --mr-welcome-background-color: #333336;
+ --mr-welcome-background-gradient: linear-gradient(0deg, rgba(144, 89, 255, 30%) 0%, rgba(2, 144, 238, 30%) 100%);
+ --mr-screen-background-color: #62697A;
+ }
+
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Ubuntu,
+ 'Helvetica Neue', sans-serif;
+ font-size: 16px;
+ position: relative;
+ text-align: center;
+ height: 100vh;
+
+ @media (prefers-contrast) {
+ --mr-screen-background-color: buttontext;
+ --mr-screen-heading-color: buttonface;
+
+ background-color: var(--in-content-page-background);
+ }
+
+ // Transition all of these and reduced motion effectively only does opacity.
+ --transition: 0.6s opacity, 0.6s scale, 0.6s rotate, 0.6s translate;
+
+ // Define some variables that are used for in/out states.
+ @media (prefers-reduced-motion: no-preference) {
+ --translate: 30px;
+ --rotate: 20deg;
+ --scale: 0.4;
+ --progress-bar-transition: 0.6s translate;
+
+ // Scale is used for noodles that can be flipped.
+ &:dir(rtl) {
+ --scale: -0.4 0.4;
+ }
+ }
+
+ // Use default values that match "unmoved" state to avoid motion.
+ @media (prefers-reduced-motion: reduce) {
+ --translate: 0;
+ --rotate: 0deg;
+ --scale: 1;
+ // To reduce motion, progress bar fades in instead of wiping in.
+ --progress-bar-transition: none;
+
+ &:dir(rtl) {
+ --scale: -1 1;
+ }
+ }
+
+ &:dir(rtl) {
+ transform: rotateY(180deg);
+ }
+
+ .section-main {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ width: $main-section-width;
+ flex-shrink: 0;
+ }
+
+ .section-main:not(.embedded-migration) {
+ position: relative;
+ }
+
+ .main-content {
+ background-color: var(--in-content-page-background);
+ border-radius: 20px;
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 20%);
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ padding: 0;
+ transition: var(--transition);
+ z-index: 1;
+ box-sizing: border-box;
+
+ &.no-steps {
+ padding-bottom: 48px;
+ }
+
+ .main-content-inner {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ justify-content: space-around;
+ }
+ }
+
+ // Handle conditional display of steps indicator
+ // Don't show when there's only one screen
+ .main-content .no-steps {
+ .main-content {
+ padding-bottom: 48px;
+ }
+
+ .steps {
+ display: none;
+ }
+ }
+
+ @mixin arrow-icon-styles {
+ .arrow-icon {
+ -moz-context-properties: fill;
+ fill: currentColor;
+ text-decoration: none;
+
+ &::after {
+ content: '';
+ padding-inline-end: 12px;
+ margin-inline-start: 4px;
+ background: url('chrome://browser/skin/forward.svg') no-repeat center / 12px;
+ }
+
+ &:dir(rtl)::after {
+ background-image: url('chrome://browser/skin/back.svg');
+ }
+ }
+ }
+
+ @mixin secondary-cta-styles {
+ background-color: var(--in-content-button-background) !important; // stylelint-disable-line declaration-no-important
+ border: 1px solid var(--in-content-button-border-color);
+ line-height: 12px;
+ font-size: 0.72em;
+ font-weight: 600;
+ padding: 8px 16px;
+ text-decoration: none;
+
+ &:hover {
+ background-color: var(--in-content-button-background-hover) !important; // stylelint-disable-line declaration-no-important
+ color: var(--in-content-button-text-color-hover);
+ }
+ }
+
+ @mixin text-link-styles {
+ text-decoration: underline;
+ cursor: pointer;
+ color: var(--in-content-link-color);
+
+ &:hover {
+ text-decoration: none;
+ color: var(--in-content-link-color-hover);
+ }
+
+ &:active {
+ text-decoration: none;
+ color: var(--in-content-link-color-active);
+ }
+ }
+
+ .screen {
+ display: flex;
+ position: relative;
+ flex-flow: row nowrap;
+ height: 100%;
+ min-height: 500px;
+ overflow: hidden;
+
+ --in-content-link-color: var(--in-content-primary-button-background);
+ --in-content-link-color-hover: var(--in-content-primary-button-background-hover);
+ --in-content-link-color-active: var(--in-content-primary-button-background-active);
+ --in-content-link-color-visited: var(--in-content-link-color);
+
+ &.light-text {
+ --in-content-page-color: rgb(251, 251, 254);
+ --in-content-primary-button-text-color: rgb(43, 42, 51);
+ --in-content-primary-button-text-color-hover: rgb(43, 42, 51);
+ --in-content-primary-button-background: rgb(0, 221, 255);
+ --in-content-primary-button-background-hover: rgb(128, 235, 255);
+ --in-content-primary-button-background-active: rgb(170, 242, 255);
+ --checkbox-checked-bgcolor: var(--in-content-primary-button-background);
+ --in-content-button-text-color: var(--in-content-page-color);
+ }
+
+ &.dark-text {
+ --in-content-page-color: rgb(21, 20, 26);
+ --in-content-primary-button-text-color: rgb(251, 251, 254);
+ --in-content-primary-button-text-color-hover: rgb(251, 251, 254);
+ --in-content-primary-button-background: #0061E0;
+ --in-content-primary-button-background-hover: #0250BB;
+ --in-content-primary-button-background-active: #053E94;
+ --in-content-primary-button-border-color: transparent;
+ --in-content-primary-button-border-hover: transparent;
+ --checkbox-checked-bgcolor: var(--in-content-primary-button-background);
+ --in-content-button-text-color: var(--in-content-page-color);
+ }
+
+ &:dir(rtl) {
+ transform: rotateY(180deg);
+ }
+
+ &[pos='center'] {
+ background-color: rgba(21, 20, 26, 50%);
+ min-width: $main-section-width;
+
+ &.with-noodles {
+ // Adjust for noodles partially extending out from the square modal
+ min-width: $main-section-width + $noodle-buffer;
+ min-height: $main-section-width + $noodle-buffer;
+
+ .section-main {
+ height: $main-section-width;
+ }
+ }
+
+ &.with-video {
+ justify-content: center;
+ background: none;
+ align-items: center;
+
+ .section-main {
+ width: $video-section-width;
+ height: $split-screen-height;
+ }
+
+ .main-content {
+ background-color: var(--mr-welcome-background-color);
+ border-radius: 8px;
+ box-shadow: 0 2px 14px rgba(58, 57, 68, 20%);
+ padding: 44px 85px 20px;
+
+ .welcome-text {
+ margin: 0;
+ }
+
+ .main-content-inner {
+ justify-content: space-between;
+ }
+
+ h1,
+ h2 {
+ align-self: start;
+ }
+
+ h1 {
+ font-size: 24px;
+ line-height: 28.8px;
+ }
+
+ h2 {
+ font-size: 15px;
+ line-height: 22px;
+ }
+
+ .secondary-cta {
+ @include arrow-icon-styles;
+
+ justify-content: end;
+
+ .secondary {
+ @include secondary-cta-styles;
+
+ color: var(--in-content-button-text-color);
+ }
+ }
+ }
+ }
+ }
+
+ &:not([pos='split']) {
+ .secondary-cta {
+ .secondary {
+ background: none;
+ color: var(--in-content-link-color);
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 20px;
+ }
+
+ &.top {
+ button {
+ color: #FFF;
+
+ &:hover {
+ color: #E0E0E6;
+ }
+ }
+ }
+ }
+ }
+
+ &[pos='split'] {
+ margin: auto;
+ min-height: $split-screen-height;
+
+ &::before {
+ content: '';
+ position: absolute;
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 20%);
+ width: $split-section-width + $split-section-width;
+ height: $split-screen-height;
+ border-radius: 8px;
+ inset: 0;
+ margin: auto;
+ pointer-events: none;
+ }
+
+ .section-secondary,
+ .section-main {
+ width: $split-section-width;
+ height: $split-screen-height;
+ }
+
+ .secondary-cta.top {
+ position: fixed;
+ padding-inline-end: 0;
+
+ button {
+ color: var(--in-content-page-color);
+ }
+ }
+
+ .section-main {
+ flex-direction: row;
+ display: block;
+ margin: auto auto auto 0;
+
+ &:dir(rtl) {
+ margin: auto 0 auto auto;
+ }
+
+ .main-content {
+ border-radius: 0 8px 8px 0;
+ overflow: hidden;
+ padding-inline: 35px 20px;
+ padding-block: 120px 0;
+ box-shadow: none;
+
+ &.no-steps {
+ padding-bottom: 48px;
+ }
+
+ &:dir(rtl) {
+ border-radius: 8px 0 0 8px;
+ }
+
+ .main-content-inner {
+ min-height: 330px;
+
+ .language-switcher-container {
+ .primary {
+ margin-bottom: 5px;
+ }
+ }
+ }
+
+ .action-buttons {
+ position: relative;
+ text-align: initial;
+ height: 100%;
+
+ .checkbox-container {
+ font-size: 13px;
+ margin-block: 1em;
+
+ &:not(.multi-select-item) {
+ transition: var(--transition);
+ }
+
+ input,
+ label {
+ vertical-align: middle;
+ }
+ }
+
+ .additional-cta {
+ margin: 8px 0;
+
+ &.cta-link {
+ background: none;
+ padding: 0;
+ font-weight: normal;
+
+ @include text-link-styles;
+ }
+
+ &.secondary {
+ &:hover {
+ background-color: var(--in-content-button-background-hover);
+ }
+ }
+ }
+
+ &.additional-cta-container {
+ flex-wrap: nowrap;
+ align-items: start;
+ }
+
+ .secondary-cta {
+ position: absolute;
+ bottom: -30px;
+ inset-inline-end: 0;
+
+ .secondary {
+ @include secondary-cta-styles;
+ }
+
+ @include arrow-icon-styles;
+ }
+ }
+
+ .logo-container {
+ text-align: start;
+ }
+
+ .brand-logo {
+ height: 25px;
+ margin-block: 0;
+ }
+
+ .welcome-text {
+ margin-inline: 0 10px;
+ margin-block: 10px 35px;
+ text-align: initial;
+ align-items: initial;
+
+ &:empty {
+ margin: 0;
+ }
+
+ h1 {
+ font-size: 24px;
+ line-height: 1.2;
+ width: 300px;
+ }
+
+ h2 {
+ margin: 10px 0 0;
+ min-height: 1em;
+ font-size: 15px;
+ line-height: 1.5;
+
+ @media (prefers-contrast: no-preference) {
+ color: #5B5B66;
+ }
+ }
+ }
+
+ .welcome-text h1,
+ .primary {
+ margin: 0;
+ }
+
+ .steps {
+ z-index: 1;
+
+ &.progress-bar {
+ width: $split-section-width;
+ margin-inline: -35px;
+ }
+ }
+
+ @media (prefers-contrast) {
+ border: 1px solid var(--in-content-page-color);
+
+ .steps.progress-bar {
+ border-top: 1px solid var(--in-content-page-color);
+ background-color: var(--in-content-page-background);
+
+ .indicator {
+ background-color: var(--in-content-accent-color);
+ }
+ }
+ }
+ }
+ }
+
+ .section-secondary {
+ --mr-secondary-position: center center / auto 350px;
+
+ border-radius: 8px 0 0 8px;
+ margin: auto 0 auto auto;
+ display: flex;
+ align-items: center;
+ -moz-context-properties: fill, stroke, fill-opacity, stroke-opacity;
+ stroke: currentColor;
+
+ &:dir(rtl) {
+ border-radius: 0 8px 8px 0;
+ margin: auto auto auto 0;
+ }
+
+ h1 {
+ color: var(--mr-screen-heading-color);
+ font-weight: 700;
+ font-size: 47px;
+ line-height: 110%;
+ max-width: 340px;
+ text-align: initial;
+ white-space: pre-wrap;
+ text-shadow: none;
+ margin-inline: 40px 0;
+ }
+
+ .image-alt {
+ width: inherit;
+ height: inherit;
+ }
+
+ .hero-image {
+ flex: 1;
+ display: flex;
+ justify-content: center;
+ max-height: 100%;
+
+ img {
+ width: 100%;
+ max-width: 180px;
+ margin: 25px 0;
+ padding-bottom: 30px;
+
+ @media only screen and (max-width: 800px) {
+ padding-bottom: unset;
+ }
+ }
+ }
+ }
+
+ .tiles-theme-container {
+ margin-block: -20px auto;
+ align-items: initial;
+
+ .colorway-text {
+ text-align: initial;
+ transition: var(--transition);
+ font-size: 13px;
+ line-height: 1.5;
+ min-height: 4.5em;
+ margin-block: 10px 20px;
+ }
+
+ .theme {
+ min-width: 38px;
+ }
+ }
+
+ @media (prefers-contrast: no-preference) and (prefers-color-scheme: dark) {
+ .section-main .main-content {
+ .welcome-text h2 {
+ color: #CFCFD8;
+ }
+
+ .action-buttons .secondary {
+ background-color: #2B2A33;
+ }
+ }
+ }
+
+ @media only screen and (min-width: 800px) {
+ .tiles-theme-section {
+ margin-inline-start: -10px;
+ }
+ }
+
+ @media only screen and (max-width: 800px) {
+ flex-direction: column;
+ min-height: $small-main-section-height + $small-secondary-section-height;
+
+ &::before {
+ width: $split-section-width;
+ }
+
+ .section-secondary,
+ .section-main {
+ width: $split-section-width;
+ }
+
+ .section-secondary {
+ --mr-secondary-background-position-y: top;
+ --mr-secondary-position: center var(--mr-secondary-background-position-y) / 75%;
+
+ border-radius: 8px 8px 0 0;
+ margin: auto auto 0;
+ height: $small-secondary-section-height;
+
+ .hero-image img {
+ margin: 6px 0;
+ }
+
+ .message-text {
+ margin-inline: auto;
+ }
+
+ h1 {
+ font-size: 35px;
+ text-align: center;
+ white-space: normal;
+ margin-inline: auto;
+ margin-block: 14px 6px;
+ }
+
+ &:dir(rtl) {
+ margin: auto auto 0;
+ border-radius: 8px 8px 0 0;
+ }
+ }
+
+ .section-main {
+ margin: 0 auto auto;
+ height: $small-main-section-height;
+
+ .main-content {
+ border-radius: 0 0 8px 8px;
+ padding: 30px 0 0;
+
+ .main-content-inner {
+ align-items: center;
+ }
+
+ .logo-container {
+ text-align: center;
+
+ .brand-logo {
+ min-height: 25px;
+
+ &,
+ &:dir(rtl) {
+ background-position: center;
+ }
+ }
+ }
+
+ .welcome-text {
+ align-items: center;
+ text-align: center;
+ margin-inline: 0;
+ padding-inline: 30px;
+
+ .spacer-bottom,
+ .spacer-top {
+ display: none;
+ }
+ }
+
+ .action-buttons {
+ text-align: center;
+
+ .checkbox-container {
+ display: none;
+ }
+
+ .secondary-cta {
+ position: relative;
+ margin-block: 10px 0;
+ bottom: 0;
+ }
+ }
+
+ .primary,
+ .secondary {
+ min-width: 240px;
+ }
+
+ .colorway-text {
+ text-align: center;
+ margin-inline: 30px;
+ }
+
+ .steps {
+ padding-block: 0;
+ margin: 0;
+
+ &.progress-bar {
+ margin-inline: 0;
+ }
+ }
+ }
+
+ .additional-cta {
+ &.cta-link {
+ align-self: center;
+ }
+ }
+
+ .dismiss-button {
+ top: -$small-secondary-section-height;
+ }
+
+ &:dir(rtl) {
+ margin: 0 auto auto;
+
+ .main-content {
+ border-radius: 0 0 8px 8px;
+ }
+ }
+ }
+
+ }
+
+ @media only screen and (max-height: 650px) {
+ // Hide the "Sign in" button on the welcome screen when it would
+ // otherwise overlap the screen. We'd reposition it, but then it would
+ // overlap the dismiss button. We may change the alignment so they don't
+ // overlap in a future revision.
+ @media (min-width: 800px) and (max-width: 990px) {
+ .section-main .secondary-cta.top {
+ display: none;
+ }
+ }
+
+ // Reposition the "Sign in" button on the welcome screen to move inside
+ // the screen when it would otherwise overlap the screen.
+ @media (max-width: 590px) {
+ .section-main .secondary-cta.top {
+ position: absolute;
+ padding: 0;
+ top: 0;
+ inset-inline-end: 0;
+ }
+ }
+ }
+ }
+ }
+
+ .brand-logo {
+ margin-block: 60px 10px;
+ transition: var(--transition);
+ height: 80px;
+
+ &.cta-top {
+ margin-top: 25px;
+ }
+
+ &.hide {
+ visibility: hidden;
+ padding: unset;
+ margin-top: 50px;
+ }
+ }
+
+ .rtamo-theme-icon {
+ max-height: 30px;
+ border-radius: 2px;
+ margin-bottom: 10px;
+ margin-top: 24px;
+ }
+
+ .rtamo-icon {
+ text-align: start;
+
+ @media only screen and (max-width: 800px) {
+ text-align: center;
+ }
+ }
+
+ .text-link {
+ @include text-link-styles;
+ }
+
+ .welcome-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ margin: 0.5em 1em;
+ transition: var(--transition);
+
+ h1,
+ h2 {
+ color: var(--in-content-page-color);
+ line-height: 1.5;
+ }
+
+ h1 {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 6px;
+ letter-spacing: -0.02em;
+ outline: none;
+ }
+
+ h2 {
+ font-size: 16px;
+ font-weight: normal;
+ margin: 10px 6px 0;
+ max-width: 750px;
+ letter-spacing: -0.01em;
+ }
+
+ &.fancy {
+ h1 {
+ background-image: linear-gradient(90deg, #9059FF, #FF4AA2, #FF8C00, #FF4AA2, #9059FF);
+ background-clip: text;
+ background-size: 200%;
+
+ @media (prefers-contrast: no-preference) {
+ color: transparent;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ background-image: linear-gradient(90deg, #C688FF, #FF84C0, #FFBD4F, #FF84C0, #C688FF);
+
+ &::selection {
+ color: #FFF;
+ background-color: #696977;
+ }
+ }
+ }
+ }
+
+ &.shine {
+ h1 {
+ animation: shine 50s linear infinite;
+ background-size: 400%;
+ }
+
+ @keyframes shine {
+ to {
+ background-position: 400%;
+ }
+ }
+ }
+
+ .cta-paragraph {
+ a {
+ margin: 0;
+ text-decoration: underline;
+ cursor: pointer;
+ }
+ }
+ }
+
+ // Override light and dark mode fancy title colors for use over light and dark backgrounds
+ .screen.light-text .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #C688FF, #FF84C0, #FFBD4F, #FF84C0, #C688FF);
+ }
+
+ .screen.dark-text .welcome-text.fancy h1 {
+ background-image: linear-gradient(90deg, #9059FF, #FF4AA2, #FF8C00, #FF4AA2, #9059FF);
+ }
+
+ .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;
+ transform: scaleY(3);
+ }
+
+ &.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');
+ }
+ }
+ }
+
+ .language-loader {
+ filter: invert(1);
+ margin-inline-end: 10px;
+ position: relative;
+ top: 3px;
+ width: 16px;
+ height: 16px;
+ margin-top: -6px;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ .language-loader {
+ filter: invert(0);
+ }
+ }
+
+ .tiles-theme-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ margin: 10px auto;
+ }
+
+ .sr-only {
+ opacity: 0;
+ overflow: hidden;
+ position: absolute;
+
+ &.input {
+ height: 1px;
+ width: 1px;
+ }
+ }
+
+ .tiles-theme-section {
+ border: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ justify-content: space-evenly;
+ margin-inline: 10px;
+ padding: 10px;
+ transition: var(--transition);
+
+ &:hover,
+ &:active,
+ &:focus-within {
+ border-radius: 8px;
+ outline: 2px solid var(--in-content-primary-button-background);
+ }
+
+ .theme {
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ padding: 0;
+ min-width: 50px;
+ width: 180px;
+ color: #000;
+ box-shadow: none;
+ border-radius: 4px;
+ cursor: pointer;
+ z-index: 0;
+
+ &.colorway {
+ width: auto;
+ }
+
+ &:focus,
+ &:active {
+ outline: initial;
+ outline-offset: initial;
+ }
+
+ .icon.colorway,
+ .label.colorway {
+ width: 20px;
+ height: 20px;
+ }
+
+ .icon {
+ background-size: cover;
+ width: 40px;
+ height: 40px;
+ border-radius: 40px;
+ outline: 1px solid var(--in-content-border-color);
+ outline-offset: -0.5px;
+ z-index: -1;
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+
+ &:focus,
+ &:active,
+ &.selected {
+ outline: 2px solid var(--in-content-primary-button-background);
+ outline-offset: 2px;
+ }
+
+ &.light {
+ background-image: url('resource://builtin-themes/light/icon.svg');
+ }
+
+ &.dark {
+ background-image: url('resource://builtin-themes/dark/icon.svg');
+ }
+
+ &.alpenglow {
+ background-image: url('resource://builtin-themes/alpenglow/icon.svg');
+ }
+
+ &.default,
+ &.automatic {
+ background-image: url('resource://default-theme/icon.svg');
+
+ &.colorway {
+ background-image: url('chrome://activity-stream/content/data/content/assets/default.svg');
+ }
+ }
+
+ &.playmaker {
+ background-image: url('resource://builtin-themes/colorways/2022playmaker/balanced/icon.svg');
+ }
+
+ &.expressionist {
+ background-image: url('resource://builtin-themes/colorways/2022expressionist/balanced/icon.svg');
+ }
+
+ &.visionary {
+ background-image: url('resource://builtin-themes/colorways/2022visionary/balanced/icon.svg');
+ }
+
+ &.dreamer {
+ background-image: url('resource://builtin-themes/colorways/2022dreamer/balanced/icon.svg');
+ }
+
+ &.innovator {
+ background-image: url('resource://builtin-themes/colorways/2022innovator/balanced/icon.svg');
+ }
+
+ &.activist {
+ background-image: url('resource://builtin-themes/colorways/2022activist/balanced/icon.svg');
+ }
+ }
+
+ .text {
+ display: flex;
+ color: var(--in-content-page-color);
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 20px;
+ margin-inline-start: 0;
+ margin-top: 9px;
+ }
+ }
+
+ legend {
+ cursor: default;
+ }
+ }
+
+ .tiles-container {
+ margin: 10px auto;
+
+ &.info {
+ padding: 6px 12px 12px;
+
+ &:hover,
+ &:focus {
+ background-color: rgba(217, 217, 227, 30%);
+ border-radius: 4px;
+ }
+ }
+ }
+
+ .tiles-delayed {
+ animation: fadein 0.4s;
+ }
+
+ .multi-select-container {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ margin-block: -1em 1em;
+ color: #5B5B66;
+ font-weight: 400;
+ font-size: 14px;
+ text-align: initial;
+ transition: var(--transition);
+ z-index: 1;
+
+ .checkbox-container {
+ display: flex;
+ margin-bottom: 16px;
+ }
+ }
+
+ @media (prefers-color-scheme: dark) {
+ .multi-select-container {
+ color: #CFCFD8;
+ }
+ }
+
+ @media only screen and (max-width: 800px) {
+ .multi-select-container {
+ padding: 0 30px;
+ }
+ }
+
+ .mobile-downloads {
+ .qr-code-image {
+ margin: 24px 0 10px;
+ width: 113px;
+ height: 113px;
+ }
+
+ .email-link {
+ font-size: 16px;
+ font-weight: 400;
+ background: none;
+
+ @include text-link-styles;
+
+ &:hover {
+ background: none;
+ }
+ }
+
+ .ios button {
+ background-image: url('chrome://app-marketplace-icons/locale/ios.svg');
+ }
+
+ .android button {
+ background-image: url('chrome://app-marketplace-icons/locale/android.png');
+ }
+ }
+
+ .mobile-download-buttons {
+ list-style: none;
+ padding: 10px 0;
+ margin: 0;
+
+ li {
+ display: inline-block;
+
+ button {
+ display: inline-block;
+ height: 45px;
+ width: 152px;
+ background-repeat: no-repeat;
+ background-size: contain;
+ background-position: center;
+ box-shadow: none;
+ border: 0;
+ }
+
+ &:not(:first-child) {
+ margin-inline: 5px 0;
+ }
+ }
+ }
+
+ .dismiss-button {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ left: auto;
+ right: 0;
+ box-sizing: border-box;
+ padding: 0;
+ margin: 16px;
+ display: block;
+ float: inline-end;
+ background: url('chrome://global/skin/icons/close.svg') no-repeat center / 16px;
+ height: 32px;
+ width: 32px;
+ align-self: end;
+ // override default min-height and min-width for buttons
+ min-height: 32px;
+ min-width: 32px;
+ -moz-context-properties: fill;
+ fill: currentColor;
+ transition: var(--transition);
+
+ &:dir(rtl) {
+ left: 0;
+ right: auto;
+ }
+ }
+
+ @keyframes fadein {
+ from { opacity: 0; }
+ }
+
+ .secondary-cta {
+ display: flex;
+ align-items: end;
+ flex-direction: row;
+ justify-content: center;
+ font-size: 14px;
+ transition: var(--transition);
+
+ &.top {
+ justify-content: end;
+ padding-inline-end: min(150px, 500px - 70vh);
+ padding-top: 4px;
+ position: absolute;
+ top: 10px;
+ inset-inline-end: 20px;
+ z-index: 2;
+ }
+
+ span {
+ color: var(--grey-subtitle-1);
+ margin: 0 4px;
+ }
+ }
+
+ .message-text,
+ .attrib-text {
+ transition: var(--transition);
+ }
+
+ .helptext {
+ padding: 1em;
+ text-align: center;
+ color: var(--grey-subtitle-1);
+ font-size: 12px;
+ line-height: 18px;
+
+ &.default {
+ align-self: center;
+ max-width: 40%;
+ }
+
+ span {
+ padding-inline-end: 4px;
+ }
+ }
+
+ .helptext-img {
+ height: 1.5em;
+ width: 1.5em;
+ margin-inline-end: 4px;
+ vertical-align: middle;
+
+ &.end {
+ margin: 4px;
+ }
+
+ &.footer {
+ vertical-align: bottom;
+ }
+ }
+
+ .steps {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ margin-top: 0;
+ padding-block: 16px 0;
+ transition: var(--transition);
+ z-index: -1;
+ height: 48px;
+ box-sizing: border-box;
+
+ &.has-helptext {
+ padding-bottom: 0;
+ }
+
+ .indicator {
+ width: 0;
+ height: 0;
+ margin-inline-end: 4px;
+ margin-inline-start: 4px;
+ background: var(--grey-subtitle-1);
+ border-radius: 5px;
+ // using border will show up in Windows High Contrast Mode to improve accessibility.
+ border: 3px solid var(--in-content-button-text-color);
+ opacity: 0.35;
+ box-sizing: inherit;
+
+ &.current {
+ opacity: 1;
+ border-color: var(--checkbox-checked-bgcolor);
+
+ // This is the only step shown, so visually hide it to maintain spacing.
+ &:last-of-type:first-of-type {
+ opacity: 0;
+ }
+ }
+ }
+
+ &.progress-bar {
+ height: 6px;
+ padding-block: 0;
+ margin-block: 42px 0;
+ background-color: color-mix(in srgb, var(--in-content-button-text-color) 25%, transparent);
+ justify-content: start;
+ opacity: 1;
+ transition: none;
+
+ .indicator {
+ width: 100%;
+ height: 100%;
+ margin-inline: -1px;
+ background-color: var(--checkbox-checked-bgcolor);
+ border: 0;
+ border-radius: 0;
+ opacity: 1;
+ transition: var(--progress-bar-transition);
+ translate: calc(var(--progress-bar-progress, 0%) - 100%);
+
+ &:dir(rtl) {
+ translate: calc(var(--progress-bar-progress, 0%) * -1 + 100%);
+ }
+ }
+ }
+ }
+
+ .additional-cta-container {
+ &[flow] {
+ display: flex;
+ flex-flow: column wrap;
+ align-items: center;
+
+ &[flow='row'] {
+ flex-direction: row;
+ justify-content: center;
+
+ .secondary-cta {
+ flex-basis: 100%;
+ }
+ }
+ }
+ }
+
+ .primary,
+ .secondary,
+ .additional-cta {
+ font-size: 13px;
+ line-height: 16px;
+ padding: 11px 15px;
+ transition: var(--transition);
+
+ &.rtamo {
+ margin-top: 24px;
+ }
+ }
+
+ .secondary {
+ background-color: var(--in-content-button-background);
+ color: var(--in-content-button-text-color);
+ }
+
+ // Styles specific to background noodles, with screen-by-screen positions
+ .noodle {
+ display: block;
+ background-repeat: no-repeat;
+ background-size: 100% 100%;
+ position: absolute;
+ transition: var(--transition);
+
+ // Flip noodles in a way that combines individual transforms.
+ &:dir(rtl) {
+ scale: -1 1;
+ }
+ }
+
+ .outline-L {
+ background-image: url('chrome://activity-stream/content/data/content/assets/noodle-outline-L.svg');
+ }
+
+ .solid-L {
+ background-image: url('chrome://activity-stream/content/data/content/assets/noodle-solid-L.svg');
+ -moz-context-properties: fill;
+ fill: var(--in-content-page-background);
+ display: none;
+ }
+
+ .purple-C {
+ background-image: url('chrome://activity-stream/content/data/content/assets/noodle-C.svg');
+ -moz-context-properties: fill;
+ fill: #E7258C;
+ }
+
+ .orange-L {
+ background-image: url('chrome://activity-stream/content/data/content/assets/noodle-solid-L.svg');
+ -moz-context-properties: fill;
+ fill: #FFA437;
+ }
+
+ .screen-1 {
+ .section-main {
+ z-index: 1;
+ margin: auto;
+ }
+
+ // Position of noodles on second screen
+ .outline-L {
+ width: 87px;
+ height: 80px;
+ transform: rotate(10deg) translate(-30%, 200%);
+ transition-delay: 0.4s;
+ z-index: 2;
+ }
+
+ .orange-L {
+ width: 550px;
+ height: 660px;
+ transform: rotate(-155deg) translate(11%, -18%);
+ transition-delay: 0.2s;
+ }
+
+ .purple-C {
+ width: 310px;
+ height: 260px;
+ transform: translate(-18%, -67%);
+ }
+
+ .yellow-circle {
+ width: 165px;
+ height: 165px;
+ border-radius: 50%;
+ transform: translate(230%, -5%);
+ background: #952BB9;
+ transition-delay: -0.2s;
+ }
+ }
+
+ // Defining the timing of the transition-in for items within the dialog,
+ // These longer delays are to allow for the dialog to slide down on first screen
+ .dialog-initial {
+ .brand-logo {
+ transition-delay: 0.6s;
+ }
+
+ .welcome-text {
+ transition-delay: 0.8s;
+ }
+
+ .tiles-theme-section,
+ .multi-select-container,
+ migration-wizard {
+ transition-delay: 0.9s;
+ }
+
+ .primary,
+ .secondary,
+ .secondary-cta,
+ .steps,
+ .cta-link {
+ transition-delay: 1s;
+ }
+ }
+
+ // Delays for transitioning-in of intermediate screens
+ .screen:not(.dialog-initial) {
+ .tiles-theme-section,
+ .multi-select-container,
+ .colorway-text {
+ transition-delay: 0.2s;
+ }
+
+ .primary,
+ .secondary,
+ .secondary-cta,
+ .cta-link {
+ transition-delay: 0.4s;
+ }
+ }
+
+ .screen-2 {
+ .section-main {
+ z-index: 1;
+ margin: auto;
+ }
+
+ // Position of noodles on third screen
+ .outline-L {
+ width: 87px;
+ height: 80px;
+ transform: rotate(250deg) translate(-420%, 425%);
+ transition-delay: 0.2s;
+ z-index: 2;
+ }
+
+ .orange-L {
+ height: 800px;
+ width: 660px;
+ transform: rotate(35deg) translate(-10%, -7%);
+ transition-delay: -0.4s;
+ }
+
+ .purple-C {
+ width: 392px;
+ height: 394px;
+ transform: rotate(260deg) translate(-34%, -35%);
+ transition-delay: -0.2s;
+ fill: #952BB9;
+ }
+
+ .yellow-circle {
+ width: 165px;
+ height: 165px;
+ border-radius: 50%;
+ transform: translate(160%, 130%);
+ background: #E7258C;
+ }
+ }
+
+ &.transition-in {
+ .noodle {
+ opacity: 0;
+ rotate: var(--rotate);
+ scale: var(--scale);
+ }
+
+ .dialog-initial {
+ .main-content,
+ .dismiss-button {
+ translate: 0 calc(-2 * var(--translate));
+ }
+
+ .brand-logo,
+ .steps {
+ opacity: 0;
+ translate: 0 calc(-1 * var(--translate));
+ }
+ }
+
+ .screen {
+ .welcome-text,
+ .multi-select-container,
+ .tiles-theme-section,
+ .colorway-text,
+ .primary,
+ .checkbox-container:not(.multi-select-item),
+ .secondary,
+ .secondary-cta:not(.top),
+ .cta-link,
+ migration-wizard {
+ opacity: 0;
+ translate: 0 calc(-1 * var(--translate));
+ }
+
+ &:not(.dialog-initial) {
+ .steps:not(.progress-bar) {
+ opacity: 0.2;
+ }
+ }
+ }
+ }
+
+ &.transition-out {
+ .noodle {
+ opacity: 0;
+ rotate: var(--rotate);
+ scale: var(--scale);
+ transition-delay: 0.2s;
+ }
+
+ .screen:not(.dialog-last) {
+ .main-content {
+ overflow: hidden;
+ }
+
+ .welcome-text,
+ .multi-select-container {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.1s;
+ }
+
+ // content that is nested between inner main content and navigation CTAs
+ // requires an additional 0.1s transition to avoid overlap
+ .tiles-theme-section,
+ .colorway-text,
+ migration-wizard {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.2s;
+ }
+
+ .primary,
+ .checkbox-container:not(.multi-select-item),
+ .secondary,
+ .secondary-cta:not(.top),
+ .cta-link {
+ opacity: 0;
+ translate: 0 var(--translate);
+ transition-delay: 0.3s;
+ }
+
+ .steps:not(.progress-bar) {
+ opacity: 0.2;
+ transition-delay: 0.5s;
+ }
+ }
+
+ .dialog-last {
+ .noodle {
+ transition-delay: 0s;
+ }
+
+ .main-content,
+ .dismiss-button {
+ opacity: 0;
+ translate: 0 calc(2 * var(--translate));
+ transition-delay: 0.4s;
+ }
+ }
+ }
+
+ migration-wizard {
+ width: unset;
+ transition: var(--transition);
+
+ &::part(buttons) {
+ margin-top: 32px;
+ justify-content: flex-start;
+ }
+
+ &::part(deck) {
+ font-size: 0.83em;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/AdditionalCTA.jsx b/browser/components/newtab/content-src/aboutwelcome/components/AdditionalCTA.jsx
new file mode 100644
index 0000000000..2b61d1a82a
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/AdditionalCTA.jsx
@@ -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/. */
+
+import React from "react";
+import { Localized } from "./MSLocalized";
+
+export const AdditionalCTA = ({ content, handleAction }) => {
+ let buttonStyle = "";
+
+ if (!content.additional_button?.style) {
+ buttonStyle = "primary";
+ } else {
+ buttonStyle =
+ content.additional_button?.style === "link"
+ ? "cta-link"
+ : content.additional_button?.style;
+ }
+
+ return (
+ <Localized text={content.additional_button?.label}>
+ <button
+ className={`${buttonStyle} additional-cta`}
+ onClick={handleAction}
+ value="additional_button"
+ disabled={content.additional_button?.disabled === true}
+ />
+ </Localized>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/CTAParagraph.jsx b/browser/components/newtab/content-src/aboutwelcome/components/CTAParagraph.jsx
new file mode 100644
index 0000000000..41726626a4
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/CTAParagraph.jsx
@@ -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/. */
+
+import React from "react";
+import { Localized } from "./MSLocalized";
+
+export const CTAParagraph = props => {
+ const { content, handleAction } = props;
+
+ if (!content?.text) {
+ return null;
+ }
+
+ return (
+ <h2 className="cta-paragraph">
+ <Localized text={content.text}>
+ {content.text.string_name && typeof handleAction === "function" ? (
+ <span
+ data-l10n-id={content.text.string_id}
+ onClick={handleAction}
+ onKeyUp={event =>
+ ["Enter", " "].includes(event.key) ? handleAction(event) : null
+ }
+ value="cta_paragraph"
+ role="button"
+ tabIndex="0"
+ >
+ {" "}
+ {/* <a> is valid here because of click and keyup handling. */}
+ {/* <button> cannot be used due to fluent integration. <a> content is provided by fluent */}
+ {/* eslint-disable jsx-a11y/anchor-is-valid */}
+ <a
+ role="button"
+ tabIndex="0"
+ data-l10n-name={content.text.string_name}
+ >
+ {" "}
+ </a>
+ </span>
+ ) : null}
+ </Localized>
+ </h2>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/EmbeddedMigrationWizard.jsx b/browser/components/newtab/content-src/aboutwelcome/components/EmbeddedMigrationWizard.jsx
new file mode 100644
index 0000000000..43930009a5
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/EmbeddedMigrationWizard.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, { useEffect, useRef } from "react";
+
+export const EmbeddedMigrationWizard = ({ handleAction }) => {
+ const ref = useRef();
+ useEffect(() => {
+ const handleBeginMigration = () => {
+ handleAction({
+ currentTarget: { value: "migrate_start" },
+ source: "primary_button",
+ });
+ };
+ const handleClose = () => {
+ handleAction({ currentTarget: { value: "migrate_close" } });
+ };
+ const { current } = ref;
+ current?.addEventListener(
+ "MigrationWizard:BeginMigration",
+ handleBeginMigration
+ );
+ current?.addEventListener("MigrationWizard:Close", handleClose);
+ return () => {
+ current?.removeEventListener(
+ "MigrationWizard:BeginMigration",
+ handleBeginMigration
+ );
+ current?.removeEventListener("MigrationWizard:Close", handleClose);
+ };
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ return (
+ <migration-wizard auto-request-state="" ref={ref}>
+ <panel-list />
+ </migration-wizard>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/HelpText.jsx b/browser/components/newtab/content-src/aboutwelcome/components/HelpText.jsx
new file mode 100644
index 0000000000..f7b413be81
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/HelpText.jsx
@@ -0,0 +1,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/. */
+
+import React from "react";
+import { Localized } from "./MSLocalized";
+const MS_STRING_PROP = "string_id";
+
+export const HelpText = props => {
+ if (!props.text) {
+ return null;
+ }
+
+ if (props.hasImg) {
+ if (typeof props.text === "object" && props.text[MS_STRING_PROP]) {
+ return (
+ <Localized text={props.text}>
+ <p className={`helptext ${props.position}`}>
+ <img
+ data-l10n-name="help-img"
+ className={`helptext-img ${props.position}`}
+ src={props.hasImg.src}
+ alt=""
+ ></img>
+ </p>
+ </Localized>
+ );
+ } else if (typeof props.text === "string") {
+ // Add the img at the end of the props.text
+ return (
+ <p className={`helptext ${props.position}`}>
+ {props.text}
+ <img
+ className={`helptext-img ${props.position} end`}
+ src={props.hasImg.src}
+ alt=""
+ />
+ </p>
+ );
+ }
+ } else {
+ return (
+ <Localized text={props.text}>
+ <p className={`helptext ${props.position}`} />
+ </Localized>
+ );
+ }
+ return null;
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/HeroImage.jsx b/browser/components/newtab/content-src/aboutwelcome/components/HeroImage.jsx
new file mode 100644
index 0000000000..e03a5f84f4
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/HeroImage.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 React from "react";
+
+export const HeroImage = props => {
+ const { height, url, alt } = props;
+
+ if (!url) {
+ return null;
+ }
+
+ return (
+ <div className="hero-image">
+ <img
+ style={height ? { height } : null}
+ src={url}
+ alt={alt || ""}
+ role={alt ? null : "presentation"}
+ />
+ </div>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/LanguageSwitcher.jsx b/browser/components/newtab/content-src/aboutwelcome/components/LanguageSwitcher.jsx
new file mode 100644
index 0000000000..9abd749a6d
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/LanguageSwitcher.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 React, { useState, useEffect } from "react";
+import { Localized } from "./MSLocalized";
+import { AboutWelcomeUtils } from "../../lib/aboutwelcome-utils";
+
+/**
+ * The language switcher implements a hook that should be placed at a higher level
+ * than the actual language switcher component, as it needs to preemptively fetch
+ * and install langpacks for the user if there is a language mismatch screen.
+ */
+export function useLanguageSwitcher(
+ appAndSystemLocaleInfo,
+ screens,
+ screenIndex,
+ setScreenIndex
+) {
+ const languageMismatchScreenIndex = screens.findIndex(
+ ({ id }) => id === "AW_LANGUAGE_MISMATCH"
+ );
+ const screen = screens[languageMismatchScreenIndex];
+
+ // Ensure fluent messages have the negotiatedLanguage args set, as they are rendered
+ // before the negotiatedLanguage is known. If the arg isn't present then Firefox will
+ // crash in development mode.
+ useEffect(() => {
+ if (screen?.content?.languageSwitcher) {
+ for (const text of Object.values(screen.content.languageSwitcher)) {
+ if (text?.args && text.args.negotiatedLanguage === undefined) {
+ text.args.negotiatedLanguage = "";
+ }
+ }
+ }
+ }, [screen]);
+
+ // If there is a mismatch, then Firefox can negotiate a better langpack to offer
+ // the user.
+ const [negotiatedLanguage, setNegotiatedLanguage] = useState(null);
+ useEffect(
+ function getNegotiatedLanguage() {
+ if (!appAndSystemLocaleInfo) {
+ return;
+ }
+ if (appAndSystemLocaleInfo.matchType !== "language-mismatch") {
+ // There is no language mismatch, so there is no need to negotiate a langpack.
+ return;
+ }
+
+ (async () => {
+ const { langPack, langPackDisplayName } =
+ await window.AWNegotiateLangPackForLanguageMismatch(
+ appAndSystemLocaleInfo
+ );
+ if (langPack) {
+ setNegotiatedLanguage({
+ langPackDisplayName,
+ appDisplayName: appAndSystemLocaleInfo.displayNames.appLanguage,
+ langPack,
+ requestSystemLocales: [
+ langPack.target_locale,
+ appAndSystemLocaleInfo.appLocaleRaw,
+ ],
+ originalAppLocales: [appAndSystemLocaleInfo.appLocaleRaw],
+ });
+ } else {
+ setNegotiatedLanguage({
+ langPackDisplayName: null,
+ appDisplayName: null,
+ langPack: null,
+ requestSystemLocales: null,
+ });
+ }
+ })();
+ },
+ [appAndSystemLocaleInfo]
+ );
+
+ /**
+ * @type {
+ * "before-installation"
+ * | "installing"
+ * | "installed"
+ * | "installation-error"
+ * | "none-available"
+ * }
+ */
+ const [langPackInstallPhase, setLangPackInstallPhase] = useState(
+ "before-installation"
+ );
+ useEffect(
+ function ensureLangPackInstalled() {
+ if (!negotiatedLanguage) {
+ // There are no negotiated languages to download yet.
+ return;
+ }
+ setLangPackInstallPhase("installing");
+ window
+ .AWEnsureLangPackInstalled(negotiatedLanguage, screen?.content)
+ .then(
+ content => {
+ // Update screen content with strings that might have changed.
+ screen.content = content;
+ setLangPackInstallPhase("installed");
+ },
+ error => {
+ console.error(error);
+ setLangPackInstallPhase("installation-error");
+ }
+ );
+ },
+ [negotiatedLanguage]
+ );
+
+ const [languageFilteredScreens, setLanguageFilteredScreens] =
+ useState(screens);
+ useEffect(
+ function filterScreen() {
+ // Remove the language screen if it exists (already removed for no live
+ // reload) and we either don't-need-to or can't switch.
+ if (
+ screen &&
+ (appAndSystemLocaleInfo?.matchType !== "language-mismatch" ||
+ negotiatedLanguage?.langPack === null)
+ ) {
+ if (screenIndex > languageMismatchScreenIndex) {
+ setScreenIndex(screenIndex - 1);
+ }
+ setLanguageFilteredScreens(
+ screens.filter(s => s.id !== "AW_LANGUAGE_MISMATCH")
+ );
+ } else {
+ setLanguageFilteredScreens(screens);
+ }
+ },
+ [screens, negotiatedLanguage]
+ );
+
+ return {
+ negotiatedLanguage,
+ langPackInstallPhase,
+ languageFilteredScreens,
+ };
+}
+
+/**
+ * The language switcher is a separate component as it needs to perform some asynchronous
+ * network actions such as retrieving the list of langpacks available, and downloading
+ * a new langpack. On a fast connection, this won't be noticeable, but on slow or unreliable
+ * internet this may fail for a user.
+ */
+export function LanguageSwitcher(props) {
+ const {
+ content,
+ handleAction,
+ negotiatedLanguage,
+ langPackInstallPhase,
+ messageId,
+ } = props;
+
+ const [isAwaitingLangpack, setIsAwaitingLangpack] = useState(false);
+
+ // Determine the status of the langpack installation.
+ useEffect(() => {
+ if (isAwaitingLangpack && langPackInstallPhase !== "installing") {
+ window.AWSetRequestedLocales(negotiatedLanguage.requestSystemLocales);
+ requestAnimationFrame(() => {
+ handleAction(
+ // Simulate the click event.
+ { currentTarget: { value: "download_complete" } }
+ );
+ });
+ }
+ }, [isAwaitingLangpack, langPackInstallPhase]);
+
+ let showWaitingScreen = false;
+ let showPreloadingScreen = false;
+ let showReadyScreen = false;
+
+ if (isAwaitingLangpack && langPackInstallPhase !== "installed") {
+ showWaitingScreen = true;
+ } else if (langPackInstallPhase === "before-installation") {
+ showPreloadingScreen = true;
+ } else {
+ showReadyScreen = true;
+ }
+
+ // Use {display: "none"} rather than if statements to prevent layout thrashing with
+ // the localized text elements rendering as blank, then filling in the text.
+ return (
+ <div className="action-buttons language-switcher-container">
+ {/* Pre-loading screen */}
+ <div style={{ display: showPreloadingScreen ? "block" : "none" }}>
+ <button
+ className="primary"
+ value="primary_button"
+ disabled={true}
+ type="button"
+ >
+ <img
+ className="language-loader"
+ src="chrome://browser/skin/tabbrowser/tab-connecting.png"
+ alt=""
+ />
+ <Localized text={content.languageSwitcher.waiting} />
+ </button>
+ <div className="secondary-cta">
+ <Localized text={content.languageSwitcher.skip}>
+ <button
+ value="decline_waiting"
+ type="button"
+ className="secondary text-link arrow-icon"
+ onClick={handleAction}
+ />
+ </Localized>
+ </div>
+ </div>
+ {/* Waiting to download the language screen. */}
+ <div style={{ display: showWaitingScreen ? "block" : "none" }}>
+ <button
+ className="primary"
+ value="primary_button"
+ disabled={true}
+ type="button"
+ >
+ <img
+ className="language-loader"
+ src="chrome://browser/skin/tabbrowser/tab-connecting.png"
+ alt=""
+ />
+ <Localized text={content.languageSwitcher.downloading} />
+ </button>
+ <div className="secondary-cta">
+ <Localized text={content.languageSwitcher.cancel}>
+ <button
+ type="button"
+ className="secondary text-link"
+ onClick={() => {
+ setIsAwaitingLangpack(false);
+ handleAction({
+ currentTarget: { value: "cancel_waiting" },
+ });
+ }}
+ />
+ </Localized>
+ </div>
+ </div>
+ {/* The typical ready screen. */}
+ <div style={{ display: showReadyScreen ? "block" : "none" }}>
+ <div>
+ <button
+ className="primary"
+ value="primary_button"
+ onClick={() => {
+ AboutWelcomeUtils.sendActionTelemetry(
+ messageId,
+ "download_langpack"
+ );
+ setIsAwaitingLangpack(true);
+ }}
+ >
+ {content.languageSwitcher.switch ? (
+ <Localized text={content.languageSwitcher.switch} />
+ ) : (
+ // This is the localized name from the Intl.DisplayNames API.
+ negotiatedLanguage?.langPackDisplayName
+ )}
+ </button>
+ </div>
+ <div>
+ <button
+ type="button"
+ className="primary"
+ value="decline"
+ onClick={event => {
+ window.AWSetRequestedLocales(
+ negotiatedLanguage.originalAppLocales
+ );
+ handleAction(event);
+ }}
+ >
+ {content.languageSwitcher.continue ? (
+ <Localized text={content.languageSwitcher.continue} />
+ ) : (
+ // This is the localized name from the Intl.DisplayNames API.
+ negotiatedLanguage?.appDisplayName
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MRColorways.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MRColorways.jsx
new file mode 100644
index 0000000000..6a69f3483a
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MRColorways.jsx
@@ -0,0 +1,198 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 } from "react";
+import { Localized } from "./MSLocalized";
+
+export const ColorwayDescription = props => {
+ const { colorway } = props;
+ if (!colorway) {
+ return null;
+ }
+ const { label, description } = colorway;
+ return (
+ <Localized text={description}>
+ <div
+ className="colorway-text"
+ data-l10n-args={JSON.stringify({
+ colorwayName: label,
+ })}
+ />
+ </Localized>
+ );
+};
+
+// Return colorway as "default" for default theme variations Automatic, Light, Dark,
+// Alpenglow theme and legacy colorways which is not supported in Colorway picker.
+// For themes other then default, theme names exist in
+// format colorway-variationId inside LIGHT_WEIGHT_THEMES in AboutWelcomeParent
+export function computeColorWay(themeName, systemVariations) {
+ return !themeName ||
+ themeName === "alpenglow" ||
+ systemVariations.includes(themeName)
+ ? "default"
+ : themeName.split("-")[0];
+}
+
+// Set variationIndex based off activetheme value e.g. 'light', 'expressionist-soft'
+export function computeVariationIndex(
+ themeName,
+ systemVariations,
+ variations,
+ defaultVariationIndex
+) {
+ // Check if themeName is in systemVariations, if yes choose variationIndex by themeName
+ let index = systemVariations.findIndex(theme => theme === themeName);
+ if (index >= 0) {
+ return index;
+ }
+
+ // If themeName is one of the colorways, select variation index from colorways
+ let variation = themeName?.split("-")[1];
+ index = variations.findIndex(element => element === variation);
+ if (index >= 0) {
+ return index;
+ }
+ return defaultVariationIndex;
+}
+
+export function Colorways(props) {
+ let {
+ colorways,
+ darkVariation,
+ defaultVariationIndex,
+ systemVariations,
+ variations,
+ } = props.content.tiles;
+ let hasReverted = false;
+
+ // Active theme id from JSON e.g. "expressionist"
+ const activeId = computeColorWay(props.activeTheme, systemVariations);
+ const [colorwayId, setState] = useState(activeId);
+ const [variationIndex, setVariationIndex] = useState(defaultVariationIndex);
+
+ function revertToDefaultTheme() {
+ if (hasReverted) return;
+
+ // Spoofing an event with current target value of "navigate_away"
+ // helps the handleAction method to read the colorways theme as "revert"
+ // which causes the initial theme to be activated.
+ // The "navigate_away" action is set in content in the colorways screen JSON config.
+ // Any value in the JSON for theme will work, provided it is not `<event>`.
+ const event = {
+ currentTarget: {
+ value: "navigate_away",
+ },
+ };
+ props.handleAction(event);
+ hasReverted = true;
+ }
+
+ // Revert to default theme if the user navigates away from the page or spotlight modal
+ // before clicking on the primary button to officially set theme.
+ useEffect(() => {
+ addEventListener("beforeunload", revertToDefaultTheme);
+ addEventListener("pagehide", revertToDefaultTheme);
+
+ return () => {
+ removeEventListener("beforeunload", revertToDefaultTheme);
+ removeEventListener("pagehide", revertToDefaultTheme);
+ };
+ });
+ // Update state any time activeTheme changes.
+ useEffect(() => {
+ setState(computeColorWay(props.activeTheme, systemVariations));
+ setVariationIndex(
+ computeVariationIndex(
+ props.activeTheme,
+ systemVariations,
+ variations,
+ defaultVariationIndex
+ )
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [props.activeTheme]);
+
+ //select a random colorway
+ useEffect(() => {
+ //We don't want the default theme to be selected
+ const randomIndex = Math.floor(Math.random() * (colorways.length - 1)) + 1;
+ const randomColorwayId = colorways[randomIndex].id;
+
+ // Change the variation to be the dark variation if configured and dark.
+ // Additional colorway changes will remain dark while system is unchanged.
+ if (
+ darkVariation !== undefined &&
+ window.matchMedia("(prefers-color-scheme: dark)").matches
+ ) {
+ variations[variationIndex] = variations[darkVariation];
+ }
+ const value = `${randomColorwayId}-${variations[variationIndex]}`;
+ props.handleAction({ currentTarget: { value } });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return (
+ <div className="tiles-theme-container">
+ <div>
+ <fieldset className="tiles-theme-section">
+ <Localized text={props.content.subtitle}>
+ <legend className="sr-only" />
+ </Localized>
+ {colorways.map(({ id, label, tooltip }) => (
+ <Localized
+ key={id + label}
+ text={typeof tooltip === "object" ? tooltip : {}}
+ >
+ <label
+ className="theme"
+ title={label}
+ data-l10n-args={JSON.stringify({
+ colorwayName: label,
+ })}
+ >
+ <Localized text={typeof tooltip === "object" ? tooltip : {}}>
+ <span
+ className="sr-only colorway label"
+ id={`${id}-label`}
+ data-l10n-args={JSON.stringify({
+ colorwayName: tooltip,
+ })}
+ />
+ </Localized>
+ <Localized text={typeof label === "object" ? label : {}}>
+ <input
+ type="radio"
+ data-colorway={id}
+ name="theme"
+ value={
+ id === "default"
+ ? systemVariations[variationIndex]
+ : `${id}-${variations[variationIndex]}`
+ }
+ checked={colorwayId === id}
+ className="sr-only input"
+ onClick={props.handleAction}
+ data-l10n-args={JSON.stringify({
+ colorwayName: label,
+ })}
+ aria-labelledby={`${id}-label`}
+ />
+ </Localized>
+ <div
+ className={`icon colorway ${
+ colorwayId === id ? "selected" : ""
+ } ${id}`}
+ />
+ </label>
+ </Localized>
+ ))}
+ </fieldset>
+ </div>
+ <ColorwayDescription
+ colorway={colorways.find(colorway => colorway.id === activeId)}
+ />
+ </div>
+ );
+}
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..461f19fb28
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.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 React, { useEffect } from "react";
+const CONFIGURABLE_STYLES = [
+ "color",
+ "fontSize",
+ "fontWeight",
+ "letterSpacing",
+ "lineHeight",
+ "marginBlock",
+ "marginInline",
+ "paddingBlock",
+ "paddingInline",
+];
+const ZAP_SIZE_THRESHOLD = 160;
+
+/**
+ * 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.
+ * Allows configuring of some styles including zap underline and color.
+ *
+ * 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>
+ * <Localized text={{raw: "Welcome"}}><h1 /></Localized>
+ * output:
+ * <h1>Welcome</h1>
+ */
+
+export const Localized = ({ text, children }) => {
+ // Dynamically determine the size of the zap style.
+ const zapRef = React.createRef();
+ useEffect(() => {
+ const { current } = zapRef;
+ if (current)
+ requestAnimationFrame(() =>
+ current?.classList.replace(
+ "short",
+ current.getBoundingClientRect().width > ZAP_SIZE_THRESHOLD
+ ? "long"
+ : "short"
+ )
+ );
+ });
+
+ // Skip rendering of children with no text.
+ if (!text) {
+ return null;
+ }
+
+ // Allow augmenting existing child container properties.
+ const props = { children: [], className: "", style: {}, ...children?.props };
+ // Support nested Localized by starting with their children.
+ const textNodes = Array.isArray(props.children)
+ ? props.children
+ : [props.children];
+
+ // Pick desired fluent or raw/plain text to render.
+ if (text.string_id) {
+ // Set the key so React knows not to reuse when switching to plain text.
+ props.key = text.string_id;
+ props["data-l10n-id"] = text.string_id;
+ if (text.args) props["data-l10n-args"] = JSON.stringify(text.args);
+ } else if (text.raw) {
+ textNodes.push(text.raw);
+ } else if (typeof text === "string") {
+ textNodes.push(text);
+ }
+
+ // Add zap style and content in a way that allows fluent to insert too.
+ if (text.zap) {
+ props.className += " welcomeZap";
+ textNodes.push(
+ <span className="short zap" data-l10n-name="zap" ref={zapRef}>
+ {text.zap}
+ </span>
+ );
+ }
+
+ if (text.aria_label) {
+ props["aria-label"] = text.aria_label;
+ }
+
+ // Apply certain configurable styles.
+ CONFIGURABLE_STYLES.forEach(style => {
+ if (text[style] !== undefined) props.style[style] = text[style];
+ });
+
+ return React.cloneElement(
+ // Provide a default container for the text if necessary.
+ children ?? <span />,
+ props,
+ // Conditionally pass in as void elements can't accept empty array.
+ textNodes.length ? textNodes : null
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MobileDownloads.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MobileDownloads.jsx
new file mode 100644
index 0000000000..8390d2fd68
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MobileDownloads.jsx
@@ -0,0 +1,71 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 MarketplaceButtons = props => {
+ return (
+ <ul className="mobile-download-buttons">
+ {props.buttons.includes("ios") ? (
+ <li className="ios">
+ <button
+ data-l10n-id={"spotlight-ios-marketplace-button"}
+ value="ios"
+ onClick={props.handleAction}
+ ></button>
+ </li>
+ ) : null}
+ {props.buttons.includes("android") ? (
+ <li className="android">
+ <button
+ data-l10n-id={"spotlight-android-marketplace-button"}
+ value="android"
+ onClick={props.handleAction}
+ ></button>
+ </li>
+ ) : null}
+ </ul>
+ );
+};
+
+export const MobileDownloads = props => {
+ const { QR_code: QRCode } = props.data;
+ const showEmailLink =
+ props.data.email && window.AWSendToDeviceEmailsSupported();
+
+ return (
+ <div className="mobile-downloads">
+ {/* Avoid use of Localized element to set alt text here as a plain string value
+ results in a React error due to "dangerouslySetInnerHTML" */}
+ {QRCode ? (
+ <img
+ data-l10n-id={
+ QRCode.alt_text.string_id ? QRCode.alt_text.string_id : null
+ }
+ className="qr-code-image"
+ alt={typeof QRCode.alt_text === "string" ? QRCode.alt_text : ""}
+ src={QRCode.image_url}
+ />
+ ) : null}
+ {showEmailLink ? (
+ <div>
+ <Localized text={props.data.email.link_text}>
+ <button
+ className="email-link"
+ value="email_link"
+ onClick={props.handleAction}
+ />
+ </Localized>
+ </div>
+ ) : null}
+ {props.data.marketplace_buttons ? (
+ <MarketplaceButtons
+ buttons={props.data.marketplace_buttons}
+ handleAction={props.handleAction}
+ />
+ ) : null}
+ </div>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MultiSelect.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MultiSelect.jsx
new file mode 100644
index 0000000000..0c1824215a
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MultiSelect.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, { useEffect } from "react";
+import { Localized } from "./MSLocalized";
+
+export const MultiSelect = props => {
+ let handleChange = event => {
+ if (event.currentTarget.checked) {
+ props.setActiveMultiSelect([
+ ...props.activeMultiSelect,
+ event.currentTarget.value,
+ ]);
+ } else {
+ props.setActiveMultiSelect(
+ props.activeMultiSelect.filter(id => id !== event.currentTarget.value)
+ );
+ }
+ };
+
+ let { data } = props.content.tiles;
+ // When screen renders for first time, update state
+ // with checkbox ids that has defaultvalue true
+ useEffect(() => {
+ if (!props.activeMultiSelect) {
+ props.setActiveMultiSelect(
+ data.map(item => item.defaultValue && item.id).filter(item => !!item)
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return (
+ <div className="multi-select-container">
+ {props.content.tiles.data.map(({ label, id }) => (
+ <div key={id + label} className="checkbox-container multi-select-item">
+ <input
+ type="checkbox"
+ id={id}
+ value={id}
+ checked={props.activeMultiSelect?.includes(id)}
+ onChange={handleChange}
+ />
+ <Localized text={label}>
+ <label htmlFor={id}></label>
+ </Localized>
+ </div>
+ ))}
+ </div>
+ );
+};
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..b58510e514
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx
@@ -0,0 +1,468 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { AboutWelcomeUtils } from "../../lib/aboutwelcome-utils";
+import { MultiStageProtonScreen } from "./MultiStageProtonScreen";
+import { useLanguageSwitcher } from "./LanguageSwitcher";
+import {
+ BASE_PARAMS,
+ addUtmParams,
+} from "../../asrouter/templates/FirstRun/addUtmParams";
+
+// Amount of milliseconds for all transitions to complete (including delays).
+const TRANSITION_OUT_TIME = 1000;
+const LANGUAGE_MISMATCH_SCREEN_ID = "AW_LANGUAGE_MISMATCH";
+
+export const MultiStageAboutWelcome = props => {
+ let { defaultScreens } = props;
+ const didFilter = useRef(false);
+ const [didMount, setDidMount] = useState(false);
+ const [screens, setScreens] = useState(defaultScreens);
+
+ const [index, setScreenIndex] = useState(props.startScreen);
+ const [previousOrder, setPreviousOrder] = useState(props.startScreen - 1);
+
+ useEffect(() => {
+ (async () => {
+ // If we want to load index from history state, we don't want to send impression yet
+ if (!didMount) {
+ return;
+ }
+ // On about:welcome first load, screensVisited should be empty
+ let screensVisited = didFilter.current ? screens.slice(0, index) : [];
+ let upcomingScreens = defaultScreens
+ .filter(s => !screensVisited.find(v => v.id === s.id))
+ // Filter out Language Mismatch screen from upcoming
+ // screens if screens set from useLanguageSwitcher hook
+ // has filtered language screen
+ .filter(
+ upcomingScreen =>
+ !(
+ !screens.find(s => s.id === LANGUAGE_MISMATCH_SCREEN_ID) &&
+ upcomingScreen.id === LANGUAGE_MISMATCH_SCREEN_ID
+ )
+ );
+
+ let filteredScreens = screensVisited.concat(
+ (await window.AWEvaluateScreenTargeting(upcomingScreens)) ??
+ upcomingScreens
+ );
+
+ // Use existing screen for the filtered screen to carry over any modification
+ // e.g. if AW_LANGUAGE_MISMATCH exists, use it from existing screens
+ setScreens(
+ filteredScreens.map(
+ filtered => screens.find(s => s.id === filtered.id) ?? filtered
+ )
+ );
+
+ didFilter.current = true;
+
+ const screenInitials = filteredScreens
+ .map(({ id }) => id?.split("_")[1]?.[0])
+ .join("");
+ // Send impression ping when respective screen first renders
+ filteredScreens.forEach((screen, order) => {
+ if (index === order) {
+ AboutWelcomeUtils.sendImpressionTelemetry(
+ `${props.message_id}_${order}_${screen.id}_${screenInitials}`
+ );
+ window.AWAddScreenImpression?.(screen);
+ }
+ });
+
+ // Remember that a new screen has loaded for browser navigation
+ if (props.updateHistory && index > window.history.state) {
+ window.history.pushState(index, "");
+ }
+
+ // Remember the previous screen index so we can animate the transition
+ setPreviousOrder(index);
+ })();
+ }, [index, didMount]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const [flowParams, setFlowParams] = useState(null);
+ const { metricsFlowUri } = props;
+ useEffect(() => {
+ (async () => {
+ if (metricsFlowUri) {
+ setFlowParams(await AboutWelcomeUtils.fetchFlowParams(metricsFlowUri));
+ }
+ })();
+ }, [metricsFlowUri]);
+
+ // Allow "in" style to render to actually transition towards regular state,
+ // which also makes using browser back/forward navigation skip transitions.
+ const [transition, setTransition] = useState(props.transitions ? "in" : "");
+ useEffect(() => {
+ if (transition === "in") {
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => setTransition(""))
+ );
+ }
+ }, [transition]);
+
+ // Transition to next screen, opening about:home on last screen button CTA
+ const handleTransition = () => {
+ // Only handle transitioning out from a screen once.
+ if (transition === "out") {
+ return;
+ }
+
+ // Start transitioning things "out" immediately when moving forwards.
+ setTransition(props.transitions ? "out" : "");
+
+ // Actually move forwards after all transitions finish.
+ setTimeout(
+ () => {
+ if (index < screens.length - 1) {
+ setTransition(props.transitions ? "in" : "");
+ setScreenIndex(prevState => prevState + 1);
+ } else {
+ window.AWFinish();
+ }
+ },
+ props.transitions ? TRANSITION_OUT_TIME : 0
+ );
+ };
+
+ useEffect(() => {
+ // When about:welcome loads (on refresh or pressing back button
+ // from about:home), ensure history state usEffect runs before
+ // useEffect hook that send impression telemetry
+ setDidMount(true);
+
+ if (props.updateHistory) {
+ // Switch to the screen tracked in state (null for initial state)
+ // or last screen index if a user navigates by pressing back
+ // button from about:home
+ const handler = ({ state }) => {
+ if (transition === "out") {
+ return;
+ }
+ setTransition(props.transitions ? "out" : "");
+ setTimeout(
+ () => {
+ setTransition(props.transitions ? "in" : "");
+ setScreenIndex(Math.min(state, screens.length - 1));
+ },
+ props.transitions ? TRANSITION_OUT_TIME : 0
+ );
+ };
+
+ // Handle page load, e.g., going back to about:welcome from about:home
+ const { state } = window.history;
+ if (state) {
+ setScreenIndex(Math.min(state, screens.length - 1));
+ setPreviousOrder(Math.min(state, screens.length - 1));
+ }
+
+ // Watch for browser back/forward button navigation events
+ window.addEventListener("popstate", handler);
+ return () => window.removeEventListener("popstate", handler);
+ }
+ return false;
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Save the active multi select state containing array of checkbox ids
+ // used in handleAction to update MULTI_ACTION data
+ const [activeMultiSelect, setActiveMultiSelect] = useState(null);
+
+ // 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 { negotiatedLanguage, langPackInstallPhase, languageFilteredScreens } =
+ useLanguageSwitcher(
+ props.appAndSystemLocaleInfo,
+ screens,
+ index,
+ setScreenIndex
+ );
+
+ useEffect(() => {
+ setScreens(languageFilteredScreens);
+ }, [languageFilteredScreens]);
+
+ return (
+ <React.Fragment>
+ <div
+ className={`outer-wrapper onboardingContainer proton transition-${transition}`}
+ style={props.backdrop ? { background: props.backdrop } : {}}
+ >
+ {screens.map((screen, order) => {
+ const isFirstScreen = screen === screens[0];
+ const isLastScreen = screen === screens[screens.length - 1];
+ const totalNumberOfScreens = screens.length;
+ const isSingleScreen = totalNumberOfScreens === 1;
+
+ return index === order ? (
+ <WelcomeScreen
+ key={screen.id + order}
+ id={screen.id}
+ totalNumberOfScreens={totalNumberOfScreens}
+ isFirstScreen={isFirstScreen}
+ isLastScreen={isLastScreen}
+ isSingleScreen={isSingleScreen}
+ order={order}
+ previousOrder={previousOrder}
+ content={screen.content}
+ navigate={handleTransition}
+ messageId={`${props.message_id}_${order}_${screen.id}`}
+ UTMTerm={props.utm_term}
+ flowParams={flowParams}
+ activeTheme={activeTheme}
+ initialTheme={initialTheme}
+ setActiveTheme={setActiveTheme}
+ setInitialTheme={setInitialTheme}
+ activeMultiSelect={activeMultiSelect}
+ setActiveMultiSelect={setActiveMultiSelect}
+ autoAdvance={screen.auto_advance}
+ negotiatedLanguage={negotiatedLanguage}
+ langPackInstallPhase={langPackInstallPhase}
+ />
+ ) : null;
+ })}
+ </div>
+ </React.Fragment>
+ );
+};
+
+export const SecondaryCTA = props => {
+ let targetElement = props.position
+ ? `secondary_button_${props.position}`
+ : `secondary_button`;
+ const buttonStyling = props.content.secondary_button?.has_arrow_icon
+ ? `secondary text-link arrow-icon`
+ : `secondary text-link`;
+
+ return (
+ <div
+ className={
+ props.position ? `secondary-cta ${props.position}` : "secondary-cta"
+ }
+ >
+ <Localized text={props.content[targetElement].text}>
+ <span />
+ </Localized>
+ <Localized text={props.content[targetElement].label}>
+ <button
+ className={buttonStyling}
+ value={targetElement}
+ onClick={props.handleAction}
+ />
+ </Localized>
+ </div>
+ );
+};
+
+export const StepsIndicator = props => {
+ let steps = [];
+ for (let i = 0; i < props.totalNumberOfScreens; i++) {
+ let className = `${i === props.order ? "current" : ""} ${
+ i < props.order ? "complete" : ""
+ }`;
+ steps.push(
+ <div key={i} className={`indicator ${className}`} role="presentation" />
+ );
+ }
+ return steps;
+};
+
+export const ProgressBar = ({ step, previousStep, totalNumberOfScreens }) => {
+ const [progress, setProgress] = React.useState(
+ previousStep / totalNumberOfScreens
+ );
+ useEffect(() => {
+ // We don't need to hook any dependencies because any time the step changes,
+ // the screen's entire DOM tree will be re-rendered.
+ setProgress(step / totalNumberOfScreens);
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ return (
+ <div
+ className="indicator"
+ role="presentation"
+ style={{ "--progress-bar-progress": `${progress * 100}%` }}
+ />
+ );
+};
+
+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: `${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, `${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() };
+ }
+ return AboutWelcomeUtils.handleUserAction({ type, data });
+ }
+
+ async handleAction(event) {
+ let { props } = this;
+ const value =
+ event.currentTarget.value ?? event.currentTarget.getAttribute("value");
+ const source = event.source || value;
+ let targetContent =
+ props.content[value] ||
+ props.content.tiles ||
+ props.content.languageSwitcher;
+
+ if (!(targetContent && targetContent.action)) {
+ return;
+ }
+ // Send telemetry before waiting on actions
+ AboutWelcomeUtils.sendActionTelemetry(props.messageId, source, event.name);
+
+ // Send additional telemetry if a messaging surface like feature callout is
+ // dismissed via the dismiss button. Other causes of dismissal will be
+ // handled separately by the messaging surface's own code.
+ if (value === "dismiss_button" && !event.name) {
+ AboutWelcomeUtils.sendDismissTelemetry(props.messageId, source);
+ }
+
+ let { action } = targetContent;
+
+ if (action.collectSelect) {
+ // Populate MULTI_ACTION data actions property with selected checkbox actions from tiles data
+ action.data = {
+ actions: [],
+ };
+
+ for (const checkbox of props.content?.tiles?.data ?? []) {
+ let checkboxAction;
+ if (this.props.activeMultiSelect.includes(checkbox.id)) {
+ checkboxAction = checkbox.checkedAction ?? checkbox.action;
+ } else {
+ checkboxAction = checkbox.uncheckedAction;
+ }
+
+ if (checkboxAction) {
+ action.data.actions.push(checkboxAction);
+ }
+ }
+
+ // Send telemetry with selected checkbox ids
+ AboutWelcomeUtils.sendActionTelemetry(
+ props.messageId,
+ props.activeMultiSelect,
+ "SELECT_CHECKBOX"
+ );
+ }
+
+ let actionResult;
+ if (["OPEN_URL", "SHOW_FIREFOX_ACCOUNTS"].includes(action.type)) {
+ actionResult = await this.handleOpenURL(
+ action,
+ props.flowParams,
+ props.UTMTerm
+ );
+ } else if (action.type) {
+ actionResult = await AboutWelcomeUtils.handleUserAction(action);
+ if (action.type === "FXA_SIGNIN_FLOW") {
+ AboutWelcomeUtils.sendActionTelemetry(
+ props.messageId,
+ actionResult ? "sign_in" : "sign_in_cancel",
+ "FXA_SIGNIN_FLOW"
+ );
+ }
+ // Wait until migration closes to complete the action
+ const hasMigrate = a =>
+ a.type === "SHOW_MIGRATION_WIZARD" ||
+ (a.type === "MULTI_ACTION" && a.data?.actions?.some(hasMigrate));
+ if (hasMigrate(action)) {
+ 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 the action has persistActiveTheme: true, we set the initial theme to the currently active theme
+ // so that it can be reverted to in the event that the user navigates away from the screen
+ if (action.persistActiveTheme) {
+ this.props.setInitialTheme(this.props.activeTheme);
+ }
+
+ // `navigate` and `dismiss` can be true/false/undefined, or they can be a
+ // string "actionResult" in which case we should use the actionResult
+ // (boolean resolved by handleUserAction)
+ const shouldDoBehavior = behavior =>
+ behavior === "actionResult" ? actionResult : behavior;
+
+ if (shouldDoBehavior(action.navigate)) {
+ props.navigate();
+ }
+
+ if (shouldDoBehavior(action.dismiss)) {
+ window.AWFinish();
+ }
+ }
+
+ render() {
+ return (
+ <MultiStageProtonScreen
+ content={this.props.content}
+ id={this.props.id}
+ order={this.props.order}
+ previousOrder={this.props.previousOrder}
+ activeTheme={this.props.activeTheme}
+ activeMultiSelect={this.props.activeMultiSelect}
+ setActiveMultiSelect={this.props.setActiveMultiSelect}
+ totalNumberOfScreens={this.props.totalNumberOfScreens}
+ appAndSystemLocaleInfo={this.props.appAndSystemLocaleInfo}
+ negotiatedLanguage={this.props.negotiatedLanguage}
+ langPackInstallPhase={this.props.langPackInstallPhase}
+ handleAction={this.handleAction}
+ messageId={this.props.messageId}
+ isFirstScreen={this.props.isFirstScreen}
+ isLastScreen={this.props.isLastScreen}
+ isSingleScreen={this.props.isSingleScreen}
+ startsWithCorner={this.props.startsWithCorner}
+ autoAdvance={this.props.autoAdvance}
+ />
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MultiStageProtonScreen.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MultiStageProtonScreen.jsx
new file mode 100644
index 0000000000..b51d2a2044
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MultiStageProtonScreen.jsx
@@ -0,0 +1,472 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, useState } from "react";
+import { Localized } from "./MSLocalized";
+import { Colorways } from "./MRColorways";
+import { MobileDownloads } from "./MobileDownloads";
+import { MultiSelect } from "./MultiSelect";
+import { Themes } from "./Themes";
+import {
+ SecondaryCTA,
+ StepsIndicator,
+ ProgressBar,
+} from "./MultiStageAboutWelcome";
+import { LanguageSwitcher } from "./LanguageSwitcher";
+import { CTAParagraph } from "./CTAParagraph";
+import { HeroImage } from "./HeroImage";
+import { OnboardingVideo } from "./OnboardingVideo";
+import { AdditionalCTA } from "./AdditionalCTA";
+import { EmbeddedMigrationWizard } from "./EmbeddedMigrationWizard";
+
+export const MultiStageProtonScreen = props => {
+ const { autoAdvance, handleAction, order } = props;
+ useEffect(() => {
+ if (autoAdvance) {
+ const timer = setTimeout(() => {
+ handleAction({
+ currentTarget: {
+ value: autoAdvance,
+ },
+ name: "AUTO_ADVANCE",
+ });
+ }, 20000);
+ return () => clearTimeout(timer);
+ }
+ return () => {};
+ }, [autoAdvance, handleAction, order]);
+
+ return (
+ <ProtonScreen
+ content={props.content}
+ id={props.id}
+ order={props.order}
+ activeTheme={props.activeTheme}
+ activeMultiSelect={props.activeMultiSelect}
+ setActiveMultiSelect={props.setActiveMultiSelect}
+ totalNumberOfScreens={props.totalNumberOfScreens}
+ handleAction={props.handleAction}
+ isFirstScreen={props.isFirstScreen}
+ isLastScreen={props.isLastScreen}
+ isSingleScreen={props.isSingleScreen}
+ previousOrder={props.previousOrder}
+ autoAdvance={props.autoAdvance}
+ isRtamo={props.isRtamo}
+ addonName={props.addonName}
+ isTheme={props.isTheme}
+ iconURL={props.iconURL}
+ messageId={props.messageId}
+ negotiatedLanguage={props.negotiatedLanguage}
+ langPackInstallPhase={props.langPackInstallPhase}
+ />
+ );
+};
+
+export const ProtonScreenActionButtons = props => {
+ const { content, addonName } = props;
+ const defaultValue = content.checkbox?.defaultValue;
+
+ const [isChecked, setIsChecked] = useState(defaultValue || false);
+
+ if (
+ !content.primary_button &&
+ !content.secondary_button &&
+ !content.additional_button
+ ) {
+ return null;
+ }
+
+ return (
+ <div
+ className={`action-buttons ${
+ content.additional_button ? "additional-cta-container" : ""
+ }`}
+ flow={content.additional_button?.flow}
+ >
+ <Localized text={content.primary_button?.label}>
+ <button
+ className="primary"
+ // Whether or not the checkbox is checked determines which action
+ // should be handled. By setting value here, we indicate to
+ // this.handleAction() where in the content tree it should take
+ // the action to execute from.
+ value={isChecked ? "checkbox" : "primary_button"}
+ disabled={content.primary_button?.disabled === true}
+ onClick={props.handleAction}
+ data-l10n-args={
+ addonName
+ ? JSON.stringify({
+ "addon-name": addonName,
+ })
+ : ""
+ }
+ />
+ </Localized>
+ {content.additional_button ? (
+ <AdditionalCTA content={content} handleAction={props.handleAction} />
+ ) : null}
+ {content.checkbox ? (
+ <div className="checkbox-container">
+ <input
+ type="checkbox"
+ id="action-checkbox"
+ checked={isChecked}
+ onChange={() => {
+ setIsChecked(!isChecked);
+ }}
+ ></input>
+ <Localized text={content.checkbox.label}>
+ <label htmlFor="action-checkbox"></label>
+ </Localized>
+ </div>
+ ) : null}
+ {content.secondary_button ? (
+ <SecondaryCTA content={content} handleAction={props.handleAction} />
+ ) : null}
+ </div>
+ );
+};
+
+export class ProtonScreen extends React.PureComponent {
+ componentDidMount() {
+ this.mainContentHeader.focus();
+ }
+
+ getScreenClassName(
+ isFirstScreen,
+ isLastScreen,
+ includeNoodles,
+ isVideoOnboarding
+ ) {
+ const screenClass = `screen-${this.props.order % 2 !== 0 ? 1 : 2}`;
+
+ if (isVideoOnboarding) return "with-video";
+
+ return `${isFirstScreen ? `dialog-initial` : ``} ${
+ isLastScreen ? `dialog-last` : ``
+ } ${includeNoodles ? `with-noodles` : ``} ${screenClass}`;
+ }
+
+ renderLogo({
+ imageURL = "chrome://branding/content/about-logo.svg",
+ darkModeImageURL,
+ reducedMotionImageURL,
+ darkModeReducedMotionImageURL,
+ alt = "",
+ height,
+ }) {
+ return (
+ <picture className="logo-container">
+ {darkModeReducedMotionImageURL ? (
+ <source
+ srcSet={darkModeReducedMotionImageURL}
+ media="(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)"
+ />
+ ) : null}
+ {darkModeImageURL ? (
+ <source
+ srcSet={darkModeImageURL}
+ media="(prefers-color-scheme: dark)"
+ />
+ ) : null}
+ {reducedMotionImageURL ? (
+ <source
+ srcSet={reducedMotionImageURL}
+ media="(prefers-reduced-motion: reduce)"
+ />
+ ) : null}
+ <img
+ className="brand-logo"
+ style={{ height }}
+ src={imageURL}
+ alt={alt}
+ role={alt ? null : "presentation"}
+ />
+ </picture>
+ );
+ }
+
+ renderContentTiles() {
+ const { content } = this.props;
+ return (
+ <React.Fragment>
+ {content.tiles &&
+ content.tiles.type === "colorway" &&
+ content.tiles.colorways ? (
+ <Colorways
+ content={content}
+ activeTheme={this.props.activeTheme}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ {content.tiles &&
+ content.tiles.type === "theme" &&
+ content.tiles.data ? (
+ <Themes
+ content={content}
+ activeTheme={this.props.activeTheme}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ {content.tiles &&
+ content.tiles.type === "mobile_downloads" &&
+ content.tiles.data ? (
+ <MobileDownloads
+ data={content.tiles.data}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ {content.tiles &&
+ content.tiles.type === "multiselect" &&
+ content.tiles.data ? (
+ <MultiSelect
+ content={content}
+ activeMultiSelect={this.props.activeMultiSelect}
+ setActiveMultiSelect={this.props.setActiveMultiSelect}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ {content.tiles && content.tiles.type === "migration-wizard" ? (
+ <EmbeddedMigrationWizard handleAction={this.props.handleAction} />
+ ) : null}
+ </React.Fragment>
+ );
+ }
+
+ renderNoodles() {
+ return (
+ <React.Fragment>
+ <div className={"noodle orange-L"} />
+ <div className={"noodle purple-C"} />
+ <div className={"noodle solid-L"} />
+ <div className={"noodle outline-L"} />
+ <div className={"noodle yellow-circle"} />
+ </React.Fragment>
+ );
+ }
+
+ renderLanguageSwitcher() {
+ return this.props.content.languageSwitcher ? (
+ <LanguageSwitcher
+ content={this.props.content}
+ handleAction={this.props.handleAction}
+ negotiatedLanguage={this.props.negotiatedLanguage}
+ langPackInstallPhase={this.props.langPackInstallPhase}
+ messageId={this.props.messageId}
+ />
+ ) : null;
+ }
+
+ renderDismissButton() {
+ return (
+ <button
+ className="dismiss-button"
+ onClick={this.props.handleAction}
+ value="dismiss_button"
+ data-l10n-id={"spotlight-dialog-close-button"}
+ ></button>
+ );
+ }
+
+ renderStepsIndicator() {
+ const currentStep = (this.props.order ?? 0) + 1;
+ const previousStep = (this.props.previousOrder ?? -1) + 1;
+ const { content, totalNumberOfScreens: total } = this.props;
+ return (
+ <div
+ id="steps"
+ className={`steps${content.progress_bar ? " progress-bar" : ""}`}
+ data-l10n-id={"onboarding-welcome-steps-indicator-label"}
+ data-l10n-args={JSON.stringify({
+ current: currentStep,
+ total: total ?? 0,
+ })}
+ data-l10n-attrs="aria-label"
+ role="progressbar"
+ aria-valuenow={currentStep}
+ aria-valuemin={1}
+ aria-valuemax={total}
+ >
+ {content.progress_bar ? (
+ <ProgressBar
+ step={currentStep}
+ previousStep={previousStep}
+ totalNumberOfScreens={total}
+ />
+ ) : (
+ <StepsIndicator
+ order={this.props.order}
+ totalNumberOfScreens={total}
+ />
+ )}
+ </div>
+ );
+ }
+
+ renderSecondarySection(content) {
+ return (
+ <div
+ className="section-secondary"
+ style={
+ content.background
+ ? {
+ background: content.background,
+ "--mr-secondary-background-position-y":
+ content.split_narrow_bkg_position,
+ }
+ : {}
+ }
+ >
+ <Localized text={content.image_alt_text}>
+ <div className="sr-only image-alt" role="img" />
+ </Localized>
+ {content.hero_image ? (
+ <HeroImage url={content.hero_image.url} />
+ ) : (
+ <React.Fragment>
+ <div className="message-text">
+ <div className="spacer-top" />
+ <Localized text={content.hero_text}>
+ <h1 />
+ </Localized>
+ <div className="spacer-bottom" />
+ </div>
+ <Localized text={content.help_text}>
+ <span className="attrib-text" />
+ </Localized>
+ </React.Fragment>
+ )}
+ </div>
+ );
+ }
+
+ render() {
+ const {
+ autoAdvance,
+ content,
+ isRtamo,
+ isTheme,
+ isFirstScreen,
+ isLastScreen,
+ isSingleScreen,
+ } = this.props;
+ const includeNoodles = content.has_noodles;
+ // The default screen position is "center"
+ const isCenterPosition = content.position === "center" || !content.position;
+ const hideStepsIndicator =
+ autoAdvance || content?.video_container || isSingleScreen;
+ const textColorClass = content.text_color
+ ? `${content.text_color}-text`
+ : "";
+ // Assign proton screen style 'screen-1' or 'screen-2' to centered screens
+ // by checking if screen order is even or odd.
+ const screenClassName = isCenterPosition
+ ? this.getScreenClassName(
+ isFirstScreen,
+ isLastScreen,
+ includeNoodles,
+ content?.video_container
+ )
+ : "";
+ const isEmbeddedMigration = content.tiles?.type === "migration-wizard";
+
+ return (
+ <main
+ className={`screen ${this.props.id || ""}
+ ${screenClassName} ${textColorClass}`}
+ role="alertdialog"
+ pos={content.position || "center"}
+ tabIndex="-1"
+ aria-labelledby="mainContentHeader"
+ ref={input => {
+ this.mainContentHeader = input;
+ }}
+ >
+ {isCenterPosition ? null : this.renderSecondarySection(content)}
+ <div
+ className={`section-main ${
+ isEmbeddedMigration ? "embedded-migration" : ""
+ }`}
+ role="document"
+ >
+ {content.secondary_button_top ? (
+ <SecondaryCTA
+ content={content}
+ handleAction={this.props.handleAction}
+ position="top"
+ />
+ ) : null}
+ {includeNoodles ? this.renderNoodles() : null}
+ <div
+ className={`main-content ${hideStepsIndicator ? "no-steps" : ""}`}
+ style={
+ content.background && isCenterPosition
+ ? { background: content.background }
+ : {}
+ }
+ >
+ {content.logo ? this.renderLogo(content.logo) : null}
+
+ {isRtamo ? (
+ <div className="rtamo-icon">
+ <img
+ className={`${isTheme ? "rtamo-theme-icon" : "brand-logo"}`}
+ src={this.props.iconURL}
+ role="presentation"
+ alt=""
+ />
+ </div>
+ ) : null}
+
+ <div className="main-content-inner">
+ <div className={`welcome-text ${content.title_style || ""}`}>
+ {content.title ? (
+ <Localized text={content.title}>
+ <h1 id="mainContentHeader" />
+ </Localized>
+ ) : null}
+ {content.subtitle ? (
+ <Localized text={content.subtitle}>
+ <h2
+ data-l10n-args={JSON.stringify({
+ "addon-name": this.props.addonName,
+ ...this.props.appAndSystemLocaleInfo?.displayNames,
+ })}
+ aria-flowto={
+ this.props.messageId?.includes("FEATURE_TOUR")
+ ? "steps"
+ : ""
+ }
+ />
+ </Localized>
+ ) : null}
+ {content.cta_paragraph ? (
+ <CTAParagraph
+ content={content.cta_paragraph}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ </div>
+ {content.video_container ? (
+ <OnboardingVideo
+ content={content.video_container}
+ handleAction={this.props.handleAction}
+ />
+ ) : null}
+ {this.renderContentTiles()}
+ {this.renderLanguageSwitcher()}
+ <ProtonScreenActionButtons
+ content={content}
+ addonName={this.props.addonName}
+ handleAction={this.props.handleAction}
+ />
+ </div>
+ {!hideStepsIndicator ? this.renderStepsIndicator() : null}
+ </div>
+ {content.dismiss_button ? this.renderDismissButton() : null}
+ </div>
+ </main>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/OnboardingVideo.jsx b/browser/components/newtab/content-src/aboutwelcome/components/OnboardingVideo.jsx
new file mode 100644
index 0000000000..629a409a59
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/OnboardingVideo.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";
+
+export const OnboardingVideo = props => {
+ const vidUrl = props.content.video_url;
+ const autoplay = props.content.autoPlay;
+
+ const handleVideoAction = event => {
+ props.handleAction({
+ currentTarget: {
+ value: event,
+ },
+ });
+ };
+
+ return (
+ <div>
+ <video // eslint-disable-line jsx-a11y/media-has-caption
+ controls={true}
+ autoPlay={autoplay}
+ src={vidUrl}
+ width="604px"
+ height="340px"
+ onPlay={() => handleVideoAction("video_start")}
+ onEnded={() => handleVideoAction("video_end")}
+ >
+ <source src={vidUrl}></source>
+ </video>
+ </div>
+ );
+};
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..fb5e80c6e4
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx
@@ -0,0 +1,105 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { MultiStageProtonScreen } from "./MultiStageProtonScreen";
+import { BASE_PARAMS } from "../../asrouter/templates/FirstRun/addUtmParams";
+
+export class ReturnToAMO extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.fetchFlowParams = this.fetchFlowParams.bind(this);
+ this.handleAction = this.handleAction.bind(this);
+ }
+
+ async fetchFlowParams() {
+ if (this.props.metricsFlowUri) {
+ this.setState({
+ flowParams: await AboutWelcomeUtils.fetchFlowParams(
+ this.props.metricsFlowUri
+ ),
+ });
+ }
+ }
+
+ componentDidUpdate() {
+ this.fetchFlowParams();
+ }
+
+ handleAction(event) {
+ const { content, message_id, url, utm_term } = this.props;
+ let { action, source_id } = content[event.currentTarget.value];
+ let { type, data } = action;
+
+ if (type === "INSTALL_ADDON_FROM_URL") {
+ if (!data) {
+ return;
+ }
+ // Set add-on url in action.data.url property from JSON
+ data = { ...data, url };
+ } else if (type === "SHOW_FIREFOX_ACCOUNTS") {
+ let params = {
+ ...BASE_PARAMS,
+ utm_term: `aboutwelcome-${utm_term}-screen`,
+ };
+ if (action.addFlowParams && this.state.flowParams) {
+ params = {
+ ...params,
+ ...this.state.flowParams,
+ };
+ }
+ data = { ...data, extraParams: params };
+ }
+
+ AboutWelcomeUtils.handleUserAction({ type, data });
+ AboutWelcomeUtils.sendActionTelemetry(message_id, source_id);
+ }
+
+ render() {
+ const { content, type } = this.props;
+
+ if (!content) {
+ return null;
+ }
+
+ if (content?.primary_button.label) {
+ content.primary_button.label.string_id = type.includes("theme")
+ ? "return-to-amo-add-theme-label"
+ : "mr1-return-to-amo-add-extension-label";
+ }
+
+ // 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 proton"}
+ style={content.backdrop ? { background: content.backdrop } : {}}
+ >
+ <MultiStageProtonScreen
+ content={content}
+ isRtamo={true}
+ isTheme={type.includes("theme")}
+ id={this.props.message_id}
+ order={this.props.order || 0}
+ totalNumberOfScreens={1}
+ isSingleScreen={true}
+ autoAdvance={this.props.auto_advance}
+ iconURL={
+ type.includes("theme")
+ ? this.props.themeScreenshots[0]?.url
+ : this.props.iconURL
+ }
+ addonName={this.props.name}
+ handleAction={this.handleAction}
+ />
+ </div>
+ );
+ }
+}
+
+ReturnToAMO.defaultProps = DEFAULT_RTAMO_CONTENT;
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/Themes.jsx b/browser/components/newtab/content-src/aboutwelcome/components/Themes.jsx
new file mode 100644
index 0000000000..def2603426
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/Themes.jsx
@@ -0,0 +1,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/. */
+
+import React from "react";
+import { Localized } from "./MSLocalized";
+
+export const Themes = props => {
+ return (
+ <div className="tiles-theme-container">
+ <div>
+ <fieldset className="tiles-theme-section">
+ <Localized text={props.content.subtitle}>
+ <legend className="sr-only" />
+ </Localized>
+ {props.content.tiles.data.map(
+ ({ theme, label, tooltip, description }) => (
+ <Localized
+ key={theme + label}
+ text={typeof tooltip === "object" ? tooltip : {}}
+ >
+ <label className="theme" title={theme + label}>
+ <Localized
+ text={typeof description === "object" ? description : {}}
+ >
+ <input
+ type="radio"
+ value={theme}
+ name="theme"
+ checked={theme === props.activeTheme}
+ className="sr-only input"
+ onClick={props.handleAction}
+ />
+ </Localized>
+ <div
+ className={`icon ${
+ theme === props.activeTheme ? " selected" : ""
+ } ${theme}`}
+ />
+ <Localized text={label}>
+ <div className="text" />
+ </Localized>
+ </label>
+ </Localized>
+ )
+ )}
+ </fieldset>
+ </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..c588e8e850
--- /dev/null
+++ b/browser/components/newtab/content-src/activity-stream.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 {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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.sys.mjs";
+
+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..4c3f08d4cd
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/asrouter-content.jsx
@@ -0,0 +1,346 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+import { ASRouterUtils } from "./asrouter-utils";
+import { generateBundles } from "./rich-text-strings";
+import { ImpressionsWrapper } from "./components/ImpressionsWrapper/ImpressionsWrapper";
+import { LocalizationProvider, ReactLocalization } 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);
+ }
+
+ 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);
+ }
+ } catch (error) {
+ console.error(error);
+ }
+ 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,
+ campaign: this.state.message.campaign,
+ });
+ }
+
+ onBlockById(id, options) {
+ return ASRouterUtils.blockById(id, options).then(clearAll => {
+ if (clearAll) {
+ this.setState({ message: {} });
+ }
+ });
+ }
+
+ onDismiss() {
+ this.clearMessage(this.state.message.id);
+ }
+
+ // Blocking a snippet by id blocks the entire campaign
+ // so when clearing we use the two values interchangeably
+ clearMessage(idOrCampaign) {
+ if (
+ idOrCampaign === this.state.message.id ||
+ idOrCampaign === this.state.message.campaign
+ ) {
+ 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, prevState) {
+ if (
+ prevProps.adminContent &&
+ JSON.stringify(prevProps.adminContent) !==
+ JSON.stringify(this.props.adminContent)
+ ) {
+ this.updateContent();
+ }
+ if (prevState.message.id !== this.state.message.id) {
+ const main = global.window.document.querySelector("main");
+ if (main) {
+ if (this.state.message.id) {
+ main.classList.add("has-snippet");
+ } else {
+ main.classList.remove("has-snippet");
+ }
+ }
+ }
+ }
+
+ 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 } = 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
+ l10n={new ReactLocalization(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..9864823a77
--- /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.sys.mjs";
+import { actionCreators as ac } from "common/Actions.sys.mjs";
+
+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..35234be4b0
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/Button/_Button.scss
@@ -0,0 +1,51 @@
+.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-primary-action-background);
+ background-color: var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+
+ &:hover {
+ background-color: var(--newtab-primary-element-hover-color);
+ }
+
+ &:active {
+ background-color: var(--newtab-primary-element-active-color);
+ }
+ }
+
+ &.slim {
+ border: $border-primary;
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px;
+
+ &:hover,
+ &:focus {
+ box-shadow: $shadow-primary;
+ transition: box-shadow 150ms;
+ }
+ }
+}
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..a1006c9437
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/ModalOverlay/_ModalOverlay.scss
@@ -0,0 +1,103 @@
+// 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-background-color-secondary);
+ box-shadow: $shadow-large;
+ 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: var(--newtab-text-primary-color);
+ 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: $border-secondary;
+ 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 {
+ @include fade-in-card;
+ }
+ }
+ }
+}
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..d430fa5c3d
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx
@@ -0,0 +1,86 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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}
+ rel="noreferrer"
+ 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}
+ elems={{
+ ...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..86bc30fa8b
--- /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-background-color-secondary);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid transparent;
+ box-shadow: $shadow-secondary;
+ display: flex;
+ align-items: center;
+
+ a {
+ cursor: pointer;
+ color: var(--newtab-primary-action-background);
+
+ &: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;
+ max-width: $wrapper-max-width-large + ($section-horizontal-padding * 2);
+
+ @media (min-width: $break-point-large) {
+ padding-inline-end: $section-horizontal-padding;
+ }
+
+ @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: 20px;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url('chrome://global/skin/icons/close.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: var(--newtab-text-primary-color);
+ background: var(--newtab-background-color-secondary);
+ 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..fedeeced5a
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/debugging-docs.md
@@ -0,0 +1,63 @@
+# 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
+
+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`
+- To view additional debug logs for messaging system or about:welcome, set:
+ - `messaging-system.log` to `debug`
+ - `browser.aboutwelcome.log` to `debug`
+- 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/first-run.md b/browser/components/newtab/content-src/asrouter/docs/first-run.md
new file mode 100644
index 0000000000..a7d84b0136
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/first-run.md
@@ -0,0 +1,68 @@
+# Onboarding flow
+
+Onboarding flow comprises of entire flow users have after Firefox has successfully been installed or upgraded.
+
+For new users, the first instance of new tab shows relevant messaging on about:welcome. For existing users, an upgrade dialog with release highlights is shown on major release upgrades.
+
+
+## New User Onboarding
+
+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` takes user to about:newtab and hides about:welcome.
+
+### Default values
+
+Multistage proton onboarding experience is live since Fx89 and its major variations are:
+
+#### Zero onboarding
+
+No about:welcome experience is shown (users see about:newtab during first run).
+
+Testing instructions: Set `browser.aboutwelcome.enabled` to `false` in about:config
+
+#### Proton
+
+A full-page multistep experience that shows a large splash screen and several subsequent screens. See [Default experience variations](#default-experience-variations) for more information.
+
+#### Return to AMO (RTAMO)
+
+Special custom onboarding experience shown to users when they try to download an addon from addons.mozilla.org but don’t have Firefox installed. This experience allows them to install the addon they were trying to install directly from a button on [RTAMO](https://docs.google.com/document/d/1QOJ8P0xQbdynAmEzOIx8I5qARwA-VqmOMpHzK9h9msg/edit?usp=sharing).
+
+Note that this uses [attribution data](https://docs.google.com/document/d/1zB5zwiyNVOiTD4I3aZ-Wm8KFai9nnWuRHsPg-NW4tcc/edit#heading=h.szk066tfte4n) added to the browser during the download process, which is only currently implemented for Windows.
+
+Testing instructions:
+- Set pref browser.newtabpage.activity-stream.asrouter.devtoolsEnabled as true
+- Open about:newtab#devtools
+- Click Targeting -> Attribution -> Force Attribution
+- Open about:welcome, should display RTAMO page
+
+### General capabilities
+- Run experiments and roll-outs through Nimbus (see [FeatureManifests](https://searchfox.org/mozilla-central/rev/5e955a47c4af398e2a859b34056017764e7a2252/toolkit/components/nimbus/FeatureManifest.js#56)), only windows is supported. FeatureConfig (from prefs or experiments) has higher precedence to defaults. See [Default experience variations](#default-experience-variations)
+- AboutWelcomeDefaults methods [getDefaults](https://searchfox.org/mozilla-central/rev/81c32a2ea5605c5cb22bd02d28c362c140b5cfb4/browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm#539) and [prepareContentForReact](https://searchfox.org/mozilla-central/rev/81c32a2ea5605c5cb22bd02d28c362c140b5cfb4/browser/components/newtab/aboutwelcome/lib/AboutWelcomeDefaults.jsm#566) have dynamic rules which are applied to both experiments and default UI before content is shown to user.
+- about:welcome only shows up for users who download Firefox Beta or release (currently not enabled on Nightly)
+- [Enterprise builds](https://searchfox.org/mozilla-central/rev/5e955a47c4af398e2a859b34056017764e7a2252/browser/components/enterprisepolicies/Policies.jsm#1385) can turn off about:welcome by setting the browser.aboutwelcome.enabled preference to false.
+
+### Default experience variations
+In order of precedence:
+- Has AMO attribution
+ - Return to AMO
+- Experiments
+- Defaults
+ - Proton default content with below screens
+ - Welcome Screen with option to 'Pin Firefox', 'Set default' or 'Get Started'
+ - Import screen allows user to import password, bookmarks and browsing history from previous browser.
+ - Set a theme lets users personalize Firefox with a theme.
+
+## Upgrade Dialog
+Upgrade Dialog was first introduced in Fx89 with MR1 release. It replaces whatsnew tab with an upgrade modal explaining proton changes, setting Firefox as default and/or pinning, and allowing theme change.
+
+### Feature Details:
+- Hides whatsnew tab on release channel when Upgrade Modal is shown
+- Modal dialog appears on major version upgrade to 89 for MR1
+ - It’s a window modal preventing access to tabs and other toolbar UI
+- Support desired content and actions on each screen. For MR1 initial screen explains proton changes, highlight option to set Firefox as default and pin. Subsequent screen allows theme changes.
+
+### Testing Instructions:
+- In about:config, set:
+ - `browser.startup.homepage_override.mstone` to `88.0` . The dialog only shows after it detects a major upgrade and need to set to 88 to trigger MR1 upgrade dialog.
+ - Ensure pref `browser.startup.upgradeDialog.version` is empty. After the dialog shows, `browser.startup.upgradeDialog.version` remembers what version of the dialog to avoid reshowing.
+- Restart Firefox
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..58241ef0d7
--- /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\:
+
+* 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
+* About Welcome - shown on startup for new users in about:welcome content page
+* Snippets - short messages that appear on New Tab Page to highlight products,
+ features and initiatives
+* Infobars - Shown at the top of browser content area these can be per tab
+ (switching tabs hides it) or global (persistent across tabs)
+* Spotlight - This is a window level modal, all other interactions are prevented,
+ the user is given a primary and a secondary button to interact with the modal.
+* PrivateBrowsing - Message shown inside about:PrivateBrowsing content page
+
+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
+ 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..a1edf4cc8a
--- /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..8fadcea0fd
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/targeting-attributes.md
@@ -0,0 +1,986 @@
+# 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
+
+* [activeNotifications](#activenotifications)
+* [addonsInfo](#addonsinfo)
+* [addressesSaved](#addressessaved)
+* [attachedFxAOAuthClients](#attachedfxaoauthclients)
+* [attributionData](#attributiondata)
+* [backgroundTaskName](#backgroundtaskname)
+* [blockedCountByType](#blockedcountbytype)
+* [browserSettings](#browsersettings)
+* [colorwaysActive](#colorwaysActive)
+* [creditCardsSaved](#creditcardssaved)
+* [currentDate](#currentdate)
+* [defaultPDFHandler](#defaultpdfhandler)
+* [devToolsOpenedCount](#devtoolsopenedcount)
+* [distributionId](#distributionId)
+* [doesAppNeedPin](#doesappneedpin)
+* [doesAppNeedPrivatePin](#doesappneedprivatepin)
+* [firefoxVersion](#firefoxversion)
+* [fxViewButtonAreaType](#fxviewbuttonareatype)
+* [hasAccessedFxAPanel](#hasaccessedfxapanel)
+* [hasActiveEnterprisePolicies](#hasactiveenterprisepolicies)
+* [hasMigratedBookmarks](#hasmigratedbookmarks)
+* [hasMigratedHistory](#hasmigratedhistory)
+* [hasMigratedPasswords](#hasmigratedpasswords)
+* [hasPinnedTabs](#haspinnedtabs)
+* [homePageSettings](#homepagesettings)
+* [inMr2022Holdback](#inmr2022holdback)
+* [isBackgroundTaskMode](#isbackgroundtaskmode)
+* [isChinaRepack](#ischinarepack)
+* [isDefaultBrowser](#isdefaultbrowser)
+* [isDefaultHandler](#isdefaulthandler)
+* [isDeviceMigration](#isdevicemigration)
+* [isFxAEnabled](#isfxaenabled)
+* [isFxASignedIn](#isFxASignedIn)
+* [isMajorUpgrade](#ismajorupgrade)
+* [isRTAMO](#isrtamo)
+* [isWhatsNewPanelEnabled](#iswhatsnewpanelenabled)
+* [locale](#locale)
+* [localeLanguageCode](#localelanguagecode)
+* [messageImpressions](#messageimpressions)
+* [needsUpdate](#needsupdate)
+* [newtabSettings](#newtabsettings)
+* [pinnedSites](#pinnedsites)
+* [platformName](#platformname)
+* [previousSessionEnd](#previoussessionend)
+* [profileAgeCreated](#profileagecreated)
+* [profileAgeReset](#profileagereset)
+* [profileRestartCount](#profilerestartcount)
+* [providerCohorts](#providercohorts)
+* [recentBookmarks](#recentbookmarks)
+* [region](#region)
+* [screenImpressions](#screenImpressions)
+* [searchEngines](#searchengines)
+* [sync](#sync)
+* [topFrecentSites](#topfrecentsites)
+* [totalBlockedCount](#totalblockedcount)
+* [totalBookmarksCount](#totalbookmarkscount)
+* [userEnabledActiveColorway](#userEnabledActiveColorway)
+* [userId](#userid)
+* [userMonthlyActivity](#usermonthlyactivity)
+* [userPrefersReducedMotion](#userprefersreducedmotion)
+* [useEmbeddedMigrationWizard][#useembeddedmigrationwizard]
+* [userPrefs](#userprefs)
+* [usesFirefoxSync](#usesfirefoxsync)
+* [xpinstallEnabled](#xpinstallEnabled)
+
+## 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`
+
+* `update`, which has information about Firefox update channel
+
+#### Examples
+
+* Is updating enabled?
+```java
+browserSettings.update.enabled
+```
+
+* Is beta channel?
+```js
+browserSettings.update.channel == 'beta'
+```
+
+#### 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;
+```
+
+### `isDefaultHandler`
+
+Is Firefox the user's default handler for various file extensions?
+
+Windows-only.
+
+#### Definition
+
+```ts
+declare const isDefaultHandler: {
+ pdf: boolean;
+ html: boolean;
+};
+```
+
+#### Examples
+* Is Firefox the default PDF handler?
+```ts
+isDefaultHandler.pdf
+```
+
+### `defaultPDFHandler`
+
+Information about the user's default PDF handler
+
+Windows-only.
+
+#### Definition
+
+```ts
+declare const defaultPDFHandler: {
+ // Does the user have a default PDF handler registered?
+ registered: boolean;
+
+ // Is the default PDF handler a known browser?
+ knownBrowser: 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;
+```
+
+### `isFxASignedIn`
+
+Is the user signed in to a Firefox Account?
+
+#### Definition
+
+```ts
+declare const isFxASignedIn: Promise<boolean>
+```
+
+### `creditCardsSaved`
+
+The number of credit cards the user has saved for Forms and Autofill.
+
+#### Examples
+```java
+creditCardsSaved > 1
+```
+
+#### Definition
+
+```ts
+declare const creditCardsSaved: Promise<number>
+```
+
+### `addressesSaved`
+
+The number of addresses the user has saved for Forms and Autofill.
+
+#### Examples
+```java
+addressesSaved > 1
+```
+
+#### Definition
+
+```ts
+declare const addressesSaved: Promise<number>
+```
+
+### `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/c5c002f81f08a73e04868e0c2bf0eb113f200b03/toolkit/modules/NewTabUtils.sys.mjs#1059)
+
+#### 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/c5c002f81f08a73e04868e0c2bf0eb113f200b03/toolkit/modules/AppConstants.sys.mjs#153).
+
+#### Definition
+
+```
+declare const platformName = "linux" | "win" | "macosx" | "android" | "other";
+```
+
+### `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: "",
+}
+```
+
+### `activeNotifications`
+
+True when an infobar style message is displayed or when the awesomebar is
+expanded to show a message (for example onboarding tips).
+
+### `isMajorUpgrade`
+
+A boolean. `true` if the browser just updated to a new major version.
+
+### `hasActiveEnterprisePolicies`
+
+A boolean. `true` if any Enterprise Policies are active.
+
+### `userMonthlyActivity`
+
+Returns an array of entries in the form `[int, unixTimestamp]` for each day of
+user activity where the first entry is the total urls visited for that day.
+
+### `doesAppNeedPin`
+
+Checks if Firefox app can be and isn't pinned to OS taskbar/dock.
+
+### `doesAppNeedPrivatePin`
+
+Checks if Firefox Private Browsing Mode can be and isn't pinned to OS taskbar/dock. Currently this only works on certain Windows versions.
+
+### `isBackgroundTaskMode`
+
+Checks if this invocation is running in background task mode.
+
+### `backgroundTaskName`
+
+A non-empty string task name if this invocation is running in background task
+mode, or `null` if this invocation is not running in background task mode.
+
+### `userPrefersReducedMotion`
+
+Checks if user prefers reduced motion as indicated by the value of a media query for `prefers-reduced-motion`.
+
+### `inMr2022Holdback`
+
+A boolean. `true` when the user is in the Major Release 2022 holdback study.
+
+### `distributionId`
+
+A string containing the id of the distribution, or the empty string if there
+is no distribution associated with the build.
+
+### `fxViewButtonAreaType`
+
+A string of the name of the container where the Firefox View button is shown, null if the button has been removed.
+
+### `hasMigratedBookmarks`
+
+A boolean. `true` if the user ever used the Migration Wizard to migrate bookmarks.
+
+### `hasMigratedHistory`
+
+A boolean. `true` if the user ever used the Migration Wizard to migrate history.
+
+### `hasMigratedPasswords`
+
+A boolean. `true` if the user ever used the Migration Wizard to migrate passwords.
+
+### `useEmbeddedMigrationWizard`
+
+A boolean. `true` if the user is configured to use the embedded Migration Wizard in about:welcome.
+
+### `isRTAMO`
+
+A boolean. `true` when [RTAMO](first-run.md#return-to-amo-rtamo) has been used to download Firefox, `false` otherwise.
+
+### `isDeviceMigration`
+
+A boolean. `true` when [support.mozilla.org](https://support.mozilla.org) has been used to download the browser as part of a "migration" campaign, for device migration guidance, `false` otherwise.
+### `screenImpressions`
+
+An array that maps about:welcome screen IDs to their most recent impression timestamp. Should only be used for unique screen IDs to avoid unintentionally targeting messages with identical screen IDs.
+#### Definition
+
+```
+declare const screenImpressions: { [key: string]: Array<UnixEpochNumber> };
+```
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..3172cece81
--- /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..3bcba7c386
--- /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, FluentResource } from "@fluent/bundle";
+
+/**
+ * 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.addResource(new FluentResource(`${key} = ${string}`));
+ });
+ return [bundle];
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/BackgroundTaskMessagingExperiment.schema.json b/browser/components/newtab/content-src/asrouter/schemas/BackgroundTaskMessagingExperiment.schema.json
new file mode 100644
index 0000000000..109a9d6cd1
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/BackgroundTaskMessagingExperiment.schema.json
@@ -0,0 +1,312 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json",
+ "title": "Messaging Experiment",
+ "description": "A Firefox Messaging System message.",
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "const": "multi"
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/MultiMessage"
+ },
+ "else": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/TemplatedMessage"
+ },
+ "$defs": {
+ "ToastNotification": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ToastNotification.schema.json",
+ "title": "ToastNotification",
+ "description": "A template for toast notifications displayed by the Alert service.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification title"
+ },
+ "body": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification body"
+ },
+ "icon_url": {
+ "description": "The URL of the image used as an icon of the toast notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "image_url": {
+ "description": "The URL of an image to be displayed as part of the notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "launch_url": {
+ "description": "The URL to launch when the notification or an action button is clicked.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "requireInteraction": {
+ "type": "boolean",
+ "description": "Whether the toast notification should remain active until the user clicks or dismisses it, rather than closing automatically."
+ },
+ "tag": {
+ "type": "string",
+ "description": "An identifying tag for the toast notification."
+ },
+ "data": {
+ "type": "object",
+ "description": "Arbitrary data associated with the toast notification."
+ },
+ "actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "The action text to be shown to the user."
+ },
+ "action": {
+ "type": "string",
+ "description": "Opaque identifer that identifies action."
+ },
+ "iconURL": {
+ "type": "string",
+ "format": "uri",
+ "description": "URL of an icon to display with the action."
+ },
+ "windowsSystemActivationType": {
+ "type": "boolean",
+ "description": "Whether to have Windows process the given `action`."
+ }
+ },
+ "required": [
+ "action",
+ "title"
+ ],
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "title",
+ "body"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "toast_notification"
+ }
+ },
+ "required": [
+ "content",
+ "targeting",
+ "template",
+ "trigger"
+ ],
+ "additionalProperties": true
+ },
+ "Message": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The message identifier"
+ },
+ "groups": {
+ "description": "Array of preferences used to control `enabled` status of the group. If any is `false` the group is disabled.",
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "Preference name"
+ }
+ },
+ "template": {
+ "type": "string",
+ "description": "Which messaging template this message is using.",
+ "enum": [
+ "toast_notification"
+ ]
+ },
+ "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": {
+ "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"
+ ]
+ }
+ }
+ }
+ },
+ "priority": {
+ "description": "The priority of the message. If there are two competing messages to show, the one with the highest priority will be shown",
+ "type": "integer"
+ },
+ "order": {
+ "description": "The order in which messages should be shown. Messages will be shown in increasing order.",
+ "type": "integer"
+ },
+ "targeting": {
+ "description": "A JEXL expression representing targeting information",
+ "type": "string"
+ },
+ "trigger": {
+ "description": "An action to trigger potentially showing the message",
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A string identifying the trigger action"
+ },
+ "params": {
+ "type": "array",
+ "description": "An optional array of string parameters for the trigger action",
+ "items": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "string"
+ }
+ ]
+ }
+ }
+ },
+ "required": [
+ "id"
+ ]
+ },
+ "provider": {
+ "description": "An identifier for the provider of this message, such as \"cfr\" or \"preview\".",
+ "type": "string"
+ }
+ },
+ "additionalProperties": true,
+ "dependentRequired": {
+ "content": [
+ "id",
+ "template"
+ ],
+ "template": [
+ "id",
+ "content"
+ ]
+ }
+ },
+ "localizedText": {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "description": "Id of localized string to be rendered.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "string_id"
+ ]
+ },
+ "localizableText": {
+ "description": "Either a raw string or an object containing the string_id of the localized text",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The string to be rendered."
+ },
+ {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/localizedText"
+ }
+ ]
+ },
+ "TemplatedMessage": {
+ "description": "An FxMS message of one of a variety of types.",
+ "type": "object",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/Message"
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "toast_notification"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/ToastNotification"
+ }
+ }
+ ]
+ },
+ "MultiMessage": {
+ "description": "An object containing an array of messages.",
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "const": "multi"
+ },
+ "messages": {
+ "type": "array",
+ "description": "An array of messages.",
+ "items": {
+ "$ref": "resource://activity-stream/schemas/BackgroundTaskMessagingExperiment.schema.json#/$defs/TemplatedMessage"
+ }
+ }
+ },
+ "required": [
+ "template",
+ "messages"
+ ]
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/FxMSCommon.schema.json b/browser/components/newtab/content-src/asrouter/schemas/FxMSCommon.schema.json
new file mode 100644
index 0000000000..51dbd3efa6
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/FxMSCommon.schema.json
@@ -0,0 +1,128 @@
+{
+ "description": "Common elements used across FxMS schemas",
+ "$id": "file:///FxMSCommon.schema.json",
+ "$defs": {
+ "Message": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The message identifier"
+ },
+ "groups": {
+ "description": "Array of preferences used to control `enabled` status of the group. If any is `false` the group is disabled.",
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "Preference name"
+ }
+ },
+ "template": {
+ "type": "string",
+ "description": "Which messaging template this message is using."
+ },
+ "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": {
+ "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"]
+ }
+ }
+ }
+ },
+ "priority": {
+ "description": "The priority of the message. If there are two competing messages to show, the one with the highest priority will be shown",
+ "type": "integer"
+ },
+ "order": {
+ "description": "The order in which messages should be shown. Messages will be shown in increasing order.",
+ "type": "integer"
+ },
+ "targeting": {
+ "description": "A JEXL expression representing targeting information",
+ "type": "string"
+ },
+ "trigger": {
+ "description": "An action to trigger potentially showing the message",
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A string identifying the trigger action"
+ },
+ "params": {
+ "type": "array",
+ "description": "An optional array of string parameters for the trigger action",
+ "items": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "string"
+ }
+ ]
+ }
+ }
+ },
+ "required": ["id"]
+ },
+ "provider": {
+ "description": "An identifier for the provider of this message, such as \"cfr\" or \"preview\".",
+ "type": "string"
+ }
+ },
+ "additionalProperties": true,
+ "dependentRequired": {
+ "content": ["id", "template"],
+ "template": ["id", "content"]
+ }
+ },
+ "localizedText": {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "description": "Id of localized string to be rendered.",
+ "type": "string"
+ }
+ },
+ "required": ["string_id"]
+ },
+ "localizableText": {
+ "description": "Either a raw string or an object containing the string_id of the localized text",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The string to be rendered."
+ },
+ {
+ "$ref": "#/$defs/localizedText"
+ }
+ ]
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/MessagingExperiment.schema.json b/browser/components/newtab/content-src/asrouter/schemas/MessagingExperiment.schema.json
new file mode 100644
index 0000000000..abd36cf6cf
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/MessagingExperiment.schema.json
@@ -0,0 +1,1640 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "resource://activity-stream/schemas/MessagingExperiment.schema.json",
+ "title": "Messaging Experiment",
+ "description": "A Firefox Messaging System message.",
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "const": "multi"
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/MultiMessage"
+ },
+ "else": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/TemplatedMessage"
+ },
+ "$defs": {
+ "CFRUrlbarChiclet": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///CFRUrlbarChiclet.schema.json",
+ "title": "CFRUrlbarChiclet",
+ "description": "A template with a chiclet button with text.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "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.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "where": {
+ "description": "Should it open in a new tab or the current tab",
+ "type": "string",
+ "enum": [
+ "current",
+ "tabshifted"
+ ]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "url",
+ "where"
+ ]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "layout",
+ "category",
+ "bucket_id",
+ "notification_text",
+ "action"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "cfr_urlbar_chiclet"
+ }
+ },
+ "required": [
+ "targeting",
+ "trigger"
+ ]
+ },
+ "ExtensionDoorhanger": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ExtensionDoorhanger.schema.json",
+ "title": "ExtensionDoorhanger",
+ "description": "A template with a heading, addon icon, title and description. No markup allowed.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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",
+ "icon_and_message",
+ "addon_recommendation"
+ ]
+ },
+ "anchor_id": {
+ "type": "string",
+ "description": "A DOM element ID that the pop-over will be anchored."
+ },
+ "alt_anchor_id": {
+ "type": "string",
+ "description": "An alternate 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."
+ },
+ "show_in_private_browsing": {
+ "type": "boolean",
+ "description": "Whether to allow the message to be shown in private browsing mode. Defaults to false."
+ },
+ "notification_text": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Text for button tooltip used to provide information about the doorhanger."
+ }
+ },
+ "required": [
+ "tooltiptext"
+ ]
+ }
+ },
+ "required": [
+ "attributes"
+ ]
+ },
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizedText"
+ }
+ ]
+ },
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "icon": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/linkUrl",
+ "description": "The icon displayed in the pop-over. Should be 32x32px or 64x64px and png/svg."
+ },
+ "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": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/plainText",
+ "description": "Unique addon ID"
+ },
+ "title": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/plainText",
+ "description": "Addon name"
+ },
+ "author": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/plainText",
+ "description": "Addon author"
+ },
+ "icon": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/linkUrl",
+ "description": "The icon displayed in the pop-over. Should be 64x64px and png/svg."
+ },
+ "rating": {
+ "type": "string",
+ "description": "Star rating"
+ },
+ "users": {
+ "type": "string",
+ "description": "Installed users"
+ },
+ "amo_url": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/linkUrl",
+ "description": "Link that offers more information related to the addon."
+ }
+ },
+ "required": [
+ "title",
+ "author",
+ "icon",
+ "amo_url"
+ ]
+ },
+ "text": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "descriptionDetails": {
+ "description": "Additional information and steps on how to use",
+ "type": "object",
+ "properties": {
+ "steps": {
+ "description": "Array of string_ids",
+ "type": "array",
+ "items": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizedText",
+ "description": "Id of string to localized addon description"
+ }
+ }
+ },
+ "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": {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/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"
+ ]
+ },
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizedText"
+ }
+ ],
+ "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": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "object",
+ "oneOf": [
+ {
+ "properties": {
+ "value": {
+ "allOf": [
+ {
+ "$ref": "file:///ExtensionDoorhanger.schema.json#/$defs/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": "file:///ExtensionDoorhanger.schema.json#/$defs/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": "file:///ExtensionDoorhanger.schema.json#/$defs/linkUrl"
+ },
+ {
+ "description": "URL used in combination with the primary action dispatched."
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "layout",
+ "bucket_id",
+ "heading_text",
+ "text",
+ "buttons"
+ ],
+ "if": {
+ "properties": {
+ "skip_address_bar_notifier": {
+ "anyOf": [
+ {
+ "const": "false"
+ },
+ {
+ "const": null
+ }
+ ]
+ }
+ }
+ },
+ "then": {
+ "required": [
+ "category",
+ "notification_text"
+ ]
+ }
+ },
+ "template": {
+ "type": "string",
+ "enum": [
+ "cfr_doorhanger",
+ "milestone_message"
+ ]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "targeting",
+ "trigger"
+ ],
+ "$defs": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ }
+ },
+ "InfoBar": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///InfoBar.schema.json",
+ "title": "InfoBar",
+ "description": "A template with an image, test and buttons.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "The text show in the notification box."
+ },
+ "priority": {
+ "description": "Infobar priority level https://searchfox.org/mozilla-central/rev/3aef835f6cb12e607154d56d68726767172571e4/toolkit/content/widgets/notificationbox.js#387",
+ "type": "number",
+ "minumum": 0,
+ "exclusiveMaximum": 10
+ },
+ "buttons": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "The text label of the button."
+ },
+ "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": true
+ },
+ "supportPage": {
+ "type": "string",
+ "description": "A page title on SUMO to link to"
+ }
+ },
+ "required": [
+ "label",
+ "action"
+ ],
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "text",
+ "buttons"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "infobar"
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "targeting",
+ "trigger"
+ ],
+ "$defs": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ }
+ },
+ "NewtabPromoMessage": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///NewtabPromoMessage.schema.json",
+ "title": "PBNewtabPromoMessage",
+ "description": "Message shown on the private browsing newtab page.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "hideDefault": {
+ "type": "boolean",
+ "description": "Should we hide the default promo after the experiment promo is dismissed."
+ },
+ "infoEnabled": {
+ "type": "boolean",
+ "description": "Should we show the info section."
+ },
+ "infoIcon": {
+ "type": "string",
+ "description": "Icon shown in the left side of the info section. Default is the private browsing icon."
+ },
+ "infoTitle": {
+ "type": "string",
+ "description": "Is the title in the info section enabled."
+ },
+ "infoTitleEnabled": {
+ "type": "boolean",
+ "description": "Is the title in the info section enabled."
+ },
+ "infoBody": {
+ "type": "string",
+ "description": "Text content in the info section."
+ },
+ "infoLinkText": {
+ "type": "string",
+ "description": "Text for the link in the info section."
+ },
+ "infoLinkUrl": {
+ "type": "string",
+ "description": "URL for the info section link.",
+ "format": "moz-url-format"
+ },
+ "promoEnabled": {
+ "type": "boolean",
+ "description": "Should we show the promo section."
+ },
+ "promoType": {
+ "type": "string",
+ "description": "Promo type used to determine if promo should show to a given user",
+ "enum": [
+ "FOCUS",
+ "VPN",
+ "PIN",
+ "COOKIE_BANNERS",
+ "OTHER"
+ ]
+ },
+ "promoSectionStyle": {
+ "type": "string",
+ "description": "Sets the position of the promo section. Possible values are: top, below-search, bottom. Default bottom.",
+ "enum": [
+ "top",
+ "below-search",
+ "bottom"
+ ]
+ },
+ "promoTitle": {
+ "type": "string",
+ "description": "The text content of the promo section."
+ },
+ "promoTitleEnabled": {
+ "type": "boolean",
+ "description": "Should we show text content in the promo section."
+ },
+ "promoLinkText": {
+ "type": "string",
+ "description": "The text of the link in the promo box."
+ },
+ "promoHeader": {
+ "type": "string",
+ "description": "The title of the promo section."
+ },
+ "promoButton": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "type": "object"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "additionalProperties": true
+ }
+ },
+ "required": [
+ "action"
+ ]
+ },
+ "promoLinkType": {
+ "type": "string",
+ "description": "Type of promo link type. Possible values: link, button. Default is link.",
+ "enum": [
+ "link",
+ "button"
+ ]
+ },
+ "promoImageLarge": {
+ "type": "string",
+ "description": "URL for image used on the left side of the promo box, larger, showcases some feature. Default off.",
+ "format": "uri"
+ },
+ "promoImageSmall": {
+ "type": "string",
+ "description": "URL for image used on the right side of the promo box, smaller, usually a logo. Default off.",
+ "format": "uri"
+ }
+ },
+ "additionalProperties": true,
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "promoEnabled": {
+ "const": true
+ }
+ },
+ "required": [
+ "promoEnabled"
+ ]
+ },
+ "then": {
+ "required": [
+ "promoButton"
+ ]
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "infoEnabled": {
+ "const": true
+ }
+ },
+ "required": [
+ "infoEnabled"
+ ]
+ },
+ "then": {
+ "required": [
+ "infoLinkText"
+ ],
+ "if": {
+ "properties": {
+ "infoTitleEnabled": {
+ "const": true
+ }
+ },
+ "required": [
+ "infoTitleEnabled"
+ ]
+ },
+ "then": {
+ "required": [
+ "infoTitle"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "pb_newtab"
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "targeting"
+ ]
+ },
+ "ProtectionsPanelMessage": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ProtectionsPanelMessage.schema.json",
+ "title": "ProtectionsPanelMessage",
+ "description": "A message shown in the protections panel.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "description": "The message title.",
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText"
+ },
+ "body": {
+ "description": "The body of the message.",
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText"
+ },
+ "link_text": {
+ "description": "The text of the call to action link.",
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText"
+ },
+ "cta_type": {
+ "description": "The type of URL open action.",
+ "type": "string",
+ "enum": [
+ "OPEN_URL",
+ "OPEN_PROTECTION_REPORT",
+ "OPEN_ABOUT_PAGE"
+ ]
+ },
+ "cta_url": {
+ "description": "The URL to open when the call to action is clicked",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "cta_where": {
+ "description": "How to open the cta.",
+ "type": "string",
+ "enum": [
+ "current",
+ "tabshifted",
+ "tab",
+ "save",
+ "window"
+ ]
+ }
+ },
+ "dependantSchemas": {
+ "link_text": [
+ "cta_type",
+ "cta_url"
+ ],
+ "cta_type": [
+ "link_text"
+ ],
+ "cta_url": [
+ "link_text"
+ ],
+ "cta_where": [
+ "link_text"
+ ]
+ },
+ "additionalProperties": false,
+ "required": [
+ "title",
+ "body"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "protections_panel"
+ },
+ "trigger": {
+ "description": "An action to trigger potentially showing the message. The action ID `protectionsPanelOpen` is required.",
+ "const": {
+ "id": "protectionsPanelOpen"
+ }
+ }
+ },
+ "required": [
+ "content",
+ "template",
+ "trigger"
+ ],
+ "additionalProperties": true
+ },
+ "Spotlight": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///Spotlight.schema.json",
+ "title": "Spotlight",
+ "description": "A template with an image, title, content and two buttons.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "description": "Specify the layout template for the Spotlight",
+ "const": "multistage"
+ },
+ "backdrop": {
+ "type": "string",
+ "description": "Background css behind modal content"
+ },
+ "logo": {
+ "type": "object",
+ "properties": {
+ "imageURL": {
+ "type": "string",
+ "description": "URL for image to use with the content"
+ },
+ "imageId": {
+ "type": "string",
+ "description": "The ID for a remotely hosted image"
+ },
+ "size": {
+ "type": "string",
+ "description": "The logo size."
+ }
+ },
+ "additionalProperties": true
+ },
+ "screens": {
+ "type": "array",
+ "description": "Collection of individual screen content"
+ },
+ "transitions": {
+ "type": "boolean",
+ "description": "Show transitions within and between screens"
+ },
+ "disableHistoryUpdates": {
+ "type": "boolean",
+ "description": "Don't alter the browser session's history stack - used with messaging surfaces like Feature Callouts"
+ },
+ "startScreen": {
+ "type": "integer",
+ "description": "Index of first screen to show from message, defaulting to 0"
+ }
+ },
+ "additionalProperties": true
+ },
+ "template": {
+ "type": "string",
+ "description": "Specify whether the surface is shown as a Spotlight modal or an in-surface Feature Callout dialog",
+ "enum": [
+ "spotlight",
+ "feature_callout"
+ ]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "targeting"
+ ]
+ },
+ "ToastNotification": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ToastNotification.schema.json",
+ "title": "ToastNotification",
+ "description": "A template for toast notifications displayed by the Alert service.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification title"
+ },
+ "body": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification body"
+ },
+ "icon_url": {
+ "description": "The URL of the image used as an icon of the toast notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "image_url": {
+ "description": "The URL of an image to be displayed as part of the notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "launch_url": {
+ "description": "The URL to launch when the notification or an action button is clicked.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "requireInteraction": {
+ "type": "boolean",
+ "description": "Whether the toast notification should remain active until the user clicks or dismisses it, rather than closing automatically."
+ },
+ "tag": {
+ "type": "string",
+ "description": "An identifying tag for the toast notification."
+ },
+ "data": {
+ "type": "object",
+ "description": "Arbitrary data associated with the toast notification."
+ },
+ "actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "The action text to be shown to the user."
+ },
+ "action": {
+ "type": "string",
+ "description": "Opaque identifer that identifies action."
+ },
+ "iconURL": {
+ "type": "string",
+ "format": "uri",
+ "description": "URL of an icon to display with the action."
+ },
+ "windowsSystemActivationType": {
+ "type": "boolean",
+ "description": "Whether to have Windows process the given `action`."
+ }
+ },
+ "required": [
+ "action",
+ "title"
+ ],
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "title",
+ "body"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "toast_notification"
+ }
+ },
+ "required": [
+ "content",
+ "targeting",
+ "template",
+ "trigger"
+ ],
+ "additionalProperties": true
+ },
+ "ToolbarBadgeMessage": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ToolbarBadgeMessage.schema.json",
+ "title": "ToolbarBadgeMessage",
+ "description": "A template that specifies to which element in the browser toolbar to add a notification.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "target": {
+ "type": "string"
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true,
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizedText",
+ "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'"
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "target"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "toolbar_badge"
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "targeting"
+ ]
+ },
+ "UpdateAction": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///UpdateAction.schema.json",
+ "title": "UpdateActionMessage",
+ "description": "A template for messages that execute predetermined actions.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "data": {
+ "type": "object",
+ "description": "Additional data provided as argument when executing the action",
+ "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"
+ }
+ }
+ }
+ },
+ "additionalProperties": true,
+ "description": "Optional action to take in addition to showing the notification",
+ "required": [
+ "id",
+ "data"
+ ]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "action"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "update_action"
+ }
+ },
+ "required": [
+ "targeting"
+ ]
+ },
+ "WhatsNewMessage": {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///WhatsNewMessage.schema.json",
+ "title": "WhatsNewMessage",
+ "description": "A template for the messages that appear in the What's New panel.",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ }
+ ],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "layout": {
+ "description": "Different message layouts",
+ "enum": [
+ "tracking-protections"
+ ]
+ },
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message title"
+ },
+ "subtitle": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message subtitle"
+ },
+ "body": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message body"
+ },
+ "link_text": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/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": "moz-url-format"
+ },
+ "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": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizableText",
+ "description": "Alt text for image."
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "published_date",
+ "title",
+ "body",
+ "cta_url",
+ "bucket_id"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "whatsnew_panel_message"
+ }
+ },
+ "required": [
+ "order"
+ ],
+ "additionalProperties": true
+ },
+ "Message": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The message identifier"
+ },
+ "groups": {
+ "description": "Array of preferences used to control `enabled` status of the group. If any is `false` the group is disabled.",
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "Preference name"
+ }
+ },
+ "template": {
+ "type": "string",
+ "description": "Which messaging template this message is using.",
+ "enum": [
+ "cfr_urlbar_chiclet",
+ "cfr_doorhanger",
+ "milestone_message",
+ "infobar",
+ "pb_newtab",
+ "protections_panel",
+ "spotlight",
+ "feature_callout",
+ "toast_notification",
+ "toolbar_badge",
+ "update_action",
+ "whatsnew_panel_message"
+ ]
+ },
+ "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": {
+ "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"
+ ]
+ }
+ }
+ }
+ },
+ "priority": {
+ "description": "The priority of the message. If there are two competing messages to show, the one with the highest priority will be shown",
+ "type": "integer"
+ },
+ "order": {
+ "description": "The order in which messages should be shown. Messages will be shown in increasing order.",
+ "type": "integer"
+ },
+ "targeting": {
+ "description": "A JEXL expression representing targeting information",
+ "type": "string"
+ },
+ "trigger": {
+ "description": "An action to trigger potentially showing the message",
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A string identifying the trigger action"
+ },
+ "params": {
+ "type": "array",
+ "description": "An optional array of string parameters for the trigger action",
+ "items": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "string"
+ }
+ ]
+ }
+ }
+ },
+ "required": [
+ "id"
+ ]
+ },
+ "provider": {
+ "description": "An identifier for the provider of this message, such as \"cfr\" or \"preview\".",
+ "type": "string"
+ }
+ },
+ "additionalProperties": true,
+ "dependentRequired": {
+ "content": [
+ "id",
+ "template"
+ ],
+ "template": [
+ "id",
+ "content"
+ ]
+ }
+ },
+ "localizedText": {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "description": "Id of localized string to be rendered.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "string_id"
+ ]
+ },
+ "localizableText": {
+ "description": "Either a raw string or an object containing the string_id of the localized text",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The string to be rendered."
+ },
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/localizedText"
+ }
+ ]
+ },
+ "TemplatedMessage": {
+ "description": "An FxMS message of one of a variety of types.",
+ "type": "object",
+ "allOf": [
+ {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Message"
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "cfr_urlbar_chiclet"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/CFRUrlbarChiclet"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "cfr_doorhanger",
+ "milestone_message"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/ExtensionDoorhanger"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "infobar"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/InfoBar"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "pb_newtab"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/NewtabPromoMessage"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "protections_panel"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/ProtectionsPanelMessage"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "spotlight",
+ "feature_callout"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/Spotlight"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "toast_notification"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/ToastNotification"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "toolbar_badge"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/ToolbarBadgeMessage"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "update_action"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/UpdateAction"
+ }
+ },
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": [
+ "whatsnew_panel_message"
+ ]
+ }
+ },
+ "required": [
+ "template"
+ ]
+ },
+ "then": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/WhatsNewMessage"
+ }
+ }
+ ]
+ },
+ "MultiMessage": {
+ "description": "An object containing an array of messages.",
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "const": "multi"
+ },
+ "messages": {
+ "type": "array",
+ "description": "An array of messages.",
+ "items": {
+ "$ref": "resource://activity-stream/schemas/MessagingExperiment.schema.json#/$defs/TemplatedMessage"
+ }
+ }
+ },
+ "required": [
+ "template",
+ "messages"
+ ]
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/corpus/ReachExperiments.messages.json b/browser/components/newtab/content-src/asrouter/schemas/corpus/ReachExperiments.messages.json
new file mode 100644
index 0000000000..1ccfefe478
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/corpus/ReachExperiments.messages.json
@@ -0,0 +1,15 @@
+[
+ {
+ "trigger": {
+ "id": "defaultBrowserCheck"
+ },
+ "targeting": "source == 'startup' && !isMajorUpgrade && !activeNotifications && totalBookmarksCount == 5"
+ },
+ {
+ "groups": ["eco"],
+ "trigger": {
+ "id": "defaultBrowserCheck"
+ },
+ "targeting": "source == 'startup' && !isMajorUpgrade && !activeNotifications && totalBookmarksCount == 5"
+ }
+]
diff --git a/browser/components/newtab/content-src/asrouter/schemas/extract-test-corpus.js b/browser/components/newtab/content-src/asrouter/schemas/extract-test-corpus.js
new file mode 100644
index 0000000000..f8d3f5ac81
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/extract-test-corpus.js
@@ -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";
+
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+
+const CWD = Services.dirsvc.get("CurWorkD", Ci.nsIFile).path;
+const CORPUS_DIR = PathUtils.join(CWD, "corpus");
+
+const CORPUS = [
+ {
+ name: "CFRMessageProvider.messages.json",
+ provider: CFRMessageProvider,
+ },
+ {
+ name: "OnboardingMessageProvider.messages.json",
+ provider: OnboardingMessageProvider,
+ },
+ {
+ name: "PanelTestProvider.messages.json",
+ provider: PanelTestProvider,
+ },
+ {
+ name: "PanelTestProvider_toast_notification.messages.json",
+ provider: PanelTestProvider,
+ filter: message => message.template === "toast_notification",
+ },
+];
+
+let exit = false;
+async function main() {
+ try {
+ await IOUtils.makeDirectory(CORPUS_DIR);
+
+ for (const entry of CORPUS) {
+ const { name, provider } = entry;
+ const filter = entry.filter ?? (() => true);
+ const messages = await provider.getMessages();
+ const json = `${JSON.stringify(messages.filter(filter), undefined, 2)}\n`;
+
+ const path = PathUtils.join(CORPUS_DIR, name);
+ await IOUtils.writeUTF8(path, json);
+ }
+ } finally {
+ exit = true;
+ }
+}
+
+main();
+
+// We need to spin the event loop here, otherwise everything goes out of scope.
+Services.tm.spinEventLoopUntil(
+ "extract-test-corpus.js: waiting for completion",
+ () => exit
+);
diff --git a/browser/components/newtab/content-src/asrouter/schemas/make-schemas.py b/browser/components/newtab/content-src/asrouter/schemas/make-schemas.py
new file mode 100755
index 0000000000..7fbf815aa0
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/make-schemas.py
@@ -0,0 +1,475 @@
+#!/usr/bin/env python3
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+"""Firefox Messaging System Messaging Experiment schema generator
+
+The Firefox Messaging System handles several types of messages. This program
+patches and combines those schemas into a single schema
+(MessagingExperiment.schema.json) which is used to validate messaging
+experiments coming from Nimbus.
+
+Definitions from FxMsCommon.schema.json are bundled into this schema. This
+allows all of the FxMS schemas to reference common definitions, e.g.
+`localizableText` for translatable strings, via referencing the common schema.
+The bundled schema will be re-written so that the references now point at the
+top-level, generated schema.
+
+Additionally, all self-references in each messaging schema will be rewritten
+into absolute references, referencing each sub-schemas `$id`. This is requried
+due to the JSONSchema validation library used by Experimenter not fully
+supporting self-references and bundled schema.
+"""
+
+import json
+import sys
+from argparse import ArgumentParser
+from itertools import chain
+from pathlib import Path
+from typing import Any, Dict, List, NamedTuple, Union
+from urllib.parse import urlparse
+
+import jsonschema
+
+
+class SchemaDefinition(NamedTuple):
+ """A definition of a schema that is to be bundled."""
+
+ #: The $id of the generated schema.
+ schema_id: str
+
+ #: The path of the generated schema.
+ schema_path: Path
+
+ #: The message types that will be bundled into the schema.
+ message_types: Dict[str, Path]
+
+ #: What common definitions to bundle into the schema.
+ #:
+ #: If `True`, all definitions will be bundled.
+ #: If `False`, no definitons will be bundled.
+ #: If a list, only the named definitions will be bundled.
+ bundle_common: Union[bool, List[str]]
+
+ #: The testing corpus for the schema.
+ test_corpus: Dict[str, Path]
+
+
+SCHEMA_DIR = Path("..", "templates")
+
+SCHEMAS = [
+ SchemaDefinition(
+ schema_id="resource://activity-stream/schemas/MessagingExperiment.schema.json",
+ schema_path=Path("MessagingExperiment.schema.json"),
+ message_types={
+ "CFRUrlbarChiclet": (
+ SCHEMA_DIR / "CFR" / "templates" / "CFRUrlbarChiclet.schema.json"
+ ),
+ "ExtensionDoorhanger": (
+ SCHEMA_DIR / "CFR" / "templates" / "ExtensionDoorhanger.schema.json"
+ ),
+ "InfoBar": SCHEMA_DIR / "CFR" / "templates" / "InfoBar.schema.json",
+ "NewtabPromoMessage": (
+ SCHEMA_DIR / "PBNewtab" / "NewtabPromoMessage.schema.json"
+ ),
+ "ProtectionsPanelMessage": (
+ SCHEMA_DIR / "OnboardingMessage" / "ProtectionsPanelMessage.schema.json"
+ ),
+ "Spotlight": SCHEMA_DIR / "OnboardingMessage" / "Spotlight.schema.json",
+ "ToastNotification": (
+ SCHEMA_DIR / "ToastNotification" / "ToastNotification.schema.json"
+ ),
+ "ToolbarBadgeMessage": (
+ SCHEMA_DIR / "OnboardingMessage" / "ToolbarBadgeMessage.schema.json"
+ ),
+ "UpdateAction": (
+ SCHEMA_DIR / "OnboardingMessage" / "UpdateAction.schema.json"
+ ),
+ "WhatsNewMessage": (
+ SCHEMA_DIR / "OnboardingMessage" / "WhatsNewMessage.schema.json"
+ ),
+ },
+ bundle_common=True,
+ test_corpus={
+ "ReachExperiments": Path("corpus", "ReachExperiments.messages.json"),
+ # These are generated via extract-test-corpus.js
+ "CFRMessageProvider": Path("corpus", "CFRMessageProvider.messages.json"),
+ "OnboardingMessageProvider": Path(
+ "corpus", "OnboardingMessageProvider.messages.json"
+ ),
+ "PanelTestProvider": Path("corpus", "PanelTestProvider.messages.json"),
+ },
+ ),
+ SchemaDefinition(
+ schema_id=(
+ "resource://activity-stream/schemas/"
+ "BackgroundTaskMessagingExperiment.schema.json"
+ ),
+ schema_path=Path("BackgroundTaskMessagingExperiment.schema.json"),
+ message_types={
+ "ToastNotification": (
+ SCHEMA_DIR / "ToastNotification" / "ToastNotification.schema.json"
+ ),
+ },
+ bundle_common=True,
+ # These are generated via extract-test-corpus.js
+ test_corpus={
+ # Just the "toast_notification" messages.
+ "PanelTestProvider": Path(
+ "corpus", "PanelTestProvider_toast_notification.messages.json"
+ ),
+ },
+ ),
+]
+
+COMMON_SCHEMA_NAME = "FxMSCommon.schema.json"
+COMMON_SCHEMA_PATH = Path(COMMON_SCHEMA_NAME)
+
+
+class NestedRefResolver(jsonschema.RefResolver):
+ """A custom ref resolver that handles bundled schema.
+
+ This is the resolver used by Experimenter.
+ """
+
+ def __init__(self, schema):
+ super().__init__(base_uri=None, referrer=None)
+
+ if "$id" in schema:
+ self.store[schema["$id"]] = schema
+
+ if "$defs" in schema:
+ for dfn in schema["$defs"].values():
+ if "$id" in dfn:
+ self.store[dfn["$id"]] = dfn
+
+
+def read_schema(path):
+ """Read a schema from disk and parse it as JSON."""
+ with path.open("r") as f:
+ return json.load(f)
+
+
+def extract_template_values(template):
+ """Extract the possible template values (either via JSON Schema enum or const)."""
+ enum = template.get("enum")
+ if enum:
+ return enum
+
+ const = template.get("const")
+ if const:
+ return [const]
+
+
+def patch_schema(schema, bundled_id, schema_id=None):
+ """Patch the given schema.
+
+ The JSON schema validator that Experimenter uses
+ (https://pypi.org/project/jsonschema/) does not support relative references,
+ nor does it support bundled schemas. We rewrite the schema so that all
+ relative refs are transformed into absolute refs via the schema's `$id`.
+
+ Additionally, we merge in the contents of FxMSCommon.schema.json, so all
+ refs relative to that schema will be transformed to become relative to this
+ schema.
+
+ See-also: https://github.com/python-jsonschema/jsonschema/issues/313
+ """
+ if schema_id is None:
+ schema_id = schema["$id"]
+
+ def patch_impl(schema):
+ ref = schema.get("$ref")
+
+ if ref:
+ uri = urlparse(ref)
+ if (
+ uri.scheme == ""
+ and uri.netloc == ""
+ and uri.path == ""
+ and uri.fragment != ""
+ ):
+ schema["$ref"] = f"{schema_id}#{uri.fragment}"
+ elif (uri.scheme, uri.path) == ("file", f"/{COMMON_SCHEMA_NAME}"):
+ schema["$ref"] = f"{bundled_id}#{uri.fragment}"
+
+ # If `schema` is object-like, inspect each of its indivual properties
+ # and patch them.
+ properties = schema.get("properties")
+ if properties:
+ for prop in properties.keys():
+ patch_impl(properties[prop])
+
+ # If `schema` is array-like, inspect each of its items and patch them.
+ items = schema.get("items")
+ if items:
+ patch_impl(items)
+
+ # Patch each `if`, `then`, `else`, and `not` sub-schema that is present.
+ for key in ("if", "then", "else", "not"):
+ if key in schema:
+ patch_impl(schema[key])
+
+ # Patch the items of each `oneOf`, `allOf`, and `anyOf` sub-schema that
+ # is present.
+ for key in ("oneOf", "allOf", "anyOf"):
+ subschema = schema.get(key)
+ if subschema:
+ for i, alternate in enumerate(subschema):
+ patch_impl(alternate)
+
+ # Patch the top-level type defined in the schema.
+ patch_impl(schema)
+
+ # Patch each named definition in the schema.
+ for key in ("$defs", "definitions"):
+ defns = schema.get(key)
+ if defns:
+ for defn_name, defn_value in defns.items():
+ patch_impl(defn_value)
+
+ return schema
+
+
+def bundle_schema(schema_def: SchemaDefinition):
+ """Create a bundled schema based on the schema definition."""
+ # Patch each message type schema to resolve all self-references to be
+ # absolute and rewrite # references to FxMSCommon.schema.json to be relative
+ # to the new schema (because we are about to bundle its definitions).
+ defs = {
+ name: patch_schema(read_schema(path), bundled_id=schema_def.schema_id)
+ for name, path in schema_def.message_types.items()
+ }
+
+ # Bundle the definitions from FxMSCommon.schema.json into this schema.
+ if schema_def.bundle_common:
+
+ def dfn_filter(name):
+ if schema_def.bundle_common is True:
+ return True
+
+ return name in schema_def.bundle_common
+
+ common_schema = patch_schema(
+ read_schema(COMMON_SCHEMA_PATH),
+ bundled_id=schema_def.schema_id,
+ schema_id=schema_def.schema_id,
+ )
+
+ # patch_schema mutates the given schema, so we read a new copy in for
+ # each bundle operation.
+ defs.update(
+ {
+ name: dfn
+ for name, dfn in common_schema["$defs"].items()
+ if dfn_filter(name)
+ }
+ )
+
+ # Ensure all bundled schemas have an $id so that $refs inside the
+ # bundled schema work correctly (i.e, they will reference the subschema
+ # and not the bundle).
+ for name in schema_def.message_types.keys():
+ subschema = defs[name]
+ if "$id" not in subschema:
+ raise ValueError(f"Schema {name} is missing an $id")
+
+ props = subschema["properties"]
+ if "template" not in props:
+ raise ValueError(f"Schema {name} is missing a template")
+
+ template = props["template"]
+ if "enum" not in template and "const" not in template:
+ raise ValueError(f"Schema {name} should have const or enum template")
+
+ templates = {
+ name: extract_template_values(defs[name]["properties"]["template"])
+ for name in schema_def.message_types.keys()
+ }
+
+ # Ensure that each schema has a unique set of template values.
+ for a in templates.keys():
+ a_keys = set(templates[a])
+
+ for b in templates.keys():
+ if a == b:
+ continue
+
+ b_keys = set(templates[b])
+ intersection = a_keys.intersection(b_keys)
+
+ if len(intersection):
+ raise ValueError(
+ f"Schema {a} and {b} have overlapping template values: "
+ f"{', '.join(intersection)}"
+ )
+
+ all_templates = list(chain.from_iterable(templates.values()))
+
+ # Enforce that one of the templates must match (so that one of the if
+ # branches will match).
+ defs["Message"]["properties"]["template"]["enum"] = all_templates
+ defs["TemplatedMessage"] = {
+ "description": "An FxMS message of one of a variety of types.",
+ "type": "object",
+ "allOf": [
+ # Ensure each message has all the fields defined in the base
+ # Message type.
+ #
+ # This is slightly redundant because each message should
+ # already inherit from this message type, but it is easier
+ # to add this requirement here than to verify that each
+ # message's schema is properly inheriting.
+ {"$ref": f"{schema_def.schema_id}#/$defs/Message"},
+ # For each message type, create a subschema that says if the
+ # template field matches a value for a message type defined
+ # in MESSAGE_TYPES, then the message must also match the
+ # schema for that message type.
+ #
+ # This is done using `allOf: [{ if, then }]` instead of `oneOf: []`
+ # because it provides better error messages. Using `if-then`
+ # will only show validation errors for the sub-schema that
+ # matches template, whereas using `oneOf` will show
+ # validation errors for *all* sub-schemas, which makes
+ # debugging messages much harder.
+ *(
+ {
+ "if": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "enum": templates[message_type],
+ },
+ },
+ "required": ["template"],
+ },
+ "then": {"$ref": f"{schema_def.schema_id}#/$defs/{message_type}"},
+ }
+ for message_type in schema_def.message_types
+ ),
+ ],
+ }
+ defs["MultiMessage"] = {
+ "description": "An object containing an array of messages.",
+ "type": "object",
+ "properties": {
+ "template": {"type": "string", "const": "multi"},
+ "messages": {
+ "type": "array",
+ "description": "An array of messages.",
+ "items": {"$ref": f"{schema_def.schema_id}#/$defs/TemplatedMessage"},
+ },
+ },
+ "required": ["template", "messages"],
+ }
+
+ # Generate the combined schema.
+ return {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": schema_def.schema_id,
+ "title": "Messaging Experiment",
+ "description": "A Firefox Messaging System message.",
+ # A message must be one of:
+ # - An object that contains id, template, and content fields
+ # - An object that contains none of the above fields (empty message)
+ # - An array of messages like the above
+ "if": {
+ "type": "object",
+ "properties": {"template": {"const": "multi"}},
+ "required": ["template"],
+ },
+ "then": {
+ "$ref": f"{schema_def.schema_id}#/$defs/MultiMessage",
+ },
+ "else": {
+ "$ref": f"{schema_def.schema_id}#/$defs/TemplatedMessage",
+ },
+ "$defs": defs,
+ }
+
+
+def check_diff(schema_def: SchemaDefinition, schema: Dict[str, Any]):
+ """Check the generated schema matches the on-disk schema."""
+ print(f" Checking {schema_def.schema_path} for differences...")
+
+ with schema_def.schema_path.open("r") as f:
+ on_disk = json.load(f)
+
+ if on_disk != schema:
+ print(f"{schema_def.schema_path} does not match generated schema:")
+ print("Generated schema:")
+ json.dump(schema, sys.stdout, indent=2)
+ print("\n\nOn Disk schema:")
+ json.dump(on_disk, sys.stdout, indent=2)
+ print("\n\n")
+
+ raise ValueError("Schemas do not match!")
+
+
+def validate_corpus(schema_def: SchemaDefinition, schema: Dict[str, Any]):
+ """Check that the schema validates.
+
+ This uses the same validation configuration that is used in Experimenter.
+ """
+ print(" Validating messages with Experimenter JSON Schema validator...")
+
+ resolver = NestedRefResolver(schema)
+
+ for provider, provider_path in schema_def.test_corpus.items():
+ print(f" Validating messages from {provider}:")
+
+ try:
+ with provider_path.open("r") as f:
+ messages = json.load(f)
+ except FileNotFoundError as e:
+ if not provider_path.parent.exists():
+ new_exc = Exception(
+ f"Could not find {provider_path}: Did you run "
+ "`mach xpcshell extract-test-corpus.js` ?"
+ )
+ raise new_exc from e
+
+ raise e
+
+ for i, message in enumerate(messages):
+ template = message.get("template", "(no template)")
+ msg_id = message.get("id", f"index {i}")
+
+ print(
+ f" Validating {msg_id} {template} message with {schema_def.schema_path}..."
+ )
+ jsonschema.validate(instance=message, schema=schema, resolver=resolver)
+
+ print()
+
+
+def main(check=False):
+ """Generate Nimbus feature schemas for Firefox Messaging System."""
+ for schema_def in SCHEMAS:
+ print(f"Generating {schema_def.schema_path} ...")
+ schema = bundle_schema(schema_def)
+
+ if check:
+ print(f"Checking {schema_def.schema_path} ...")
+ check_diff(schema_def, schema)
+ validate_corpus(schema_def, schema)
+ else:
+ with schema_def.schema_path.open("wb") as f:
+ print(f"Writing {schema_def.schema_path} ...")
+ f.write(json.dumps(schema, indent=2).encode("utf-8"))
+ f.write(b"\n")
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(description=main.__doc__)
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Check that the generated schemas have not changed and run validation tests.",
+ default=False,
+ )
+ args = parser.parse_args()
+
+ main(args.check)
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..421acf159a
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/message-group.schema.json
@@ -0,0 +1,64 @@
+{
+ "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": {
+ "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"]
+ }
+ }
+ }
+ },
+ "type": {
+ "type": "string",
+ "description": "Local auto-generated group or remote group configuration from RS.",
+ "enum": ["remote-settings", "local", "default"]
+ }
+ },
+ "required": ["id", "enabled", "type"],
+ "additionalProperties": true
+}
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..f0a92705be
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json
@@ -0,0 +1,67 @@
+{
+ "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"
+ },
+ "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..004234f45f
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/template-utils.js
@@ -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/. */
+
+export function safeURI(url) {
+ if (!url) {
+ return "";
+ }
+ const { protocol } = new URL(url);
+ const isAllowed = [
+ "http:",
+ "https:",
+ "data:",
+ "resource:",
+ "chrome:",
+ ].includes(protocol);
+ if (!isAllowed) {
+ // eslint-disable-next-line no-console
+ console.warn(`The protocol ${protocol} is not allowed for template URLs.`);
+ }
+ 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..ff5dff535a
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json
@@ -0,0 +1,66 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///CFRUrlbarChiclet.schema.json",
+ "title": "CFRUrlbarChiclet",
+ "description": "A template with a chiclet button with text.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "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.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "where": {
+ "description": "Should it open in a new tab or the current tab",
+ "type": "string",
+ "enum": ["current", "tabshifted"]
+ }
+ },
+ "additionalProperties": true,
+ "required": ["url", "where"]
+ }
+ },
+ "additionalProperties": true,
+ "required": [
+ "layout",
+ "category",
+ "bucket_id",
+ "notification_text",
+ "action"
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "cfr_urlbar_chiclet"
+ }
+ },
+ "required": ["targeting", "trigger"]
+}
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..1bb157b5fb
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json
@@ -0,0 +1,320 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ExtensionDoorhanger.schema.json",
+ "title": "ExtensionDoorhanger",
+ "description": "A template with a heading, addon icon, title and description. No markup allowed.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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", "icon_and_message", "addon_recommendation"]
+ },
+ "anchor_id": {
+ "type": "string",
+ "description": "A DOM element ID that the pop-over will be anchored."
+ },
+ "alt_anchor_id": {
+ "type": "string",
+ "description": "An alternate 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."
+ },
+ "show_in_private_browsing": {
+ "type": "boolean",
+ "description": "Whether to allow the message to be shown in private browsing mode. Defaults to false."
+ },
+ "notification_text": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Text for button tooltip used to provide information about the doorhanger."
+ }
+ },
+ "required": ["tooltiptext"]
+ }
+ },
+ "required": ["attributes"]
+ },
+ {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizedText"
+ }
+ ]
+ },
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "icon": {
+ "$ref": "#/$defs/linkUrl",
+ "description": "The icon displayed in the pop-over. Should be 32x32px or 64x64px and png/svg."
+ },
+ "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": {
+ "$ref": "#/$defs/plainText",
+ "description": "Unique addon ID"
+ },
+ "title": {
+ "$ref": "#/$defs/plainText",
+ "description": "Addon name"
+ },
+ "author": {
+ "$ref": "#/$defs/plainText",
+ "description": "Addon author"
+ },
+ "icon": {
+ "$ref": "#/$defs/linkUrl",
+ "description": "The icon displayed in the pop-over. Should be 64x64px and png/svg."
+ },
+ "rating": {
+ "type": "string",
+ "description": "Star rating"
+ },
+ "users": {
+ "type": "string",
+ "description": "Installed users"
+ },
+ "amo_url": {
+ "$ref": "#/$defs/linkUrl",
+ "description": "Link that offers more information related to the addon."
+ }
+ },
+ "required": ["title", "author", "icon", "amo_url"]
+ },
+ "text": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "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."
+ },
+ "descriptionDetails": {
+ "description": "Additional information and steps on how to use",
+ "type": "object",
+ "properties": {
+ "steps": {
+ "description": "Array of string_ids",
+ "type": "array",
+ "items": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizedText",
+ "description": "Id of string to localized addon description"
+ }
+ }
+ },
+ "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": {
+ "$ref": "#/$defs/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"]
+ },
+ {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizedText"
+ }
+ ],
+ "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": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "object",
+ "oneOf": [
+ {
+ "properties": {
+ "value": {
+ "allOf": [
+ { "$ref": "#/$defs/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": "#/$defs/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": "#/$defs/linkUrl" },
+ {
+ "description": "URL used in combination with the primary action dispatched."
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": ["layout", "bucket_id", "heading_text", "text", "buttons"],
+ "if": {
+ "properties": {
+ "skip_address_bar_notifier": {
+ "anyOf": [{ "const": "false" }, { "const": null }]
+ }
+ }
+ },
+ "then": {
+ "required": ["category", "notification_text"]
+ }
+ },
+ "template": {
+ "type": "string",
+ "enum": ["cfr_doorhanger", "milestone_message"]
+ }
+ },
+ "additionalProperties": true,
+ "required": ["targeting", "trigger"],
+ "$defs": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ }
+}
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..ca0c0745bb
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json
@@ -0,0 +1,89 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///InfoBar.schema.json",
+ "title": "InfoBar",
+ "description": "A template with an image, test and buttons.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "The text show in the notification box."
+ },
+ "priority": {
+ "description": "Infobar priority level https://searchfox.org/mozilla-central/rev/3aef835f6cb12e607154d56d68726767172571e4/toolkit/content/widgets/notificationbox.js#387",
+ "type": "number",
+ "minumum": 0,
+ "exclusiveMaximum": 10
+ },
+ "buttons": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "The text label of the button."
+ },
+ "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": true
+ },
+ "supportPage": {
+ "type": "string",
+ "description": "A page title on SUMO to link to"
+ }
+ },
+ "required": ["label", "action"],
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": ["text", "buttons"]
+ },
+ "template": {
+ "type": "string",
+ "const": "infobar"
+ }
+ },
+ "additionalProperties": true,
+ "required": ["targeting", "trigger"],
+ "$defs": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ }
+}
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..d9b6728067
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json
@@ -0,0 +1,171 @@
+{
+ "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..d9911ff02c
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss
@@ -0,0 +1,55 @@
+.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: var(--newtab-text-primary-color);
+ margin-inline-end: 18px;
+ border: $input-border;
+ padding: 5px 14px;
+ background: var(--newtab-background-color-secondary);
+ cursor: pointer;
+ }
+
+ input {
+ &[type='radio'] {
+ opacity: 0;
+ margin-inline-end: -18px;
+
+ &:checked + .donation-amount {
+ // Use a text color for the background to achieve an inverted look.
+ background: var(--newtab-text-secondary-color);
+ color: var(--newtab-background-color-secondary);
+ border: $border-secondary;
+ }
+
+ // accessibility
+ &:checked:focus + .donation-amount,
+ &:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-primary-action-background);
+ }
+ }
+ }
+
+ .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..315aaba7a0
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json
@@ -0,0 +1,196 @@
+{
+ "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..6fc4d2283a
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.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/. */
+
+/**
+ * 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);
+ }
+ for (let [key, value] of Object.entries(BASE_PARAMS)) {
+ if (!returnUrl.searchParams.has(key)) {
+ returnUrl.searchParams.append(key, value);
+ }
+ }
+ 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..c77261c191
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json
@@ -0,0 +1,186 @@
+{
+ "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/ProtectionsPanelMessage.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ProtectionsPanelMessage.schema.json
new file mode 100644
index 0000000000..8ef9b802e1
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ProtectionsPanelMessage.schema.json
@@ -0,0 +1,62 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ProtectionsPanelMessage.schema.json",
+ "title": "ProtectionsPanelMessage",
+ "description": "A message shown in the protections panel.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "description": "The message title.",
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText"
+ },
+ "body": {
+ "description": "The body of the message.",
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText"
+ },
+ "link_text": {
+ "description": "The text of the call to action link.",
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText"
+ },
+ "cta_type": {
+ "description": "The type of URL open action.",
+ "type": "string",
+ "enum": ["OPEN_URL", "OPEN_PROTECTION_REPORT", "OPEN_ABOUT_PAGE"]
+ },
+ "cta_url": {
+ "description": "The URL to open when the call to action is clicked",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "cta_where": {
+ "description": "How to open the cta.",
+ "type": "string",
+ "enum": ["current", "tabshifted", "tab", "save", "window"]
+ }
+ },
+ "dependantSchemas": {
+ "link_text": ["cta_type", "cta_url"],
+ "cta_type": ["link_text"],
+ "cta_url": ["link_text"],
+ "cta_where": ["link_text"]
+ },
+ "additionalProperties": false,
+ "required": ["title", "body"]
+ },
+ "template": {
+ "type": "string",
+ "const": "protections_panel"
+ },
+ "trigger": {
+ "description": "An action to trigger potentially showing the message. The action ID `protectionsPanelOpen` is required.",
+ "const": {
+ "id": "protectionsPanelOpen"
+ }
+ }
+ },
+ "required": ["content", "template", "trigger"],
+ "additionalProperties": true
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/Spotlight.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/Spotlight.schema.json
new file mode 100644
index 0000000000..5d5b98f594
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/Spotlight.schema.json
@@ -0,0 +1,66 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///Spotlight.schema.json",
+ "title": "Spotlight",
+ "description": "A template with an image, title, content and two buttons.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "template": {
+ "type": "string",
+ "description": "Specify the layout template for the Spotlight",
+ "const": "multistage"
+ },
+ "backdrop": {
+ "type": "string",
+ "description": "Background css behind modal content"
+ },
+ "logo": {
+ "type": "object",
+ "properties": {
+ "imageURL": {
+ "type": "string",
+ "description": "URL for image to use with the content"
+ },
+ "imageId": {
+ "type": "string",
+ "description": "The ID for a remotely hosted image"
+ },
+ "size": {
+ "type": "string",
+ "description": "The logo size."
+ }
+ },
+ "additionalProperties": true
+ },
+ "screens": {
+ "type": "array",
+ "description": "Collection of individual screen content"
+ },
+ "transitions": {
+ "type": "boolean",
+ "description": "Show transitions within and between screens"
+ },
+ "disableHistoryUpdates": {
+ "type": "boolean",
+ "description": "Don't alter the browser session's history stack - used with messaging surfaces like Feature Callouts"
+ },
+ "startScreen": {
+ "type": "integer",
+ "description": "Index of first screen to show from message, defaulting to 0"
+ }
+ },
+ "additionalProperties": true
+ },
+ "template": {
+ "type": "string",
+ "description": "Specify whether the surface is shown as a Spotlight modal or an in-surface Feature Callout dialog",
+ "enum": ["spotlight", "feature_callout"]
+ }
+ },
+ "additionalProperties": true,
+ "required": ["targeting"]
+}
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..4ec7dc9522
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json
@@ -0,0 +1,45 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ToolbarBadgeMessage.schema.json",
+ "title": "ToolbarBadgeMessage",
+ "description": "A template that specifies to which element in the browser toolbar to add a notification.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "target": {
+ "type": "string"
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true,
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizedText",
+ "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'"
+ }
+ },
+ "additionalProperties": true,
+ "required": ["target"]
+ },
+ "template": {
+ "type": "string",
+ "const": "toolbar_badge"
+ }
+ },
+ "additionalProperties": true,
+ "required": ["targeting"]
+}
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..c5a466a6e5
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json
@@ -0,0 +1,47 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///UpdateAction.schema.json",
+ "title": "UpdateActionMessage",
+ "description": "A template for messages that execute predetermined actions.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "data": {
+ "type": "object",
+ "description": "Additional data provided as argument when executing the action",
+ "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"
+ }
+ }
+ }
+ },
+ "additionalProperties": true,
+ "description": "Optional action to take in addition to showing the notification",
+ "required": ["id", "data"]
+ }
+ },
+ "additionalProperties": true,
+ "required": ["action"]
+ },
+ "template": {
+ "type": "string",
+ "const": "update_action"
+ }
+ },
+ "required": ["targeting"]
+}
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..26e795d068
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json
@@ -0,0 +1,73 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///WhatsNewMessage.schema.json",
+ "title": "WhatsNewMessage",
+ "description": "A template for the messages that appear in the What's New panel.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "layout": {
+ "description": "Different message layouts",
+ "enum": ["tracking-protections"]
+ },
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message title"
+ },
+ "subtitle": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message subtitle"
+ },
+ "body": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of What's New message body"
+ },
+ "link_text": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/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": "moz-url-format"
+ },
+ "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": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Alt text for image."
+ }
+ },
+ "additionalProperties": true,
+ "required": ["published_date", "title", "body", "cta_url", "bucket_id"]
+ },
+ "template": {
+ "type": "string",
+ "const": "whatsnew_panel_message"
+ }
+ },
+ "required": ["order"],
+ "additionalProperties": true
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/PBNewtab/NewtabPromoMessage.schema.json b/browser/components/newtab/content-src/asrouter/templates/PBNewtab/NewtabPromoMessage.schema.json
new file mode 100644
index 0000000000..3719419428
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/PBNewtab/NewtabPromoMessage.schema.json
@@ -0,0 +1,153 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///NewtabPromoMessage.schema.json",
+ "title": "PBNewtabPromoMessage",
+ "description": "Message shown on the private browsing newtab page.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "hideDefault": {
+ "type": "boolean",
+ "description": "Should we hide the default promo after the experiment promo is dismissed."
+ },
+ "infoEnabled": {
+ "type": "boolean",
+ "description": "Should we show the info section."
+ },
+ "infoIcon": {
+ "type": "string",
+ "description": "Icon shown in the left side of the info section. Default is the private browsing icon."
+ },
+ "infoTitle": {
+ "type": "string",
+ "description": "Is the title in the info section enabled."
+ },
+ "infoTitleEnabled": {
+ "type": "boolean",
+ "description": "Is the title in the info section enabled."
+ },
+ "infoBody": {
+ "type": "string",
+ "description": "Text content in the info section."
+ },
+ "infoLinkText": {
+ "type": "string",
+ "description": "Text for the link in the info section."
+ },
+ "infoLinkUrl": {
+ "type": "string",
+ "description": "URL for the info section link.",
+ "format": "moz-url-format"
+ },
+ "promoEnabled": {
+ "type": "boolean",
+ "description": "Should we show the promo section."
+ },
+ "promoType": {
+ "type": "string",
+ "description": "Promo type used to determine if promo should show to a given user",
+ "enum": ["FOCUS", "VPN", "PIN", "COOKIE_BANNERS", "OTHER"]
+ },
+ "promoSectionStyle": {
+ "type": "string",
+ "description": "Sets the position of the promo section. Possible values are: top, below-search, bottom. Default bottom.",
+ "enum": ["top", "below-search", "bottom"]
+ },
+ "promoTitle": {
+ "type": "string",
+ "description": "The text content of the promo section."
+ },
+ "promoTitleEnabled": {
+ "type": "boolean",
+ "description": "Should we show text content in the promo section."
+ },
+ "promoLinkText": {
+ "type": "string",
+ "description": "The text of the link in the promo box."
+ },
+ "promoHeader": {
+ "type": "string",
+ "description": "The title of the promo section."
+ },
+ "promoButton": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "type": "object"
+ }
+ },
+ "required": ["type"],
+ "additionalProperties": true
+ }
+ },
+ "required": ["action"]
+ },
+ "promoLinkType": {
+ "type": "string",
+ "description": "Type of promo link type. Possible values: link, button. Default is link.",
+ "enum": ["link", "button"]
+ },
+ "promoImageLarge": {
+ "type": "string",
+ "description": "URL for image used on the left side of the promo box, larger, showcases some feature. Default off.",
+ "format": "uri"
+ },
+ "promoImageSmall": {
+ "type": "string",
+ "description": "URL for image used on the right side of the promo box, smaller, usually a logo. Default off.",
+ "format": "uri"
+ }
+ },
+ "additionalProperties": true,
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "promoEnabled": { "const": true }
+ },
+ "required": ["promoEnabled"]
+ },
+ "then": {
+ "required": ["promoButton"]
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "infoEnabled": { "const": true }
+ },
+ "required": ["infoEnabled"]
+ },
+ "then": {
+ "required": ["infoLinkText"],
+ "if": {
+ "properties": {
+ "infoTitleEnabled": { "const": true }
+ },
+ "required": ["infoTitleEnabled"]
+ },
+ "then": {
+ "required": ["infoTitle"]
+ }
+ }
+ }
+ ]
+ },
+ "template": {
+ "type": "string",
+ "const": "pb_newtab"
+ }
+ },
+ "additionalProperties": true,
+ "required": ["targeting"]
+}
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..34567443f4
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json
@@ -0,0 +1,243 @@
+{
+ "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..44ef622227
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js
@@ -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/. */
+
+/**
+ * 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..06368257f0
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json
@@ -0,0 +1,114 @@
+{
+ "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..9d902b4cbb
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss
@@ -0,0 +1,190 @@
+
+.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: $shadow-card;
+ flex-direction: column;
+ padding: 16px;
+ text-align: center;
+ width: 100%;
+
+ @media (min-width: $break-point-medium) {
+ 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) {
+ 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: $shadow-primary;
+ 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;
+
+ @media (min-width: $break-point-medium) {
+ height: 24px;
+ width: 24px;
+ }
+
+ @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..96570e2dbd
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx
@@ -0,0 +1,222 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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..4970b124af
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json
@@ -0,0 +1,159 @@
+{
+ "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..1ee83a5cc9
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss
@@ -0,0 +1,131 @@
+$section-header-height: 30px;
+$icon-width: 54px; // width of primary icon + margin
+
+.SimpleSnippet {
+ &.tall {
+ padding: 27px 0;
+ }
+
+ p em {
+ color: var(--newtab-text-emphasis-text-color);
+ font-style: normal;
+ background: var(--newtab-text-emphasis-background);
+ }
+
+ &.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;
+ }
+
+ &.bold,
+ &.takeover {
+ .donation-form-url,
+ .donation-amount {
+ padding-block: 8px;
+ }
+
+ .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-text-primary-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0;
+
+ a {
+ color: var(--newtab-text-primary-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..12eeecc084
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json
@@ -0,0 +1,167 @@
+{
+ "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..b9750e0765
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx
@@ -0,0 +1,408 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.error(err);
+ }
+
+ 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 {
+ 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..2a5ebda7e0
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json
@@ -0,0 +1,235 @@
+{
+ "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..3c1738aef0
--- /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-background-color-secondary);
+ 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-text-primary-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/ToastNotification/ToastNotification.schema.json b/browser/components/newtab/content-src/asrouter/templates/ToastNotification/ToastNotification.schema.json
new file mode 100644
index 0000000000..c6d917d235
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/ToastNotification/ToastNotification.schema.json
@@ -0,0 +1,85 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "file:///ToastNotification.schema.json",
+ "title": "ToastNotification",
+ "description": "A template for toast notifications displayed by the Alert service.",
+ "allOf": [{ "$ref": "file:///FxMSCommon.schema.json#/$defs/Message" }],
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification title"
+ },
+ "body": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "Id of localized string or message override of toast notification body"
+ },
+ "icon_url": {
+ "description": "The URL of the image used as an icon of the toast notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "image_url": {
+ "description": "The URL of an image to be displayed as part of the notification.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "launch_url": {
+ "description": "The URL to launch when the notification or an action button is clicked.",
+ "type": "string",
+ "format": "moz-url-format"
+ },
+ "requireInteraction": {
+ "type": "boolean",
+ "description": "Whether the toast notification should remain active until the user clicks or dismisses it, rather than closing automatically."
+ },
+ "tag": {
+ "type": "string",
+ "description": "An identifying tag for the toast notification."
+ },
+ "data": {
+ "type": "object",
+ "description": "Arbitrary data associated with the toast notification."
+ },
+ "actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "$ref": "file:///FxMSCommon.schema.json#/$defs/localizableText",
+ "description": "The action text to be shown to the user."
+ },
+ "action": {
+ "type": "string",
+ "description": "Opaque identifer that identifies action."
+ },
+ "iconURL": {
+ "type": "string",
+ "format": "uri",
+ "description": "URL of an icon to display with the action."
+ },
+ "windowsSystemActivationType": {
+ "type": "boolean",
+ "description": "Whether to have Windows process the given `action`."
+ }
+ },
+ "required": ["action", "title"],
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": ["title", "body"]
+ },
+ "template": {
+ "type": "string",
+ "const": "toast_notification"
+ }
+ },
+ "required": ["content", "targeting", "template", "trigger"],
+ "additionalProperties": true
+}
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..c87fc93b60
--- /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-primary-action-background);
+
+ &: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..3762be9c99
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
@@ -0,0 +1,1967 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+import { ASRouterUtils } from "../../asrouter/asrouter-utils";
+import { connect } from "react-redux";
+import React from "react";
+import { SimpleHashRouter } from "./SimpleHashRouter";
+import { CopyButton } from "./CopyButton";
+
+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.togglePersonalization = this.togglePersonalization.bind(this);
+ }
+
+ togglePersonalization() {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_TOGGLE,
+ })
+ );
+ }
+
+ render() {
+ const { lastUpdated, initialized } = this.props.state.Personalization;
+ return (
+ <React.Fragment>
+ <table>
+ <tbody>
+ <Row>
+ <td colSpan="2">
+ <TogglePrefCheckbox
+ checked={this.props.personalized}
+ pref="personalized"
+ onChange={this.togglePersonalization}
+ />
+ </td>
+ </Row>
+ <Row>
+ <td className="min">Personalization Last Updated</td>
+ <td>{relativeTime(lastUpdated) || "(no data)"}</td>
+ </Row>
+ <Row>
+ <td className="min">Personalization Initialized</td>
+ <td>{initialized ? "true" : "false"}</td>
+ </Row>
+ </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 collapsible".split(
+ " "
+ );
+ const { config, lastUpdated, layout } = this.props.state.DiscoveryStream;
+ const personalized =
+ this.props.otherPrefs["discoverystream.personalization.enabled"];
+ 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
+ personalized={personalized}
+ 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.handleOpenPB = this.handleOpenPB.bind(this);
+ this.selectPBMessage = this.selectPBMessage.bind(this);
+ this.resetPBJSON = this.resetPBJSON.bind(this);
+ this.resetPBMessageState = this.resetPBMessageState.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",
+ collapsedMessages: [],
+ modifiedMessages: [],
+ selectedPBMessage: "",
+ evaluationStatus: {},
+ stringTargetingParameters: null,
+ newStringTargetingParameters: null,
+ copiedToClipboard: false,
+ attributionParameters: {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: `rta:${btoa("uBlock0@raymondhill.net")}`,
+ 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),
+ ],
+ }));
+ }
+
+ handleOverride(id) {
+ return () =>
+ ASRouterUtils.overrideMessage(id).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message,
+ });
+ });
+ }
+
+ resetPBMessageState() {
+ // Iterate over Private Browsing messages and block/unblock each one to clear impressions
+ const PBMessages = this.state.messages.filter(
+ message => message.template === "pb_newtab"
+ ); // messages from state go here
+
+ PBMessages.forEach(message => {
+ if (message?.id) {
+ ASRouterUtils.blockById(message.id);
+ ASRouterUtils.unblockById(message.id);
+ }
+ });
+ // Clear the selected messages & radio buttons
+ document.getElementById("clear radio").checked = true;
+ this.selectPBMessage("clear");
+ }
+
+ resetPBJSON(msg) {
+ // reset the displayed JSON for the given message
+ document.getElementById(`${msg.id}-textarea`).value = JSON.stringify(
+ msg,
+ null,
+ 2
+ );
+ }
+
+ handleOpenPB() {
+ ASRouterUtils.sendMessage({
+ type: "FORCE_PRIVATE_BROWSING_WINDOW",
+ data: { message: { content: this.state.selectedPBMessage } },
+ });
+ }
+
+ 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.error(`Error parsing value of parameter ${name}`);
+ 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);
+ const aboutMessagePreviewSupported = [
+ "infobar",
+ "spotlight",
+ "cfr_doorhanger",
+ ].includes(msg.template);
+
+ 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>
+ )}
+ {aboutMessagePreviewSupported ? (
+ <CopyButton
+ transformer={text =>
+ `about:messagepreview?json=${encodeURIComponent(btoa(text))}`
+ }
+ label="Share"
+ copiedLabel="Copied!"
+ inputSelector={`#${msg.id}-textarea`}
+ className={"button share"}
+ />
+ ) : null}
+ <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>
+ );
+ }
+
+ selectPBMessage(msgId) {
+ if (msgId === "clear") {
+ this.setState({
+ selectedPBMessage: "",
+ });
+ } else {
+ let selected = document.getElementById(`${msgId} radio`);
+ let msg = JSON.parse(document.getElementById(`${msgId}-textarea`).value);
+
+ if (selected.checked) {
+ this.setState({
+ selectedPBMessage: msg?.content,
+ });
+ } else {
+ this.setState({
+ selectedPBMessage: "",
+ });
+ }
+ }
+ }
+
+ 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,
+ });
+ });
+ }
+
+ renderPBMessageItem(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="radio"
+ id={`${msg.id} radio`}
+ name="PB_message_radio"
+ style={{ marginBottom: 20 }}
+ onClick={() => this.selectPBMessage(msg.id)}
+ disabled={isBlocked}
+ />
+ <button
+ className={`button ${isBlocked ? "" : " primary"}`}
+ onClick={
+ isBlocked ? this.handleUnblock(msg) : this.handleBlock(msg)
+ }
+ >
+ {isBlocked ? "Unblock" : "Block"}
+ </button>
+ <button
+ className="ASRouterButton slim button"
+ onClick={e => this.resetPBJSON(msg)}
+ >
+ Reset JSON
+ </button>
+ </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 &&
+ message.template !== "pb_newtab"
+ );
+
+ 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. Click
+ 'Share' to copy a link to the clipboard that can be used to preview
+ the message by opening the link in Nightly/local builds.
+ </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>
+ );
+ }
+
+ renderPBMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+ const messagesToShow = this.state.messages.filter(
+ message => message.template === "pb_newtab"
+ );
+ return (
+ <table>
+ <tbody>
+ {messagesToShow.map(msg => this.renderPBMessageItem(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>
+ Show messages from{" "}
+ <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.collection})`;
+ } 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 'uBlock Origin'. 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 a string that is 'rta:base64(addonID)', the
+ base64 string of the addonID prefixed with 'rta:'. The addon must
+ currently be a recommended addon on AMO. 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={`rta:${btoa("uBlock0@raymondhill.net")}`}
+ 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>;
+ }
+
+ renderPBTab() {
+ if (!this.state.messages) {
+ return null;
+ }
+ let messagesToShow = this.state.messages.filter(
+ message => message.template === "pb_newtab"
+ );
+
+ return (
+ <div>
+ <p className="helpLink">
+ <span className="icon icon-small-spacer icon-info" />{" "}
+ <span>
+ To view an available message, select its radio button and click
+ "Open a Private Browsing Window".
+ <br />
+ To modify a message, make changes to the JSON first, then select the
+ radio button. (To make new changes, click "Reset Message State",
+ make your changes, and reselect the radio button.)
+ <br />
+ Click "Reset Message State" to clear all message impressions and
+ view messages in a clean state.
+ <br />
+ Note that ContentSearch functions do not work in debug mode.
+ </span>
+ </p>
+ <div>
+ <button
+ className="ASRouterButton primary button"
+ onClick={this.handleOpenPB}
+ >
+ Open a Private Browsing Window
+ </button>
+ <button
+ className="ASRouterButton primary button"
+ style={{ marginInlineStart: 12 }}
+ onClick={this.resetPBMessageState}
+ >
+ Reset Message State
+ </button>
+ <br />
+ <input
+ type="radio"
+ id={`clear radio`}
+ name="PB_message_radio"
+ value="clearPBMessage"
+ style={{ display: "none" }}
+ />
+ <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.renderPBMessages()}
+ </div>
+ </div>
+ );
+ }
+
+ getSection() {
+ const [section] = this.props.location.routes;
+ switch (section) {
+ case "private":
+ return (
+ <React.Fragment>
+ <h2>Private Browsing Messages</h2>
+ {this.renderPBTab()}
+ </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-private">Private Browsing</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://firefox-source-docs.mozilla.org/browser/components/newtab/content-src/asrouter/docs/debugging-docs.html"
+ >
+ 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..b095b94ef6
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss
@@ -0,0 +1,280 @@
+.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://global/skin/icons/developer.svg');
+ padding: 15px;
+ }
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &.expanded {
+ background: $black-20;
+ }
+}
+
+.asrouter-admin {
+ $border-color: var(--newtab-border-color);
+ $monospace: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', 'Droid Sans Mono',
+ 'Source Code Pro', monospace;
+ $sidebar-width: 240px;
+
+ 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: $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-background-color-secondary);
+ }
+ }
+ }
+
+ 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: var(--newtab-element-hover-color);
+ 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-background-color-secondary);
+ }
+
+ td {
+ padding: 4px;
+
+ &[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+ }
+ }
+ }
+ }
+
+ .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+
+ &.isDisabled {
+ background: $email-input-invalid;
+ color: var(--newtab-status-error);
+ }
+ }
+
+ .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-background-color-secondary);
+ margin: 0;
+ padding: 8px;
+ font-size: 12px;
+ max-width: 750px;
+ overflow: auto;
+ font-family: $monospace;
+ }
+
+ .errorState {
+ border: $input-error-border;
+ }
+
+ .helpLink {
+ padding: 10px;
+ display: flex;
+ background: $black-10;
+ border-radius: 3px;
+ align-items: center;
+
+ a {
+ text-decoration: underline;
+ }
+
+ .icon {
+ min-width: 18px;
+ min-height: 18px;
+ }
+ }
+
+ .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/CopyButton.jsx b/browser/components/newtab/content-src/components/ASRouterAdmin/CopyButton.jsx
new file mode 100644
index 0000000000..07ce12d7bf
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/CopyButton.jsx
@@ -0,0 +1,31 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, useRef, useCallback } from "react";
+
+export const CopyButton = ({
+ className,
+ label,
+ copiedLabel,
+ inputSelector,
+ transformer,
+ ...props
+}) => {
+ const [copied, setCopied] = useState(false);
+ const timeout = useRef(null);
+ const onClick = useCallback(() => {
+ let text = document.querySelector(inputSelector).value;
+ if (transformer) text = transformer(text);
+ navigator.clipboard.writeText(text);
+
+ clearTimeout(timeout.current);
+ setCopied(true);
+ timeout.current = setTimeout(() => setCopied(false), 1500);
+ }, [inputSelector, transformer]);
+ return (
+ <button className={className} onClick={e => onClick()} {...props}>
+ {(copied && copiedLabel) || label}
+ </button>
+ );
+};
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..8845ad87cd
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/Base.jsx
@@ -0,0 +1,273 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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";
+
+export const PrefsButton = ({ onClick, icon }) => (
+ <div className="prefs-button">
+ <button
+ className={`icon ${icon || "icon-settings"}`}
+ onClick={onClick}
+ data-l10n-id="newtab-settings-button"
+ />
+ </div>
+);
+
+// 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 };
+ }
+
+ 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.props.dispatch({ type: at.SHOW_PERSONALIZE });
+ this.props.dispatch(ac.UserEvent({ event: "SHOW_PERSONALIZE" }));
+ }
+
+ closeCustomizationMenu() {
+ if (this.props.App.customizeMenuVisible) {
+ this.props.dispatch({ type: at.HIDE_PERSONALIZE });
+ 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, customizeMenuVisible } = App;
+ const prefs = props.Prefs.values;
+
+ 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 enabledSections = {
+ topSitesEnabled: prefs["feeds.topsites"],
+ pocketEnabled: prefs["feeds.section.topstories"],
+ highlightsEnabled: prefs["feeds.section.highlights"],
+ showSponsoredTopSitesEnabled: prefs.showSponsoredTopSites,
+ showSponsoredPocketEnabled: prefs.showSponsored,
+ showRecentSavesEnabled: prefs.showRecentSaves,
+ 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",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ const hasSnippet =
+ prefs["feeds.snippets"] &&
+ this.props.adminContent &&
+ this.props.adminContent.message &&
+ this.props.adminContent.message.id;
+
+ return (
+ <div>
+ <CustomizeMenu
+ onClose={this.closeCustomizationMenu}
+ onOpen={this.openCustomizationMenu}
+ openPreferences={this.openPreferences}
+ setPref={this.setPref}
+ enabledSections={enabledSections}
+ pocketRegion={pocketRegion}
+ mayHaveSponsoredTopSites={mayHaveSponsoredTopSites}
+ showing={customizeMenuVisible}
+ />
+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions*/}
+ <div className={outerClassName} onClick={this.closeCustomizationMenu}>
+ <main className={hasSnippet ? "has-snippet" : ""}>
+ {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..7e13fe9a90
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/_Base.scss
@@ -0,0 +1,143 @@
+.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-primary-action-background);
+ }
+}
+
+main {
+ margin: auto;
+ width: $wrapper-default-width;
+ padding: 0;
+
+ 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;
+ }
+
+ &.has-snippet {
+ // 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;
+ }
+}
+
+.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: 0;
+
+ @media (min-width: $break-point-medium) {
+ width: 510px;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: 746px;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: 986px;
+ }
+
+ &.has-snippet {
+ // 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;
+ }
+ }
+}
+
+.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);
+ }
+ }
+}
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..9d03377f1b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/Card.jsx
@@ -0,0 +1,362 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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
+ try {
+ await gImageLoading.get(imageUrl);
+ } catch (ex) {
+ // Ignore the failed image without changing state
+ return;
+ }
+
+ // 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..0c363b52d8
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/_Card.scss
@@ -0,0 +1,331 @@
+@use 'sass:math';
+
+.card-outer {
+ @include context-menu-button;
+
+ background: var(--newtab-background-color-secondary);
+ border-radius: $border-radius-new;
+ display: inline-block;
+ height: $card-height;
+ margin-inline-end: $base-gutter;
+ position: relative;
+ width: 100%;
+
+ &:is(:focus):not(.placeholder) {
+ @include ds-focus;
+
+ transition: none;
+ }
+
+ &:hover {
+ box-shadow: none;
+ transition: none;
+ }
+
+ &.placeholder {
+ background: transparent;
+
+ .card-preview-image-outer,
+ .card-context {
+ display: none;
+ }
+ }
+
+ .card {
+ border-radius: $border-radius-new;
+ box-shadow: $shadow-card;
+ height: 100%;
+ }
+
+ > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%;
+
+ &:is(:focus) {
+ .card {
+ @include ds-focus;
+ }
+ }
+
+ &:is(.active, :focus) {
+ .card {
+ @include fade-in-card;
+ }
+
+ .card-title {
+ color: var(--newtab-primary-action-background);
+ }
+ }
+ }
+
+ &:is(:hover, :focus, .active):not(.placeholder) {
+ @include context-menu-button-hover;
+
+ outline: none;
+
+ .card-title {
+ color: var(--newtab-primary-action-background);
+ }
+
+ .alternate ~ .card-host-name {
+ display: none;
+ }
+
+ .card-host-name.alternate {
+ display: block;
+ }
+ }
+
+ .card-preview-image-outer {
+ background-color: var(--newtab-element-secondary-color);
+ border-radius: $border-radius-new $border-radius-new 0 0;
+ height: $card-preview-image-height;
+ overflow: hidden;
+ position: relative;
+
+ &::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;
+ 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-background-color-secondary);
+ border-radius: math.div($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: math.div($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 - math.div($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: math.div($container-size, 2) + 1 math.div($container-size, 2) + 1 0 0;
+ content: '';
+ position: absolute;
+ height: math.div($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..679e8e137f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx
@@ -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/. */
+
+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";
+
+/**
+ * A section that can collapse. As of bug 1710937, it can no longer collapse.
+ * See bug 1727365 for follow-up work to simplify this component.
+ */
+export class _CollapsibleSection extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBodyMount = this.onBodyMount.bind(this);
+ this.onMenuButtonMouseEnter = this.onMenuButtonMouseEnter.bind(this);
+ this.onMenuButtonMouseLeave = this.onMenuButtonMouseLeave.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.state = {
+ menuButtonHover: false,
+ showContextMenu: false,
+ };
+ this.setContextMenuButtonRef = this.setContextMenuButtonRef.bind(this);
+ }
+
+ setContextMenuButtonRef(element) {
+ this.contextMenuButtonRef = element;
+ }
+
+ onBodyMount(node) {
+ this.sectionBody = node;
+ }
+
+ onMenuButtonMouseEnter() {
+ this.setState({ menuButtonHover: true });
+ }
+
+ onMenuButtonMouseLeave() {
+ this.setState({ menuButtonHover: false });
+ }
+
+ onMenuUpdate(showContextMenu) {
+ this.setState({ showContextMenu });
+ }
+
+ render() {
+ const { isAnimating, maxHeight, menuButtonHover, showContextMenu } =
+ this.state;
+ const { id, collapsed, learnMore, title, subTitle } = 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" };
+ }
+ const hasSubtitleClassName = subTitle ? `has-subtitle` : ``;
+ return (
+ <section
+ className={`collapsible-section ${this.props.className}${
+ active ? " active" : ""
+ }`}
+ // 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-container ${hasSubtitleClassName}`}
+ style={titleStyle}
+ >
+ <span className="section-title">
+ <FluentOrText message={title} />
+ </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>
+ {subTitle && (
+ <span className="section-sub-title">
+ <FluentOrText message={subTitle} />
+ </span>
+ )}
+ </h3>
+ </div>
+ <ErrorBoundary className="section-body-fallback">
+ <div 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..9811339b27
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss
@@ -0,0 +1,106 @@
+.collapsible-section {
+ padding: $section-vertical-padding $section-horizontal-padding;
+
+ .section-title-container {
+ margin: 0;
+
+ &.has-subtitle {
+ display: flex;
+ flex-direction: column;
+
+ @media (min-width: $break-point-large) {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ }
+ }
+ }
+
+ .section-title {
+ font-size: $section-title-font-size;
+ font-weight: 600;
+ color: var(--newtab-text-primary-color);
+
+ &.grey-title {
+ color: var(--newtab-text-primary-color);
+ display: inline-block;
+ fill: var(--newtab-text-primary-color);
+ vertical-align: middle;
+ }
+
+ .section-title-contents {
+ // 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;
+ }
+ }
+
+ .section-sub-title {
+ font-size: 14px;
+ line-height: 16px;
+ color: var(--newtab-text-secondary-color);
+ opacity: 0.3;
+ }
+
+ .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative;
+ }
+
+ &.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+ }
+
+ .learn-more-link {
+ font-size: 13px;
+ margin-inline-start: 12px;
+
+ a {
+ color: var(--newtab-primary-action-background);
+ }
+ }
+
+ .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;
+ }
+ }
+
+ &[data-section-id='topsites'] {
+ .section-top-bar {
+ display: none;
+ }
+ }
+
+ // 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..4efd8c712e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx
@@ -0,0 +1,177 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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..f69e540079
--- /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.sys.mjs";
+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..ca9940ffc5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ConfirmDialog/_ConfirmDialog.scss
@@ -0,0 +1,68 @@
+.confirmation-dialog {
+ .modal {
+ box-shadow: $shadow-secondary;
+ 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-background-color-secondary);
+ 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..5ea6a57f71
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/ContextMenu.jsx
@@ -0,0 +1,176 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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;
+ 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}
+ aria-haspopup={
+ option.id === "newtab-menu-edit-topsites" ? "dialog" : null
+ }
+ >
+ <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..c0074128e6
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss
@@ -0,0 +1,57 @@
+@use 'sass:math';
+
+.context-menu {
+ background: var(--newtab-background-color-secondary);
+ 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: math.div($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-secondary-hover-color);
+ }
+
+ &:active {
+ background: var(--newtab-element-secondary-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..423fd131e2
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx
@@ -0,0 +1,308 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+
+export class ContentSection extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onPreferenceSelect = this.onPreferenceSelect.bind(this);
+
+ // Refs are necessary for dynamically measuring drawer heights for slide animations
+ this.topSitesDrawerRef = React.createRef();
+ this.pocketDrawerRef = React.createRef();
+ }
+
+ 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"); // TOP_SITES, TOP_STORIES, HIGHLIGHTS
+ 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);
+ }
+
+ componentDidMount() {
+ this.setDrawerMargins();
+ }
+
+ componentDidUpdate() {
+ this.setDrawerMargins();
+ }
+
+ setDrawerMargins() {
+ this.setDrawerMargin(
+ `TOP_SITES`,
+ this.props.enabledSections.topSitesEnabled
+ );
+ this.setDrawerMargin(
+ `TOP_STORIES`,
+ this.props.enabledSections.pocketEnabled
+ );
+ }
+
+ setDrawerMargin(drawerID, isOpen) {
+ let drawerRef;
+
+ if (drawerID === `TOP_SITES`) {
+ drawerRef = this.topSitesDrawerRef.current;
+ } else if (drawerID === `TOP_STORIES`) {
+ drawerRef = this.pocketDrawerRef.current;
+ } else {
+ return;
+ }
+
+ let drawerHeight;
+
+ if (drawerRef) {
+ drawerHeight = parseFloat(window.getComputedStyle(drawerRef)?.height);
+
+ if (isOpen) {
+ drawerRef.style.marginTop = `0`;
+ } else {
+ drawerRef.style.marginTop = `-${drawerHeight}px`;
+ }
+ }
+ }
+
+ render() {
+ const {
+ enabledSections,
+ mayHaveSponsoredTopSites,
+ pocketRegion,
+ mayHaveSponsoredStories,
+ mayHaveRecentSaves,
+ openPreferences,
+ } = this.props;
+ const {
+ topSitesEnabled,
+ pocketEnabled,
+ highlightsEnabled,
+ showSponsoredTopSitesEnabled,
+ showSponsoredPocketEnabled,
+ showRecentSavesEnabled,
+ topSitesRowsCount,
+ } = 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">
+ <div className="more-information" ref={this.topSitesDrawerRef}>
+ <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>
+ {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>
+
+ {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"
+ />
+ {(mayHaveSponsoredStories || mayHaveRecentSaves) && (
+ <div className="more-info-pocket-wrapper">
+ <div className="more-information" ref={this.pocketDrawerRef}>
+ {mayHaveSponsoredStories && (
+ <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>
+ )}
+ {mayHaveRecentSaves && (
+ <div className="check-wrapper" role="presentation">
+ <input
+ id="recent-saves-pocket"
+ className="sponsored-checkbox"
+ disabled={!pocketEnabled}
+ checked={showRecentSavesEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="showRecentSaves"
+ eventSource="POCKET_RECENT_SAVES"
+ />
+ <label
+ className="sponsored"
+ htmlFor="recent-saves-pocket"
+ data-l10n-id="newtab-custom-pocket-show-recent-saves"
+ />
+ </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>
+
+ <span className="divider" role="separator"></span>
+
+ <div>
+ <button
+ id="settings-link"
+ className="external-link"
+ onClick={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..2b16c7fd39
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx
@@ -0,0 +1,87 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { 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";
+import { CSSTransition } from "react-transition-group";
+
+export class _CustomizeMenu extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEntered = this.onEntered.bind(this);
+ this.onExited = this.onExited.bind(this);
+ }
+
+ onEntered() {
+ if (this.closeButton) {
+ this.closeButton.focus();
+ }
+ }
+
+ onExited() {
+ if (this.openButton) {
+ this.openButton.focus();
+ }
+ }
+
+ render() {
+ return (
+ <span>
+ <CSSTransition
+ timeout={300}
+ classNames="personalize-animate"
+ in={!this.props.showing}
+ appear={true}
+ >
+ <button
+ className="icon icon-settings personalize-button"
+ onClick={() => this.props.onOpen()}
+ data-l10n-id="newtab-personalize-icon-label"
+ ref={c => (this.openButton = c)}
+ />
+ </CSSTransition>
+ <CSSTransition
+ timeout={250}
+ classNames="customize-animate"
+ in={this.props.showing}
+ onEntered={this.onEntered}
+ onExited={this.onExited}
+ appear={true}
+ >
+ <div
+ className="customize-menu"
+ role="dialog"
+ data-l10n-id="newtab-personalize-dialog-label"
+ >
+ <button
+ onClick={() => this.props.onClose()}
+ className="close-button"
+ data-l10n-id="newtab-custom-close-button"
+ ref={c => (this.closeButton = c)}
+ />
+ <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
+ }
+ mayHaveRecentSaves={this.props.DiscoveryStream.recentSavesEnabled}
+ dispatch={this.props.dispatch}
+ />
+ </div>
+ </CSSTransition>
+ </span>
+ );
+ }
+}
+
+export const CustomizeMenu = connect(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+}))(_CustomizeMenu);
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..98046c2326
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss
@@ -0,0 +1,311 @@
+@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 {
+ border: 0;
+ border-radius: 4px;
+ background-color: transparent;
+ padding: 15px;
+
+ &:hover {
+ background-color: var(--newtab-element-hover-color);
+ }
+
+ &:active {
+ background-color: var(--newtab-element-active-color);
+ }
+
+ &:focus-visible {
+ @include ds-focus;
+ }
+
+ &.personalize-animate-exit-done {
+ visibility: hidden;
+ }
+}
+
+.customize-menu {
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color-secondary);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default;
+
+ @media (prefers-reduced-motion: no-preference) {
+ transition: transform 250ms $customize-menu-slide-bezier, visibility 250ms;
+ }
+
+ @media (forced-colors: active) {
+ border-inline-start: solid 1px;
+ }
+
+ &:dir(rtl) {
+ transform: translateX(-435px);
+ }
+
+ &.customize-animate-enter-done,
+ &.customize-animate-enter-active {
+ box-shadow: $shadow-large;
+ visibility: visible;
+ transform: translateX(0);
+ }
+
+ &.customize-animate-exit-active {
+ box-shadow: $shadow-large;
+ }
+
+ .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--newtab-element-secondary-color);
+ padding: 8px 10px;
+ border: $customize-menu-border-tint;
+ border-radius: 4px;
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ font-weight: 600;
+ }
+
+ .close-button:hover {
+ background-color: var(--newtab-element-secondary-hover-color);
+ }
+
+ .close-button:hover:active {
+ background-color: var(--newtab-element-secondary-active-color);
+ }
+}
+
+.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-element-secondary-color);
+ }
+
+ .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ background: url('chrome://global/skin/icons/check.svg') center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+
+ @media (forced-colors: active) {
+ fill: $black;
+ }
+ }
+
+ .sponsored-checkbox:active + .checkmark {
+ fill: var(--newtab-element-secondary-color);
+ }
+
+ .selector {
+ color: var(--newtab-text-primary-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ margin-bottom: 2px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-primary-color);
+ background: url('chrome://global/skin/icons/arrow-down-12.svg') right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--newtab-background-color-secondary);
+
+ &: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-element-secondary-color);
+
+ &::before {
+ position: absolute;
+ content: '';
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--newtab-primary-element-text-color);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: $customize-menu-border-tint;
+ }
+ }
+
+ .switch input:focus-visible + .slider {
+ outline: 0;
+ box-shadow: $shadow-focus;
+ }
+
+ .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-primary-action-background);
+ }
+
+ 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;
+
+ .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: margin-top 250ms $customize-menu-expand-bezier;
+ }
+ }
+
+ .more-info-top-wrapper {
+ .check-wrapper {
+ margin-top: 10px;
+ }
+ }
+ }
+
+ .divider {
+ border-top: 1px var(--newtab-border-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(--newtab-text-primary-color);
+ background: url('chrome://global/skin/icons/settings.svg') left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px;
+ text-decoration: underline;
+
+ @media (forced-colors: active) {
+ padding: 8px 10px;
+ padding-inline-start: 21px;
+ }
+
+ &:dir(rtl) {
+ background-position-x: right;
+ }
+ }
+
+ .external-link:hover {
+ text-decoration: none;
+ }
+}
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: $shadow-focus;
+}
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..9acfef211b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx
@@ -0,0 +1,384 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { Highlights } from "content-src/components/DiscoveryStreamComponents/Highlights/Highlights";
+import { HorizontalRule } from "content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule";
+import { Navigation } from "content-src/components/DiscoveryStreamComponents/Navigation/Navigation";
+import { PrivacyLink } from "content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink";
+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/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}`);
+ 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}`);
+ }
+ });
+ });
+ });
+ }
+
+ renderComponent(component, embedWidth) {
+ switch (component.type) {
+ case "Highlights":
+ return <Highlights />;
+ case "TopSites":
+ return (
+ <div className="ds-top-sites">
+ <TopSites isFixed={true} title={component.header?.title} />
+ </div>
+ );
+ 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}
+ essentialReadsHeader={component.essentialReadsHeader}
+ editorsPicksHeader={component.editorsPicksHeader}
+ />
+ );
+ case "SectionTitle":
+ return <SectionTitle header={component.header} />;
+ case "Navigation":
+ return (
+ <Navigation
+ dispatch={this.props.dispatch}
+ links={component.properties.links}
+ extraLinks={component.properties.extraLinks}
+ alignment={component.properties.alignment}
+ explore_topics={component.properties.explore_topics}
+ header={component.header}
+ locale={this.props.App.locale}
+ newFooterSection={component.newFooterSection}
+ privacyNoticeURL={component.properties.privacyNoticeURL}
+ />
+ );
+ case "CollectionCardGrid":
+ const { DiscoveryStream } = this.props;
+ return (
+ <CollectionCardGrid
+ data={component.data}
+ feed={component.feed}
+ spocs={DiscoveryStream.spocs}
+ placement={component.placement}
+ type={component.type}
+ items={component.properties.items}
+ dismissible={this.props.DiscoveryStream.isCollectionDismissible}
+ dispatch={this.props.dispatch}
+ />
+ );
+ case "CardGrid":
+ return (
+ <CardGrid
+ title={component.header && component.header.title}
+ data={component.data}
+ feed={component.feed}
+ widgets={component.widgets}
+ type={component.type}
+ dispatch={this.props.dispatch}
+ items={component.properties.items}
+ hybridLayout={component.properties.hybridLayout}
+ hideCardBackground={component.properties.hideCardBackground}
+ fourCardLayout={component.properties.fourCardLayout}
+ compactGrid={component.properties.compactGrid}
+ essentialReadsHeader={component.properties.essentialReadsHeader}
+ onboardingExperience={component.properties.onboardingExperience}
+ editorsPicksHeader={component.properties.editorsPicksHeader}
+ recentSavesEnabled={this.props.DiscoveryStream.recentSavesEnabled}
+ hideDescriptions={this.props.DiscoveryStream.hideDescriptions}
+ />
+ );
+ case "HorizontalRule":
+ return <HorizontalRule />;
+ case "PrivacyLink":
+ return <PrivacyLink properties={component.properties} />;
+ 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() {
+ const { locale } = this.props;
+ // Select layout render data by adding spocs and position to recommendations
+ const { layoutRender } = selectLayoutRender({
+ state: this.props.DiscoveryStream,
+ prefs: this.props.Prefs.values,
+ 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,
+ },
+ };
+
+ const privacyLinkComponent = extractComponent("PrivacyLink");
+ let learnMore = {
+ link: {
+ href: message.header.link_url,
+ message: message.header.link_text,
+ },
+ };
+ let sectionTitle = message.header.title;
+ let subTitle = "";
+
+ // If we're in one of these experiments, override the default message.
+ // For now this is English only.
+ if (message.essentialReadsHeader || message.editorsPicksHeader) {
+ learnMore = null;
+ subTitle = "Recommended By Pocket";
+ if (message.essentialReadsHeader) {
+ sectionTitle = "Today’s Essential Reads";
+ } else if (message.editorsPicksHeader) {
+ sectionTitle = "Editor’s Picks";
+ }
+ }
+
+ // 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}
+ id={topStories.id}
+ isFixed={true}
+ learnMore={learnMore}
+ privacyNoticeURL={topStories.privacyNoticeURL}
+ showPrefName={topStories.pref.feed}
+ title={sectionTitle}
+ subTitle={subTitle}
+ eventSource="CARDGRID"
+ >
+ {this.renderLayout(layoutRender)}
+ </CollapsibleSection>
+ )}
+ {this.renderLayout([
+ {
+ width: 12,
+ components: [{ type: "Highlights" }],
+ },
+ ])}
+ {privacyLinkComponent &&
+ this.renderLayout([
+ {
+ width: 12,
+ components: [privacyLinkComponent],
+ },
+ ])}
+ </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,
+ App: state.App,
+}))(_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..015cb57a8b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss
@@ -0,0 +1,67 @@
+$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 {
+ color: var(--newtab-text-primary-color);
+ font-size: $section-title-font-size;
+ 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-primary-action-background);
+ font-weight: 500;
+
+ &:is(:focus, :hover) {
+ text-decoration: none;
+ }
+ }
+ }
+}
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..09dc657cbb
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx
@@ -0,0 +1,536 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { DSDismiss } from "content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss";
+import { TopicsWidget } from "../TopicsWidget/TopicsWidget.jsx";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { FluentOrText } from "../../FluentOrText/FluentOrText.jsx";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import React, { useEffect, useState, useRef, useCallback } from "react";
+import { connect, useSelector } from "react-redux";
+const PREF_ONBOARDING_EXPERIENCE_DISMISSED =
+ "discoverystream.onboardingExperience.dismissed";
+const INTERSECTION_RATIO = 0.5;
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+const WIDGET_IDS = {
+ TOPICS: 1,
+};
+
+export function DSSubHeader({ children }) {
+ return (
+ <div className="section-top-bar ds-sub-header">
+ <h3 className="section-title-container">{children}</h3>
+ </div>
+ );
+}
+
+export function OnboardingExperience({
+ children,
+ dispatch,
+ windowObj = global,
+}) {
+ const [dismissed, setDismissed] = useState(false);
+ const [maxHeight, setMaxHeight] = useState(null);
+ const heightElement = useRef(null);
+
+ const onDismissClick = useCallback(() => {
+ // We update this as state and redux.
+ // The state update is for this newtab,
+ // and the redux update is for other tabs, offscreen tabs, and future tabs.
+ // We need the state update for this tab to support the transition.
+ setDismissed(true);
+ dispatch(ac.SetPref(PREF_ONBOARDING_EXPERIENCE_DISMISSED, true));
+ dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "BLOCK",
+ source: "POCKET_ONBOARDING",
+ })
+ );
+ }, [dispatch]);
+
+ useEffect(() => {
+ const resizeObserver = new windowObj.ResizeObserver(() => {
+ if (heightElement.current) {
+ setMaxHeight(heightElement.current.offsetHeight);
+ }
+ });
+
+ const options = { threshold: INTERSECTION_RATIO };
+ const intersectionObserver = new windowObj.IntersectionObserver(entries => {
+ if (
+ entries.some(
+ entry =>
+ entry.isIntersecting &&
+ entry.intersectionRatio >= INTERSECTION_RATIO
+ )
+ ) {
+ dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "IMPRESSION",
+ source: "POCKET_ONBOARDING",
+ })
+ );
+ // Once we have observed an impression, we can stop for this instance of newtab.
+ intersectionObserver.unobserve(heightElement.current);
+ }
+ }, options);
+
+ const onVisibilityChange = () => {
+ intersectionObserver.observe(heightElement.current);
+ windowObj.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ onVisibilityChange
+ );
+ };
+
+ if (heightElement.current) {
+ resizeObserver.observe(heightElement.current);
+ // Check visibility or setup a visibility event to make
+ // sure we don't fire this for off screen pre loaded tabs.
+ if (windowObj.document.visibilityState === VISIBLE) {
+ intersectionObserver.observe(heightElement.current);
+ } else {
+ windowObj.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ onVisibilityChange
+ );
+ }
+ setMaxHeight(heightElement.current.offsetHeight);
+ }
+
+ // Return unmount callback to clean up observers.
+ return () => {
+ resizeObserver?.disconnect();
+ intersectionObserver?.disconnect();
+ windowObj.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ onVisibilityChange
+ );
+ };
+ }, [dispatch, windowObj]);
+
+ const style = {};
+ if (dismissed) {
+ style.maxHeight = "0";
+ style.opacity = "0";
+ style.transition = "max-height 0.26s ease, opacity 0.26s ease";
+ } else if (maxHeight) {
+ style.maxHeight = `${maxHeight}px`;
+ }
+
+ return (
+ <div style={style}>
+ <div className="ds-onboarding-ref" ref={heightElement}>
+ <div className="ds-onboarding-container">
+ <DSDismiss
+ onDismissClick={onDismissClick}
+ extraClasses={`ds-onboarding`}
+ >
+ <div>
+ <header>
+ <span className="icon icon-pocket" />
+ <span data-l10n-id="newtab-pocket-onboarding-discover" />
+ </header>
+ <p data-l10n-id="newtab-pocket-onboarding-cta" />
+ </div>
+ <div className="ds-onboarding-graphic" />
+ </DSDismiss>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function IntersectionObserver({
+ children,
+ windowObj = window,
+ onIntersecting,
+}) {
+ const intersectionElement = useRef(null);
+
+ useEffect(() => {
+ let observer;
+ if (!observer && onIntersecting && intersectionElement.current) {
+ observer = new windowObj.IntersectionObserver(entries => {
+ const entry = entries.find(e => e.isIntersecting);
+
+ if (entry) {
+ // Stop observing since element has been seen
+ if (observer && intersectionElement.current) {
+ observer.unobserve(intersectionElement.current);
+ }
+
+ onIntersecting();
+ }
+ });
+ observer.observe(intersectionElement.current);
+ }
+ // Cleanup
+ return () => observer?.disconnect();
+ }, [windowObj, onIntersecting]);
+
+ return <div ref={intersectionElement}>{children}</div>;
+}
+
+export function RecentSavesContainer({
+ gridClassName = "",
+ dispatch,
+ windowObj = window,
+ items = 3,
+ source = "CARDGRID_RECENT_SAVES",
+}) {
+ const {
+ recentSavesData,
+ isUserLoggedIn,
+ experimentData: { utmCampaign, utmContent, utmSource },
+ } = useSelector(state => state.DiscoveryStream);
+
+ const [visible, setVisible] = useState(false);
+ const onIntersecting = useCallback(() => setVisible(true), []);
+
+ useEffect(() => {
+ if (visible) {
+ dispatch(
+ ac.AlsoToMain({
+ type: at.DISCOVERY_STREAM_POCKET_STATE_INIT,
+ })
+ );
+ }
+ }, [visible, dispatch]);
+
+ // The user has not yet scrolled to this section,
+ // so wait before potentially requesting Pocket data.
+ if (!visible) {
+ return (
+ <IntersectionObserver
+ windowObj={windowObj}
+ onIntersecting={onIntersecting}
+ />
+ );
+ }
+
+ // Intersection observer has finished, but we're not yet logged in.
+ if (visible && !isUserLoggedIn) {
+ return null;
+ }
+
+ let queryParams = `?utm_source=${utmSource}`;
+ // We really only need to add these params to urls we own.
+ if (utmCampaign && utmContent) {
+ queryParams += `&utm_content=${utmContent}&utm_campaign=${utmCampaign}`;
+ }
+
+ function renderCard(rec, index) {
+ const url = new URL(rec.url);
+ const urlSearchParams = new URLSearchParams(queryParams);
+ if (rec?.id && !url.href.match(/getpocket\.com\/read/)) {
+ url.href = `https://getpocket.com/read/${rec.id}`;
+ }
+
+ for (let [key, val] of urlSearchParams.entries()) {
+ url.searchParams.set(key, val);
+ }
+
+ return (
+ <DSCard
+ key={`dscard-${rec?.id || index}`}
+ id={rec.id}
+ pos={index}
+ type={source}
+ image_src={rec.image_src}
+ raw_image_src={rec.raw_image_src}
+ word_count={rec.word_count}
+ time_to_read={rec.time_to_read}
+ title={rec.title}
+ excerpt={rec.excerpt}
+ url={url.href}
+ source={rec.domain}
+ isRecentSave={true}
+ dispatch={dispatch}
+ />
+ );
+ }
+
+ function onMyListClicked() {
+ dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: `${source}_VIEW_LIST`,
+ })
+ );
+ }
+
+ const recentSavesCards = [];
+ // We fill the cards with a for loop over an inline map because
+ // we want empty placeholders if there are not enough cards.
+ for (let index = 0; index < items; index++) {
+ const recentSave = recentSavesData[index];
+ if (!recentSave) {
+ recentSavesCards.push(<PlaceholderDSCard key={`dscard-${index}`} />);
+ } else {
+ recentSavesCards.push(
+ renderCard(
+ {
+ id: recentSave.id,
+ image_src: recentSave.top_image_url,
+ raw_image_src: recentSave.top_image_url,
+ word_count: recentSave.word_count,
+ time_to_read: recentSave.time_to_read,
+ title: recentSave.resolved_title || recentSave.given_title,
+ url: recentSave.resolved_url || recentSave.given_url,
+ domain: recentSave.domain_metadata?.name,
+ excerpt: recentSave.excerpt,
+ },
+ index
+ )
+ );
+ }
+ }
+
+ // We are visible and logged in.
+ return (
+ <>
+ <DSSubHeader>
+ <span className="section-title">
+ <FluentOrText message="Recently Saved to your List" />
+ </span>
+ <SafeAnchor
+ onLinkClick={onMyListClicked}
+ className="section-sub-link"
+ url={`https://getpocket.com/a${queryParams}`}
+ >
+ <FluentOrText message="View My List" />
+ </SafeAnchor>
+ </DSSubHeader>
+ <div className={`ds-card-grid-recent-saves ${gridClassName}`}>
+ {recentSavesCards}
+ </div>
+ </>
+ );
+}
+
+export class _CardGrid extends React.PureComponent {
+ renderCards() {
+ const prefs = this.props.Prefs.values;
+ const {
+ items,
+ hybridLayout,
+ hideCardBackground,
+ fourCardLayout,
+ compactGrid,
+ essentialReadsHeader,
+ editorsPicksHeader,
+ onboardingExperience,
+ widgets,
+ recentSavesEnabled,
+ hideDescriptions,
+ DiscoveryStream,
+ } = this.props;
+ const { saveToPocketCard } = DiscoveryStream;
+ const showRecentSaves = prefs.showRecentSaves && recentSavesEnabled;
+ const isOnboardingExperienceDismissed =
+ prefs[PREF_ONBOARDING_EXPERIENCE_DISMISSED];
+
+ const recs = this.props.data.recommendations.slice(0, items);
+ const cards = [];
+ let essentialReadsCards = [];
+ let editorsPicksCards = [];
+
+ for (let index = 0; index < 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}
+ word_count={rec.word_count}
+ time_to_read={rec.time_to_read}
+ 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}
+ is_collection={this.props.is_collection}
+ saveToPocketCard={saveToPocketCard}
+ />
+ )
+ );
+ }
+
+ if (widgets?.positions?.length && widgets?.data?.length) {
+ let positionIndex = 0;
+ const source = "CARDGRID_WIDGET";
+
+ for (const widget of widgets.data) {
+ let widgetComponent = null;
+ const position = widgets.positions[positionIndex];
+
+ // Stop if we run out of positions to place widgets.
+ if (!position) {
+ break;
+ }
+
+ switch (widget?.type) {
+ case "TopicsWidget":
+ widgetComponent = (
+ <TopicsWidget
+ position={position.index}
+ dispatch={this.props.dispatch}
+ source={source}
+ id={WIDGET_IDS.TOPICS}
+ />
+ );
+ break;
+ }
+
+ if (widgetComponent) {
+ // We found a widget, so up the position for next try.
+ positionIndex++;
+ // We replace an existing card with the widget.
+ cards.splice(position.index, 1, widgetComponent);
+ }
+ }
+ }
+
+ let moreRecsHeader = "";
+ // For now this is English only.
+ if (showRecentSaves || (essentialReadsHeader && editorsPicksHeader)) {
+ let spliceAt = 6;
+ // For 4 card row layouts, second row is 8 cards, and regular it is 6 cards.
+ if (fourCardLayout) {
+ spliceAt = 8;
+ }
+ // If we have a custom header, ensure the more recs section also has a header.
+ moreRecsHeader = "More Recommendations";
+ // Put the first 2 rows into essentialReadsCards.
+ essentialReadsCards = [...cards.splice(0, spliceAt)];
+ // Put the rest into editorsPicksCards.
+ if (essentialReadsHeader && editorsPicksHeader) {
+ editorsPicksCards = [...cards.splice(0, cards.length)];
+ }
+ }
+
+ const hideCardBackgroundClass = hideCardBackground
+ ? `ds-card-grid-hide-background`
+ : ``;
+ const fourCardLayoutClass = fourCardLayout
+ ? `ds-card-grid-four-card-variant`
+ : ``;
+ const hideDescriptionsClassName = !hideDescriptions
+ ? `ds-card-grid-include-descriptions`
+ : ``;
+ const compactGridClassName = compactGrid ? `ds-card-grid-compact` : ``;
+ const hybridLayoutClassName = hybridLayout
+ ? `ds-card-grid-hybrid-layout`
+ : ``;
+
+ const gridClassName = `ds-card-grid ${hybridLayoutClassName} ${hideCardBackgroundClass} ${fourCardLayoutClass} ${hideDescriptionsClassName} ${compactGridClassName}`;
+
+ return (
+ <>
+ {!isOnboardingExperienceDismissed && onboardingExperience && (
+ <OnboardingExperience dispatch={this.props.dispatch} />
+ )}
+ {essentialReadsCards?.length > 0 && (
+ <div className={gridClassName}>{essentialReadsCards}</div>
+ )}
+ {showRecentSaves && (
+ <RecentSavesContainer
+ gridClassName={gridClassName}
+ dispatch={this.props.dispatch}
+ />
+ )}
+ {editorsPicksCards?.length > 0 && (
+ <>
+ <DSSubHeader>
+ <span className="section-title">
+ <FluentOrText message="Editor’s Picks" />
+ </span>
+ </DSSubHeader>
+ <div className={gridClassName}>{editorsPicksCards}</div>
+ </>
+ )}
+ {cards?.length > 0 && (
+ <>
+ {moreRecsHeader && (
+ <DSSubHeader>
+ <span className="section-title">
+ <FluentOrText message={moreRecsHeader} />
+ </span>
+ </DSSubHeader>
+ )}
+ <div className={gridClassName}>{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 = {
+ items: 4, // Number of stories to display
+};
+
+export const CardGrid = connect(state => ({
+ Prefs: state.Prefs,
+ DiscoveryStream: state.DiscoveryStream,
+}))(_CardGrid);
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..fb838f4628
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss
@@ -0,0 +1,355 @@
+$col4-header-line-height: 20;
+$col4-header-font-size: 14;
+
+.ds-onboarding-container,
+.ds-card-grid .ds-card {
+ @include dark-theme-only {
+ background: none;
+ }
+
+ background: $white;
+ border-radius: 4px;
+
+ &:not(.placeholder) {
+ @include dark-theme-only {
+ background: var(--newtab-background-color-secondary);
+ }
+
+ border-radius: $border-radius-new;
+ box-shadow: $shadow-card;
+
+ .img-wrapper .img {
+ img,
+ .placeholder-image {
+ border-radius: $border-radius-new $border-radius-new 0 0;
+ }
+ }
+ }
+}
+
+.ds-onboarding-container {
+ padding-inline-start: 16px;
+ padding-inline-end: 16px;
+
+ @media (min-width: $break-point-medium) {
+ padding-inline-end: 48px;
+ }
+
+ @media (min-width: $break-point-large) {
+ padding-inline-end: 56px;
+ }
+
+ margin-bottom: 24px;
+ // This is to position the dismiss button to the right most of this element.
+ position: relative;
+
+ .ds-onboarding {
+ position: static;
+ display: flex;
+
+ .ds-dismiss-button {
+ inset-inline-end: 8px;
+ top: 8px;
+ }
+ }
+
+ header {
+ @include dark-theme-only {
+ color: var(--newtab-background-color-primary);
+ }
+
+ display: flex;
+ margin: 32px 0 8px;
+
+ @media (min-width: $break-point-medium) {
+ margin: 16px 0 8px;
+ display: block;
+ height: 24px;
+ }
+
+ font-size: 17px;
+ line-height: 23.8px;
+ font-weight: 600;
+ color: $pocket-icon-fill;
+ }
+
+ p {
+ margin: 8px 0 16px;
+ font-size: 13px;
+ line-height: 19.5px;
+ }
+
+ .icon-pocket {
+ @include dark-theme-only {
+ @media (forced-colors: active) {
+ fill: CurrentColor;
+ }
+ fill: var(--newtab-text-primary-color);
+ }
+ @media (forced-colors: active) {
+ fill: CurrentColor;
+ }
+
+ fill: $pocket-icon-fill;
+ margin-top: 3px;
+ margin-inline-end: 8px;
+ height: 22px;
+ width: 22px;
+ background-image: url('chrome://global/skin/icons/pocket.svg');
+
+ @media (min-width: $break-point-medium) {
+ margin-top: -5px;
+ margin-inline-start: -2px;
+ margin-inline-end: 15px;
+ height: 30px;
+ width: 30px;
+ }
+
+ background-size: contain;
+ }
+
+ .ds-onboarding-graphic {
+ background-image: url('chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif');
+
+ @media (min-resolution: 2x) {
+ background-image: url('chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif');
+ }
+
+ border-radius: 8px;
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: center;
+ height: 120px;
+ width: 200px;
+ margin-top: 16px;
+ margin-bottom: 16px;
+ margin-inline-start: 54px;
+ flex-shrink: 0;
+ display: none;
+
+ @media (min-width: $break-point-large) {
+ display: block;
+ }
+ }
+}
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px;
+
+ &.ds-card-grid-compact {
+ grid-gap: 20px;
+ }
+
+ &.ds-card-grid-recent-saves {
+ .ds-card {
+ // Hide the second row orphan on narrow screens.
+ @media (min-width: $break-point-medium) and (max-width: $break-point-large) {
+ &:last-child:nth-child(2n - 1) {
+ display: none;
+ }
+ }
+ }
+ }
+
+ .ds-card-link:focus {
+ @include ds-focus;
+
+ transition: none;
+ border-radius: $border-radius-new;
+ }
+
+ // "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;
+ }
+
+ @mixin small-cards {
+ .ds-card {
+ &.placeholder {
+ min-height: 247px;
+ }
+
+ .meta {
+ .story-footer {
+ margin-top: 8px;
+ }
+
+ .source,
+ .story-sponsored-label,
+ .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+
+ .source,
+ .story-sponsored-label {
+ font-size: 13px;
+ }
+
+ .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+
+ .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+
+ .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+
+ .info-wrap {
+ flex-grow: 0;
+ }
+ }
+ }
+ }
+
+ &.ds-card-grid-four-card-variant {
+ // "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);
+ }
+
+ @media (min-width: $break-point-widest) {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ }
+
+ @include small-cards;
+ }
+
+ &.ds-card-grid-hybrid-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);
+ }
+
+ @media (max-height: 1065px) {
+ .excerpt {
+ display: none;
+ }
+ }
+
+ @media (max-width: $break-point-widest) {
+ @include small-cards;
+ }
+
+ @media (min-width: $break-point-widest) and (max-height: 964px) {
+ @include small-cards;
+
+ grid-template-columns: repeat(4, 1fr);
+ }
+ }
+ }
+}
+
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card {
+ &:not(.placeholder) {
+ box-shadow: none;
+ background: none;
+
+ .ds-card-link:focus {
+ box-shadow: none;
+
+ .img-wrapper .img img {
+ @include ds-focus;
+ }
+ }
+
+ .img-wrapper .img img {
+ border-radius: 8px;
+ box-shadow: $shadow-card;
+ }
+
+ .meta {
+ padding: 12px 0 0;
+ }
+ }
+}
+
+.ds-layout {
+ .ds-sub-header {
+ margin-top: 24px;
+
+ .section-title-container {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ display: flex;
+ }
+
+ .section-sub-link {
+ color: var(--newtab-primary-action-background);
+ font-size: 14px;
+ line-height: 16px;
+ cursor: pointer;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ &:active {
+ color: var(--newtab-primary-element-active-color);
+ }
+ }
+ }
+}
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..d089a5c8ab
--- /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.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ event: userEvent,
+ source,
+ action_position: pos,
+ })
+ );
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const { data, dismissible, pocket_button_enabled } = 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
+ pocket_button_enabled={pocket_button_enabled}
+ title={title}
+ context={sponsoredByMessage}
+ data={recsData}
+ feed={feed}
+ 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..f4778f3b95
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/_CollectionCardGrid.scss
@@ -0,0 +1,38 @@
+.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 {
+ color: var(--newtab-text-primary-color);
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px;
+ }
+
+ .ds-context {
+ color: var(--newtab-text-secondary-color);
+ 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..561da8e2fa
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx
@@ -0,0 +1,491 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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,
+ SponsorLabel,
+ DSMessageFooter,
+} from "../DSContextFooter/DSContextFooter.jsx";
+import { FluentOrText } from "../../FluentOrText/FluentOrText.jsx";
+import { connect } from "react-redux";
+
+const READING_WPM = 220;
+
+/**
+ * READ TIME FROM WORD COUNT
+ * @param {int} wordCount number of words in an article
+ * @returns {int} number of words per minute in minutes
+ */
+export function readTimeFromWordCount(wordCount) {
+ if (!wordCount) return false;
+ return Math.ceil(parseInt(wordCount, 10) / READING_WPM);
+}
+
+export const DSSource = ({
+ source,
+ timeToRead,
+ newSponsoredLabel,
+ context,
+ sponsor,
+ sponsored_by_override,
+}) => {
+ // First try to display sponsored label or time to read here.
+ if (newSponsoredLabel) {
+ // If we can display something for spocs, do so.
+ if (sponsored_by_override || sponsor || context) {
+ return (
+ <SponsorLabel
+ context={context}
+ sponsor={sponsor}
+ sponsored_by_override={sponsored_by_override}
+ newSponsoredLabel="new-sponsored-label"
+ />
+ );
+ }
+ }
+
+ // If we are not a spoc, and can display a time to read value.
+ if (source && timeToRead) {
+ return (
+ <p className="source clamp time-to-read">
+ <FluentOrText
+ message={{
+ id: `newtab-label-source-read-time`,
+ values: { source, timeToRead },
+ }}
+ />
+ </p>
+ );
+ }
+
+ // Otherwise display a default source.
+ return <p className="source clamp">{source}</p>;
+};
+
+export const DefaultMeta = ({
+ source,
+ title,
+ excerpt,
+ timeToRead,
+ newSponsoredLabel,
+ context,
+ context_type,
+ sponsor,
+ sponsored_by_override,
+ saveToPocketCard,
+ isRecentSave,
+}) => (
+ <div className="meta">
+ <div className="info-wrap">
+ <DSSource
+ source={source}
+ timeToRead={timeToRead}
+ newSponsoredLabel={newSponsoredLabel}
+ context={context}
+ sponsor={sponsor}
+ sponsored_by_override={sponsored_by_override}
+ />
+ <header title={title} className="title clamp">
+ {title}
+ </header>
+ {excerpt && <p className="excerpt clamp">{excerpt}</p>}
+ </div>
+ {!newSponsoredLabel && (
+ <DSContextFooter
+ context_type={context_type}
+ context={context}
+ sponsor={sponsor}
+ sponsored_by_override={sponsored_by_override}
+ />
+ )}
+ {/* Sponsored label is normally in the way of any message.
+ newSponsoredLabel cards sponsored label is moved to just under the thumbnail,
+ so we can display both, so we specifically don't pass in context. */}
+ {newSponsoredLabel && (
+ <DSMessageFooter
+ context_type={context_type}
+ context={null}
+ saveToPocketCard={saveToPocketCard}
+ />
+ )}
+ </div>
+);
+
+export class _DSCard extends React.PureComponent {
+ constructor(props) {
+ super(props);
+
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onSaveClick = this.onSaveClick.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+
+ this.setContextMenuButtonHostRef = element => {
+ this.contextMenuButtonHostElement = element;
+ };
+ 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.DiscoveryStreamUserEvent({
+ 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,
+ window_inner_width: this.props.windowObj.innerWidth,
+ window_inner_height: this.props.windowObj.innerHeight,
+ tiles: [
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click
+ ? { shim: this.props.shim.click }
+ : {}),
+ type: this.props.flightId ? "spoc" : "organic",
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ onSaveClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(
+ ac.AlsoToMain({
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: this.props.url, title: this.props.title } },
+ })
+ );
+
+ this.props.dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ source: "CARDGRID_HOVER",
+ action_position: this.props.pos,
+ value: { card_type: this.props.flightId ? "spoc" : "organic" },
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: "CARDGRID_HOVER",
+ pocket: 0,
+ tiles: [
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.save
+ ? { shim: this.props.shim.save }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ onMenuUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ const dsLinkMenuHostDiv = this.contextMenuButtonHostElement;
+ if (dsLinkMenuHostDiv) {
+ dsLinkMenuHostDiv.classList.remove("active", "last-item");
+ }
+ }
+ }
+
+ async onMenuShow() {
+ const dsLinkMenuHostDiv = this.contextMenuButtonHostElement;
+ if (dsLinkMenuHostDiv) {
+ // Force translation so we can be sure it's ready before measuring.
+ await this.props.windowObj.document.l10n.translateFragment(
+ dsLinkMenuHostDiv
+ );
+ if (this.props.windowObj.scrollMaxX > 0) {
+ dsLinkMenuHostDiv.classList.add("last-item");
+ }
+ dsLinkMenuHostDiv.classList.add("active");
+ }
+ }
+
+ 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 { isRecentSave, DiscoveryStream, saveToPocketCard } = this.props;
+ let { source } = this.props;
+ if (!source) {
+ try {
+ source = new URL(this.props.url).hostname;
+ } catch (e) {}
+ }
+
+ const {
+ pocketButtonEnabled,
+ hideDescriptions,
+ compactImages,
+ imageGradient,
+ newSponsoredLabel,
+ titleLines = 3,
+ descLines = 3,
+ readTime: displayReadTime,
+ } = DiscoveryStream;
+
+ const excerpt = !hideDescriptions ? this.props.excerpt : "";
+
+ let timeToRead;
+ if (displayReadTime) {
+ timeToRead =
+ this.props.time_to_read || readTimeFromWordCount(this.props.word_count);
+ }
+
+ const compactImagesClassName = compactImages ? `ds-card-compact-image` : ``;
+ const imageGradientClassName = imageGradient
+ ? `ds-card-image-gradient`
+ : ``;
+ const titleLinesName = `ds-card-title-lines-${titleLines}`;
+ const descLinesClassName = `ds-card-desc-lines-${descLines}`;
+
+ let stpButton = () => {
+ return (
+ <button className="card-stp-button" onClick={this.onSaveClick}>
+ {this.props.context_type === "pocket" ? (
+ <>
+ <span className="story-badge-icon icon icon-pocket" />
+ <span data-l10n-id="newtab-pocket-saved" />
+ </>
+ ) : (
+ <>
+ <span className="story-badge-icon icon icon-pocket-save" />
+ <span data-l10n-id="newtab-pocket-save" />
+ </>
+ )}
+ </button>
+ );
+ };
+
+ return (
+ <div
+ className={`ds-card ${compactImagesClassName} ${imageGradientClassName} ${titleLinesName} ${descLinesClassName}`}
+ ref={this.setContextMenuButtonHostRef}
+ >
+ <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}
+ url={this.props.url}
+ title={this.props.title}
+ isRecentSave={isRecentSave}
+ />
+ </div>
+ <DefaultMeta
+ source={source}
+ title={this.props.title}
+ excerpt={excerpt}
+ newSponsoredLabel={newSponsoredLabel}
+ timeToRead={timeToRead}
+ context={this.props.context}
+ context_type={this.props.context_type}
+ sponsor={this.props.sponsor}
+ sponsored_by_override={this.props.sponsored_by_override}
+ saveToPocketCard={saveToPocketCard}
+ />
+ <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>
+ {saveToPocketCard && (
+ <div className="card-stp-button-hover-background">
+ <div className="card-stp-button-position-wrapper">
+ {!this.props.flightId && stpButton()}
+ <DSLinkMenu
+ id={this.props.id}
+ index={this.props.pos}
+ dispatch={this.props.dispatch}
+ url={this.props.url}
+ title={this.props.title}
+ source={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}
+ onMenuUpdate={this.onMenuUpdate}
+ onMenuShow={this.onMenuShow}
+ saveToPocketCard={saveToPocketCard}
+ pocket_button_enabled={pocketButtonEnabled}
+ isRecentSave={isRecentSave}
+ />
+ </div>
+ </div>
+ )}
+ {!saveToPocketCard && (
+ <DSLinkMenu
+ id={this.props.id}
+ index={this.props.pos}
+ dispatch={this.props.dispatch}
+ url={this.props.url}
+ title={this.props.title}
+ source={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}
+ hostRef={this.contextMenuButtonHostRef}
+ onMenuUpdate={this.onMenuUpdate}
+ onMenuShow={this.onMenuShow}
+ pocket_button_enabled={pocketButtonEnabled}
+ isRecentSave={isRecentSave}
+ />
+ )}
+ </div>
+ );
+ }
+}
+
+_DSCard.defaultProps = {
+ windowObj: window, // Added to support unit tests
+};
+
+export const DSCard = connect(state => ({
+ App: state.App,
+ DiscoveryStream: state.DiscoveryStream,
+}))(_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..a29087a5df
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss
@@ -0,0 +1,251 @@
+// Type sizes
+$header-font-size: 17;
+$header-line-height: 24;
+$excerpt-font-size: 14;
+$excerpt-line-height: 20;
+$ds-card-image-gradient-fade: rgba(0, 0, 0, 0%);
+$ds-card-image-gradient-solid: rgba(0, 0, 0, 100%);
+
+.ds-card {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+
+ &.placeholder {
+ background: transparent;
+ box-shadow: inset $inner-box-shadow;
+ border-radius: 4px;
+ min-height: 300px;
+ }
+
+ .img-wrapper {
+ width: 100%;
+ position: relative;
+ }
+
+ .card-stp-button-hover-background {
+ opacity: 0;
+ width: 100%;
+ position: absolute;
+ top: 0;
+ height: 0;
+ transition: opacity;
+ transition-duration: 0s;
+ padding-top: 50%;
+ pointer-events: none;
+ background: $black-40;
+ border-radius: 8px 8px 0 0;
+
+ .card-stp-button-position-wrapper {
+ position: absolute;
+ inset-inline-end: 10px;
+ top: 10px;
+ display: flex;
+ justify-content: end;
+ align-items: center;
+ }
+
+ .icon-pocket-save,
+ .icon-pocket {
+ margin-inline-end: 4px;
+ height: 15px;
+ width: 15px;
+ background-size: 15px;
+ fill: $white;
+ }
+
+ .context-menu-button {
+ position: static;
+ transition: none;
+ border-radius: 3px;
+ }
+
+ .context-menu-position-container {
+ position: relative;
+ }
+
+ .context-menu {
+ margin-inline-start: 18.5px;
+ inset-inline-start: auto;
+ position: absolute;
+ top: 20.25px;
+ }
+
+ .card-stp-button {
+ display: flex;
+ margin-inline-end: 7px;
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 16px;
+ background-color: $pocket-icon-fill;
+ border: 0;
+ border-radius: 4px;
+ padding: 6px;
+ white-space: nowrap;
+ color: $white;
+ }
+
+ button,
+ .context-menu {
+ pointer-events: auto;
+ }
+
+ button {
+ cursor: pointer;
+ }
+ }
+
+ &.last-item {
+ .card-stp-button-hover-background {
+ .context-menu {
+ margin-inline-start: auto;
+ margin-inline-end: 18.5px;
+ }
+ }
+ }
+
+ // The active class is added when the context menu is open.
+ &.active,
+ &:focus-within,
+ &:hover {
+ .card-stp-button-hover-background {
+ display: block;
+ opacity: 1;
+ transition-duration: 0.3s;
+
+ .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ }
+ }
+ }
+
+ .img {
+ height: 0;
+ padding-top: 50%; // 2:1 aspect ratio
+
+ img {
+ border-radius: 4px;
+ box-shadow: $shadow-image-inset;
+ }
+ }
+
+ .ds-card-link {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ text-decoration: none;
+
+ &:hover {
+ header {
+ color: var(--newtab-primary-action-background);
+ }
+ }
+
+ &:focus {
+ @include ds-focus;
+
+ transition: none;
+
+ header {
+ color: var(--newtab-primary-action-background);
+ }
+ }
+
+ &:active {
+ header {
+ color: var(--newtab-primary-element-active-color);
+ }
+ }
+ }
+
+ .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 {
+ -webkit-line-clamp: 1;
+ margin-bottom: 2px;
+ font-size: 13px;
+ color: var(--newtab-text-secondary-color);
+
+ span {
+ display: inline-block;
+ }
+ }
+
+ .new-sponsored-label {
+ font-size: 13px;
+ margin-bottom: 2px;
+ }
+ }
+
+ &.ds-card-title-lines-2 .meta .title {
+ // show only 2 lines of copy
+ @include limit-visible-lines(2, $header-line-height, $header-font-size);
+ }
+
+ &.ds-card-title-lines-1 .meta .title {
+ // show only 1 line of copy
+ @include limit-visible-lines(1, $header-line-height, $header-font-size);
+ }
+
+ &.ds-card-desc-lines-2 .meta .excerpt {
+ // show only 2 lines of copy
+ @include limit-visible-lines(2, $excerpt-line-height, $excerpt-font-size);
+ }
+
+ &.ds-card-desc-lines-1 .meta .excerpt {
+ // show only 1 line of copy
+ @include limit-visible-lines(1, $excerpt-line-height, $excerpt-font-size);
+ }
+
+ &.ds-card-compact-image .img {
+ padding-top: 47%;
+ }
+
+ &.ds-card-image-gradient {
+ img {
+ mask-image: linear-gradient(to top, $ds-card-image-gradient-fade, $ds-card-image-gradient-solid 40px);
+ }
+
+ .meta {
+ padding: 3px 15px 11px;
+ }
+ }
+
+ header {
+ line-height: $header-line-height * 1px;
+ font-size: $header-font-size * 1px;
+ color: var(--newtab-text-primary-color);
+ }
+
+ p {
+ font-size: $excerpt-font-size * 1px;
+ line-height: $excerpt-line-height * 1px;
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+ }
+}
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..0d7d4f666e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx
@@ -0,0 +1,118 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 DSMessageLabel = props => {
+ const { context, context_type } = props;
+ const { icon, fluentID } = cardContextTypes[context_type] || {};
+
+ if (!context && context_type) {
+ return (
+ <TransitionGroup component={null}>
+ <CSSTransition
+ key={fluentID}
+ timeout={ANIMATION_DURATION}
+ classNames="story-animate"
+ >
+ <StatusMessage icon={icon} fluentID={fluentID} />
+ </CSSTransition>
+ </TransitionGroup>
+ );
+ }
+
+ return null;
+};
+
+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,
+ newSponsoredLabel,
+}) => {
+ const classList = `story-sponsored-label ${newSponsoredLabel || ""} 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() {
+ const { context, context_type, sponsor, sponsored_by_override } =
+ this.props;
+
+ const sponsorLabel = SponsorLabel({
+ sponsored_by_override,
+ sponsor,
+ context,
+ });
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type,
+ });
+
+ if (sponsorLabel || dsMessageLabel) {
+ return (
+ <div className="story-footer">
+ {sponsorLabel}
+ {dsMessageLabel}
+ </div>
+ );
+ }
+
+ return null;
+ }
+}
+
+export const DSMessageFooter = props => {
+ const { context, context_type, saveToPocketCard } = props;
+
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type,
+ });
+
+ // This case is specific and already displayed to the user elsewhere.
+ if (!dsMessageLabel || (saveToPocketCard && context_type === "pocket")) {
+ return null;
+ }
+
+ return <div className="story-footer">{dsMessageLabel}</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..c23bb1c661
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss
@@ -0,0 +1,81 @@
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative;
+
+ .story-sponsored-label span {
+ display: inline-block;
+ }
+
+ .story-sponsored-label,
+ .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: var(--newtab-text-secondary-color);
+ }
+
+ .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px;
+
+ .story-badge-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 16px;
+ margin-inline-end: 6px;
+
+ &.icon-bookmark-removed {
+ background-image: url('#{$image-path}icon-removed-bookmark.svg');
+ }
+ }
+
+ .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ 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 {
+ animation: color 3s ease-out 0.3s;
+
+ @keyframes color {
+ 0% {
+ color: var(--newtab-status-success);
+ fill: var(--newtab-status-success);
+ }
+
+ 100% {
+ color: var(--newtab-text-secondary-color);
+ fill: var(--newtab-text-secondary-color);
+ }
+ }
+ }
+}
+
+.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..3c736a24ad
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss
@@ -0,0 +1,47 @@
+.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 {
+ @media (forced-colors: active) {
+ fill: CurrentColor;
+ }
+ fill: var(--newtab-text-primary-color);
+ }
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &:active {
+ background: var(--newtab-element-active-color);
+ }
+
+ &:focus {
+ box-shadow: $shadow-secondary;
+ }
+ }
+}
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..ff3886b407
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.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 {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..9f9accf71b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss
@@ -0,0 +1,83 @@
+.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-button-secondary-color);
+ color: var(--newtab-text-primary-color);
+ 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(var(--newtab-element-secondary-color));
+ }
+ }
+
+ &::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-text-secondary-color);
+ }
+
+ &.waiting {
+ cursor: initial;
+ background: var(--newtab-element-secondary-color);
+ color: transparent;
+ 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..8a6cefed3a
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx
@@ -0,0 +1,263 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 PLACEHOLDER_IMAGE_DATA_ARRAY = [
+ {
+ rotation: "0deg",
+ offsetx: "20px",
+ offsety: "8px",
+ scale: "45%",
+ },
+ {
+ rotation: "54deg",
+ offsetx: "-26px",
+ offsety: "62px",
+ scale: "55%",
+ },
+ {
+ rotation: "-30deg",
+ offsetx: "78px",
+ offsety: "30px",
+ scale: "68%",
+ },
+ {
+ rotation: "-22deg",
+ offsetx: "0",
+ offsety: "92px",
+ scale: "60%",
+ },
+ {
+ rotation: "-65deg",
+ offsetx: "66px",
+ offsety: "28px",
+ scale: "60%",
+ },
+ {
+ rotation: "22deg",
+ offsetx: "-35px",
+ offsety: "62px",
+ scale: "52%",
+ },
+ {
+ rotation: "-25deg",
+ offsetx: "86px",
+ offsety: "-15px",
+ scale: "68%",
+ },
+];
+
+const PLACEHOLDER_IMAGE_COLORS_ARRAY =
+ "#0090ED #FF4F5F #2AC3A2 #FF7139 #A172FF #FFA437 #FF2A8A".split(" ");
+
+function generateIndex({ keyCode, max }) {
+ if (!keyCode) {
+ // Just grab a random index if we cannot generate an index from a key.
+ return Math.floor(Math.random() * max);
+ }
+
+ const hashStr = str => {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ let charCode = str.charCodeAt(i);
+ hash += charCode;
+ }
+ return hash;
+ };
+
+ const hash = hashStr(keyCode);
+ return hash % max;
+}
+
+export function PlaceholderImage({ urlKey, titleKey }) {
+ const dataIndex = generateIndex({
+ keyCode: urlKey,
+ max: PLACEHOLDER_IMAGE_DATA_ARRAY.length,
+ });
+ const colorIndex = generateIndex({
+ keyCode: titleKey,
+ max: PLACEHOLDER_IMAGE_COLORS_ARRAY.length,
+ });
+ const { rotation, offsetx, offsety, scale } =
+ PLACEHOLDER_IMAGE_DATA_ARRAY[dataIndex];
+ const color = PLACEHOLDER_IMAGE_COLORS_ARRAY[colorIndex];
+ const style = {
+ "--placeholderBackgroundColor": color,
+ "--placeholderBackgroundRotation": rotation,
+ "--placeholderBackgroundOffsetx": offsetx,
+ "--placeholderBackgroundOffsety": offsety,
+ "--placeholderBackgroundScale": scale,
+ };
+
+ return <div style={style} className="placeholder-image" />;
+}
+
+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.props.source && !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 {
+ // We consider a failed to load img or source without an image as loaded.
+ classNames = `${classNames} loaded`;
+ // Remove the img element if we have no source. Render a placeholder instead.
+ // This only happens for recent saves without a source.
+ if (
+ this.props.isRecentSave &&
+ !this.props.rawSource &&
+ !this.props.source
+ ) {
+ img = (
+ <PlaceholderImage
+ urlKey={this.props.url}
+ titleKey={this.props.title}
+ />
+ );
+ } else {
+ 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..b11bcdcf55
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss
@@ -0,0 +1,48 @@
+.ds-image {
+ display: block;
+ position: relative;
+ opacity: 0;
+
+ &.use-transition {
+ transition: opacity 0.8s;
+ }
+
+ &.loaded {
+ opacity: 1;
+ }
+
+ img,
+ .placeholder-image,
+ .broken-image {
+ background-color: var(--newtab-element-secondary-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+
+ .placeholder-image {
+ overflow: hidden;
+ background-color: var(--placeholderBackgroundColor);
+
+ &::before {
+ content: '';
+ background-image: url('chrome://activity-stream/content/data/content/assets/pocket-swoosh.svg');
+ background-repeat: no-repeat;
+ background-position: center;
+ transform: rotate(var(--placeholderBackgroundRotation));
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ // We use margin-left over margin-inline-start on purpose.
+ // This is because we are using it to offset an image's content,
+ // and the image content is the same in ltr and rtl.
+ margin-left: var(--placeholderBackgroundOffsetx); // stylelint-disable-line property-disallowed-list
+ margin-top: var(--placeholderBackgroundOffsety);
+ background-size: var(--placeholderBackgroundScale);
+ }
+ }
+}
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..b75063940c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx
@@ -0,0 +1,70 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { actionCreators as ac } from "common/Actions.sys.mjs";
+import React from "react";
+
+export class DSLinkMenu extends React.PureComponent {
+ render() {
+ const { index, dispatch } = this.props;
+ let pocketMenuOptions = [];
+ let TOP_STORIES_CONTEXT_MENU_OPTIONS = [
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ ];
+ if (!this.props.isRecentSave) {
+ if (this.props.pocket_button_enabled) {
+ pocketMenuOptions = this.props.saveToPocketCard
+ ? ["CheckDeleteFromPocket"]
+ : ["CheckSavedToPocket"];
+ }
+ TOP_STORIES_CONTEXT_MENU_OPTIONS = [
+ "CheckBookmark",
+ "CheckArchiveFromPocket",
+ ...pocketMenuOptions,
+ "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 className="context-menu-position-container">
+ <ContextMenuButton
+ tooltip={"newtab-menu-content-tooltip"}
+ tooltipArgs={{ title }}
+ onUpdate={this.props.onMenuUpdate}
+ >
+ <LinkMenu
+ dispatch={dispatch}
+ index={index}
+ source={type.toUpperCase()}
+ onShow={this.props.onMenuShow}
+ options={TOP_STORIES_CONTEXT_MENU_OPTIONS}
+ shouldSendImpressionStats={true}
+ userEvent={ac.DiscoveryStreamUserEvent}
+ 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>
+ );
+ }
+}
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..e85eab11e7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss
@@ -0,0 +1,28 @@
+.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;
+ }
+}
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..bb9666ae38
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/_DSMessage.scss
@@ -0,0 +1,37 @@
+.ds-message {
+ margin: 8px 0 0;
+
+ .title {
+ display: flex;
+ align-items: center;
+
+ .glyph {
+ width: 16px;
+ height: 16px;
+ margin: 0 6px 0 0;
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-secondary-color);
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat;
+ }
+
+ .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: var(--newtab-text-secondary-color);
+ 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..06ec1f7e78
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.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";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ 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..2077f35709
--- /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: var(--newtab-primary-action-background);
+ width: max-content;
+
+ &:hover {
+ text-decoration: underline;
+ cursor: pointer;
+ }
+
+ &::before {
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-action-background);
+ 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://global/skin/icons/info.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..b7e3205646
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.jsx
@@ -0,0 +1,168 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ 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}
+ userEvent={ac.DiscoveryStreamUserEvent}
+ 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..dcaf0e804a
--- /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: var(--newtab-text-secondary-color);
+ 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..02a3326eb7
--- /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.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ 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.DiscoveryStreamUserEvent({
+ 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..b0abea1213
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/_DSTextPromo.scss
@@ -0,0 +1,92 @@
+.ds-dismiss-ds-text-promo {
+ max-width: 744px;
+ margin: auto;
+ overflow: hidden;
+
+ &.hovering {
+ background: var(--newtab-element-hover-color);
+ }
+
+ .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 {
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px;
+ }
+
+ .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: var(--newtab-text-primary-color);
+ }
+}
+
+.ds-chevron-link {
+ color: var(--newtab-primary-action-background);
+ display: inline-block;
+ outline: 0;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ &:active {
+ color: var(--newtab-primary-element-active-color);
+
+ &::after {
+ background-color: var(--newtab-primary-element-active-color);
+ }
+ }
+
+ &:focus {
+ box-shadow: $shadow-secondary;
+ border-radius: 2px;
+ }
+
+ &::after {
+ background-color: var(--newtab-primary-action-background);
+ content: ' ';
+ mask: url('chrome://global/skin/icons/arrow-right-12.svg') 0 -8px no-repeat;
+ 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/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..3c5b60e946
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss
@@ -0,0 +1,45 @@
+.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;
+ }
+
+ .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: $line-height;
+ max-height: $line-height;
+ }
+
+ a {
+ text-decoration: none;
+ }
+ }
+ }
+ }
+
+ .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/Navigation/Navigation.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx
new file mode 100644
index 0000000000..1062c3cade
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx
@@ -0,0 +1,112 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ 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() {
+ let links = this.props.links || [];
+ const alignment = this.props.alignment || "centered";
+ const header = this.props.header || {};
+ const english = this.props.locale.startsWith("en-");
+ const privacyNotice = this.props.privacyNoticeURL || {};
+ const { newFooterSection } = this.props;
+ const className = `ds-navigation ds-navigation-${alignment} ${
+ newFooterSection ? `ds-navigation-new-topics` : ``
+ }`;
+ let { title } = header;
+ if (newFooterSection) {
+ title = { id: "newtab-pocket-new-topics-title" };
+ if (this.props.extraLinks) {
+ links = [
+ ...links.slice(0, links.length - 1),
+ ...this.props.extraLinks,
+ links[links.length - 1],
+ ];
+ }
+ }
+
+ return (
+ <div className={className}>
+ {title && english ? (
+ <FluentOrText message={title}>
+ <span className="ds-navigation-header" />
+ </FluentOrText>
+ ) : null}
+
+ {english ? (
+ <ul>
+ {links &&
+ links.map(t => (
+ <li key={t.name}>
+ <Topic
+ url={t.url}
+ name={t.name}
+ dispatch={this.props.dispatch}
+ />
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {!newFooterSection ? (
+ <SafeAnchor className="ds-navigation-privacy" url={privacyNotice.url}>
+ <FluentOrText message={privacyNotice.title} />
+ </SafeAnchor>
+ ) : null}
+
+ {newFooterSection ? (
+ <div className="ds-navigation-family">
+ <span className="icon firefox-logo" />
+ <span>|</span>
+ <span className="icon pocket-logo" />
+ <span
+ className="ds-navigation-family-message"
+ data-l10n-id="newtab-pocket-pocket-firefox-family"
+ />
+ </div>
+ ) : null}
+ </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..f9b5e5c704
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss
@@ -0,0 +1,180 @@
+.ds-navigation {
+ color: var(--newtab-text-primary-color);
+ font-size: 11.5px;
+ font-weight: 500;
+ line-height: 22px;
+ padding: 4px 0;
+
+ @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: none;
+ }
+
+ &:active {
+ color: var(--newtab-primary-element-active-color);
+ }
+ }
+ }
+
+ .ds-navigation-header {
+ padding-inline-end: 6px;
+ }
+
+ .ds-navigation-privacy {
+ padding-inline-start: 6px;
+ float: inline-end;
+
+ &:hover {
+ text-decoration: none;
+ }
+ }
+
+ &.ds-navigation-new-topics {
+ display: block;
+ padding-top: 32px;
+
+ .ds-navigation-header {
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: 700;
+ display: inline-block;
+ margin-bottom: 8px;
+ }
+
+ .ds-navigation-family {
+ text-align: center;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 16px auto 28px;
+
+ span {
+ margin: 0 6px;
+ }
+
+ .firefox-logo,
+ .pocket-logo {
+ height: 20px;
+ width: 20px;
+ background-size: cover;
+ }
+
+ .firefox-logo {
+ background-image: url('chrome://activity-stream/content/data/content/assets/firefox.svg');
+ }
+
+ .pocket-logo {
+ background-image: url('chrome://global/skin/icons/pocket.svg');
+ fill: $pocket-icon-fill;
+ }
+
+ .ds-navigation-family-message {
+ font-weight: 400;
+ display: block;
+
+ @media (min-width: $break-point-medium) {
+ display: inline;
+ }
+ }
+
+ @media (min-width: $break-point-medium) {
+ margin-top: 43px;
+ }
+ }
+
+ ul {
+ display: grid;
+ grid-gap: 0 24px;
+ grid-auto-flow: column;
+ grid-template: repeat(8, 1fr) / repeat(1, 1fr);
+
+ li {
+ border-top: $border-primary;
+ line-height: 24px;
+ font-size: 13px;
+ font-weight: 500;
+
+ &::after {
+ content: '';
+ padding: 0;
+ }
+
+ &:nth-last-child(2),
+ &:nth-last-child(3) {
+ display: none;
+ }
+
+ &:nth-last-child(1) {
+ border-bottom: $border-primary;
+ }
+ }
+
+ @media (min-width: $break-point-medium) {
+ grid-template: repeat(3, 1fr) / repeat(2, 1fr);
+
+ li {
+ &:nth-child(3) {
+ border-bottom: $border-primary;
+ }
+ }
+ }
+
+ @media (min-width: $break-point-large) {
+ grid-template: repeat(2, 1fr) / repeat(3, 1fr);
+
+
+ li {
+ &:nth-child(odd) {
+ border-bottom: 0;
+ }
+
+ &:nth-child(even) {
+ border-bottom: $border-primary;
+ }
+ }
+ }
+
+ @media (min-width: $break-point-widest) {
+ grid-template: repeat(2, 1fr) / repeat(4, 1fr);
+
+ li {
+ &:nth-last-child(2),
+ &:nth-last-child(3) {
+ display: block;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink.jsx
new file mode 100644
index 0000000000..8f7d88be85
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink.jsx
@@ -0,0 +1,20 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 PrivacyLink extends React.PureComponent {
+ render() {
+ const { properties } = this.props;
+ return (
+ <div className="ds-privacy-link">
+ <SafeAnchor url={properties.url}>
+ <FluentOrText message={properties.title} />
+ </SafeAnchor>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/_PrivacyLink.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/_PrivacyLink.scss
new file mode 100644
index 0000000000..08ce093c27
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/PrivacyLink/_PrivacyLink.scss
@@ -0,0 +1,10 @@
+.ds-privacy-link {
+ text-align: center;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 24px;
+
+ a:hover {
+ text-decoration: none;
+ }
+}
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..cfbc6fe6cb
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx
@@ -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/. */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..453001b1b7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/_SectionTitle.scss
@@ -0,0 +1,18 @@
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px;
+
+ .title {
+ color: var(--newtab-text-primary-color);
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+ }
+
+ .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 4px;
+ }
+}
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..e0c7c1a8eb
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss
@@ -0,0 +1,77 @@
+.outer-wrapper {
+ .ds-top-sites {
+ .top-sites {
+ .top-site-outer {
+ .top-site-inner > a:is(.active, :focus) .tile {
+ @include ds-focus;
+ }
+
+ .top-site-inner > a:is(:hover) .top-site-inner {
+ @include ds-fade-in(var(--newtab-background-color-secondary));
+ }
+ }
+
+ .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/DiscoveryStreamComponents/TopicsWidget/TopicsWidget.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget.jsx
new file mode 100644
index 0000000000..1fe2343b94
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget.jsx
@@ -0,0 +1,125 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import { connect } from "react-redux";
+
+export function _TopicsWidget(props) {
+ const { id, source, position, DiscoveryStream, dispatch } = props;
+
+ const { utmCampaign, utmContent, utmSource } = DiscoveryStream.experimentData;
+
+ let queryParams = `?utm_source=${utmSource}`;
+ if (utmCampaign && utmContent) {
+ queryParams += `&utm_content=${utmContent}&utm_campaign=${utmCampaign}`;
+ }
+
+ const topics = [
+ { label: "Technology", name: "technology" },
+ { label: "Science", name: "science" },
+ { label: "Self-Improvement", name: "self-improvement" },
+ { label: "Travel", name: "travel" },
+ { label: "Career", name: "career" },
+ { label: "Entertainment", name: "entertainment" },
+ { label: "Food", name: "food" },
+ { label: "Health", name: "health" },
+ {
+ label: "Must-Reads",
+ name: "must-reads",
+ url: `https://getpocket.com/collections${queryParams}`,
+ },
+ ];
+
+ function onLinkClick(topic, positionInCard) {
+ if (dispatch) {
+ dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source,
+ action_position: position,
+ value: {
+ card_type: "topics_widget",
+ topic,
+ ...(positionInCard || positionInCard === 0
+ ? { position_in_card: positionInCard }
+ : {}),
+ },
+ })
+ );
+ dispatch(
+ ac.ImpressionStats({
+ source,
+ click: 0,
+ window_inner_width: props.windowObj.innerWidth,
+ window_inner_height: props.windowObj.innerHeight,
+ tiles: [
+ {
+ id,
+ pos: position,
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ function mapTopicItem(topic, index) {
+ return (
+ <li
+ key={topic.name}
+ className={topic.overflow ? "ds-topics-widget-list-overflow-item" : ""}
+ >
+ <SafeAnchor
+ url={
+ topic.url ||
+ `https://getpocket.com/explore/${topic.name}${queryParams}`
+ }
+ dispatch={dispatch}
+ onLinkClick={() => onLinkClick(topic.name, index)}
+ >
+ {topic.label}
+ </SafeAnchor>
+ </li>
+ );
+ }
+
+ return (
+ <div className="ds-topics-widget">
+ <header className="ds-topics-widget-header">Popular Topics</header>
+ <hr />
+ <div className="ds-topics-widget-list-container">
+ <ul>{topics.map(mapTopicItem)}</ul>
+ </div>
+ <SafeAnchor
+ className="ds-topics-widget-button button primary"
+ url={`https://getpocket.com/${queryParams}`}
+ dispatch={dispatch}
+ onLinkClick={() => onLinkClick("more-topics")}
+ >
+ More Topics
+ </SafeAnchor>
+ <ImpressionStats
+ dispatch={dispatch}
+ rows={[
+ {
+ id,
+ pos: position,
+ },
+ ]}
+ source={source}
+ />
+ </div>
+ );
+}
+
+_TopicsWidget.defaultProps = {
+ windowObj: window, // Added to support unit tests
+};
+
+export const TopicsWidget = connect(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+}))(_TopicsWidget);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/_TopicsWidget.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/_TopicsWidget.scss
new file mode 100644
index 0000000000..d05d46cd07
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/_TopicsWidget.scss
@@ -0,0 +1,88 @@
+.ds-topics-widget {
+ display: flex;
+ position: relative;
+ flex-direction: column;
+
+ .ds-topics-widget-header {
+ font-size: 18px;
+ line-height: 20px;
+ }
+
+ hr {
+ background-color: color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ height: 1px;
+ border: 0;
+ margin: 10px 0 0;
+ }
+
+ .ds-topics-widget-list-container {
+ flex-grow: 1;
+
+ ul {
+ margin: 14px 0 0;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ grid-gap: 10px;
+ flex-wrap: wrap;
+
+ li {
+ display: flex;
+
+ a {
+ font-size: 14px;
+ line-height: 16px;
+ text-decoration: none;
+ padding: 8px 15px;
+ background: var(--newtab-background-color-secondary);
+ border: 1px solid color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ color: var(--newtab-text-primary-color);
+ border-radius: 8px;
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: box-shadow 150ms;
+ }
+ }
+ }
+
+ .ds-topics-widget-list-overflow-item {
+ display: flex;
+
+ @media (min-width: $break-point-medium) {
+ display: none;
+ }
+
+ @media (min-width: $break-point-widest) {
+ display: flex;
+ }
+ }
+ }
+ }
+
+ .ds-topics-widget-button {
+ margin: 14px 0 0;
+ font-size: 16px;
+ line-height: 24px;
+ text-align: center;
+ padding: 8px;
+ border-radius: 4px;
+ background-color: var(--newtab-primary-action-background-pocket);
+ border: 0;
+
+ &:hover {
+ background: var(--newtab-primary-element-hover-pocket-color);
+ }
+
+ &:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-pocket-dimmed), 0 0 0 1px var(--newtab-primary-action-background-pocket);
+ transition: box-shadow 150ms;
+ }
+ }
+}
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..b385c2ebf7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx
@@ -0,0 +1,250 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+import { TOP_SITES_SOURCE } from "../TopSites/TopSitesConstants";
+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 },
+ })
+ );
+
+ // Record sponsored topsites impressions if the source is `TOP_SITES_SOURCE`.
+ if (this.props.source === TOP_SITES_SOURCE) {
+ for (const card of cards) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "impression",
+ tile_id: card.id,
+ source: "newtab",
+ advertiser: card.advertiser,
+ // Keep the 0-based position, can be adjusted by the telemetry
+ // sender if necessary.
+ position: card.pos,
+ },
+ })
+ );
+ }
+ }
+ }
+
+ if (this._needsImpressionStats(cards)) {
+ props.dispatch(
+ ac.DiscoveryStreamImpressionStats({
+ source: props.source.toUpperCase(),
+ window_inner_width: window.innerWidth,
+ window_inner_height: window.innerHeight,
+ tiles: cards.map(link => ({
+ id: link.id,
+ pos: link.pos,
+ type: this.props.flightId ? "spoc" : "organic",
+ ...(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..cc54f78a27
--- /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-secondary-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-secondary-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..650a03eb95
--- /dev/null
+++ b/browser/components/newtab/content-src/components/LinkMenu/LinkMenu.jsx
@@ -0,0 +1,110 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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,
+ userEvent = ac.UserEvent,
+ } = 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: eventName } = 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 (eventName) {
+ const userEventData = Object.assign(
+ {
+ event: eventName,
+ source,
+ action_position: index,
+ value: { card_type: site.flight_id ? "spoc" : "organic" },
+ },
+ siteInfo
+ );
+ props.dispatch(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..12a66b7c11
--- /dev/null
+++ b/browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss
@@ -0,0 +1,24 @@
+@use 'sass:math';
+
+.more-recommendations {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ line-height: math.div(16, 13); // (16 / 13) -> 16px computed
+
+ &::after {
+ background: url('chrome://global/skin/icons/arrow-right-12.svg') no-repeat center center;
+ content: '';
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-primary-action-background);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px;
+ }
+
+ &:dir(rtl)::after {
+ background-image: url('chrome://global/skin/icons/arrow-left-12.svg');
+ }
+}
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..e1eed58e9c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss
@@ -0,0 +1,42 @@
+@use 'sass:math';
+
+.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: var(--newtab-primary-action-background);
+ 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: math.div(16, 13); // (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..b131c884c1
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/Search.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/. */
+
+/* globals ContentSearchUIController, ContentSearchHandoffUIController */
+"use strict";
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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.DISABLE_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 us set the search icon and reacts to
+ // changes to default engine to keep everything in sync.
+ this._handoffSearchController = new ContentSearchHandoffUIController();
+ }
+ }
+
+ getDefaultEngineName() {
+ // _handoffSearchController will manage engine names once it is initialized.
+ return this.props.Prefs.values["urlbar.placeholderName"];
+ }
+
+ getHandoffInputL10nAttributes() {
+ let defaultEngineName = this.getDefaultEngineName();
+ return defaultEngineName
+ ? {
+ "data-l10n-id": "newtab-search-box-handoff-input",
+ "data-l10n-args": `{"engine": "${defaultEngineName}"}`,
+ }
+ : {
+ "data-l10n-id": "newtab-search-box-handoff-input-no-engine",
+ };
+ }
+
+ getHandoffTextL10nAttributes() {
+ let defaultEngineName = this.getDefaultEngineName();
+ return defaultEngineName
+ ? {
+ "data-l10n-id": "newtab-search-box-handoff-text",
+ "data-l10n-args": `{"engine": "${defaultEngineName}"}`,
+ }
+ : {
+ "data-l10n-id": "newtab-search-box-handoff-text-no-engine",
+ };
+ }
+
+ 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.disable && "search-disabled",
+ this.props.fakeFocus && "fake-focus",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ 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="newtab-search-box-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"
+ {...this.getHandoffInputL10nAttributes()}
+ ref={this.onSearchHandoffButtonMount}
+ onClick={this.onSearchHandoffClick}
+ tabIndex="-1"
+ >
+ <div
+ className="fake-textbox"
+ {...this.getHandoffTextL10nAttributes()}
+ />
+ <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..189198a16c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/_Search.scss
@@ -0,0 +1,412 @@
+$search-height: 48px;
+$search-height-new: 52px;
+$search-icon-size: 24px;
+$search-icon-padding: 16px;
+$search-icon-width: 2 * $search-icon-padding + $search-icon-size - 4px;
+$search-button-width: 48px;
+$glyph-forward: url('chrome://browser/skin/forward.svg');
+
+.search-wrapper {
+ padding: 34px 0 38px;
+
+ .only-search & {
+ padding: 0 0 38px;
+ }
+
+ .logo-and-wordmark {
+ $logo-size: 82px;
+ $wordmark-size: 134px;
+
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px;
+
+ .logo {
+ display: inline-block;
+ height: $logo-size;
+ width: $logo-size;
+ 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');
+ }
+ }
+
+ .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-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-new;
+ margin: 0 auto;
+ position: relative;
+ width: $searchbar-width-small;
+
+ @media (min-width: $break-point-medium) {
+ width: $searchbar-width-medium;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: $searchbar-width-large;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: $searchbar-width-largest;
+ }
+ }
+
+ .search-handoff-button,
+ input {
+ background: var(--newtab-background-color-secondary) 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;
+ padding-block: 0;
+ width: 100%;
+ box-shadow: $shadow-card;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-text-primary-color);
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-secondary-color);
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+
+ .search-inner-wrapper:active input,
+ input:focus {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: $shadow-focus;
+ }
+
+ .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-text-secondary-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: $search-button-width;
+
+ &:focus,
+ &:hover {
+ background-color: var(--newtab-element-hover-color);
+ cursor: pointer;
+ }
+
+ &:focus {
+ outline: 0;
+ box-shadow: $shadow-focus;
+ border: 1px solid var(--newtab-primary-action-background);
+ border-radius: 0 $border-radius-new $border-radius-new 0;
+ }
+
+ &:active {
+ background-color: var(--newtab-element-hover-color);
+ }
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+ }
+
+ &.fake-focus:not(.search.disabled) {
+ .search-handoff-button {
+ border: 1px solid var(--newtab-primary-action-background);
+ box-shadow: $shadow-focus;
+ }
+ }
+
+ .search-handoff-button {
+ padding-inline-end: 15px;
+ color: var(--newtab-text-primary-color);
+ fill: var(--newtab-text-secondary-color);
+ -moz-context-properties: fill;
+
+ .fake-caret {
+ top: 18px;
+ inset-inline-start: $search-icon-width;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+ }
+
+ &.visible-logo {
+ .logo-and-wordmark {
+ .wordmark {
+ fill: var(--newtab-wordmark-color);
+ }
+ }
+ }
+}
+
+.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-background-color-secondary) var(--newtab-search-icon) $search-icon-padding center no-repeat;
+ background-size: $search-icon-size;
+ border: solid 1px transparent;
+ 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;
+ width: 100%;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+
+ .fake-focus:not(.search-disabled) & {
+ border: $input-border-active;
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+
+ .fake-caret {
+ display: block;
+ }
+ }
+
+ .search-disabled & {
+ opacity: 0.5;
+ box-shadow: none;
+ }
+
+ .fake-editable:focus {
+ outline: none;
+ caret-color: transparent;
+ }
+
+ .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ inset: 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: 124px;
+ }
+
+ &.visible-logo {
+ main {
+ padding-top: 254px;
+ }
+ }
+
+ .search-wrapper {
+ $search-height: 45px;
+ $search-icon-size: 24px;
+ $search-icon-padding: 16px;
+ $search-header-bar-height: 95px;
+
+ border-bottom: solid 1px var(--newtab-border-color);
+ padding: 27px 0;
+ background-color: var(--newtab-overlay-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;
+ }
+ }
+
+ .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 {
+ border: 0;
+ box-shadow: $context-menu-shadow;
+ transform: translateY($textbox-shadow-size);
+ background-color: var(--newtab-background-color);
+
+ .contentSearchHeader {
+ color: var(--newtab-text-secondary-color);
+ background-color: var(--newtab-background-color-secondary);
+ }
+
+ .contentSearchHeader,
+ .contentSearchSettingsButton {
+ border-color: var(--newtab-border-color);
+ }
+
+ .contentSearchSuggestionsList {
+ color: var(--newtab-text-primary-color);
+ border: 0;
+ }
+
+ .contentSearchOneOffsTable {
+ border-top: solid 1px var(--newtab-border-color);
+ background-color: var(--newtab-background-color);
+ }
+
+ .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-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-text-secondary-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-color) $border-offset, var(--newtab-border-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/Sections/Sections.jsx b/browser/components/newtab/content-src/components/Sections/Sections.jsx
new file mode 100644
index 0000000000..e72e9145ad
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Sections/Sections.jsx
@@ -0,0 +1,378 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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,
+ 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}
+ 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">
+ <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..e3fe15f762
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Sections/_Sections.scss
@@ -0,0 +1,123 @@
+.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-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-text-primary-color);
+ font-size: 12px;
+ line-height: 1.6;
+ margin-top: $topic-margin-top;
+ display: flex;
+ justify-content: space-between;
+
+ a {
+ color: var(--newtab-primary-action-background);
+ 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..4324c019f6
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx
@@ -0,0 +1,192 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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..90641008be
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSite.jsx
@@ -0,0 +1,873 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+import {
+ MIN_RICH_FAVICON_SIZE,
+ MIN_SMALL_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.sys.mjs";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { TopSiteImpressionWrapper } from "./TopSiteImpressionWrapper";
+import { connect } from "react-redux";
+
+const SPOC_TYPE = "SPOC";
+const NEWTAB_SOURCE = "newtab";
+
+// For cases if we want to know if this is sponsored by either sponsored_position or type.
+// We have two sources for sponsored topsites, and
+// sponsored_position is set by one sponsored source, and type is set by another.
+// This is not called in all cases, sometimes we want to know if it's one source
+// or the other. This function is only applicable in cases where we only care if it's either.
+function isSponsored(link) {
+ return link?.sponsored_position || link?.type === SPOC_TYPE;
+}
+
+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 || !isSponsored(this.props.link)) &&
+ 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":
+ event.target.blur();
+ if (isSponsored(this.props.link)) {
+ event.preventDefault();
+ break;
+ }
+ this.dragged = true;
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/topsite-index", this.props.index);
+ 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 } = this.props;
+
+ const { tippyTopIcon, faviconSize } = link;
+ let imageClassName;
+ let imageStyle;
+ let showSmallFavicon = false;
+ let smallFaviconStyle;
+ let hasScreenshotImage =
+ this.state.screenshotImage && this.state.screenshotImage.url;
+ let selectedColor;
+
+ if (defaultStyle) {
+ // force no styles (letter fallback) even if the link has imagery
+ 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
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: hasScreenshotImage
+ ? `url(${this.state.screenshotImage.url})`
+ : "",
+ };
+ } else if (
+ tippyTopIcon ||
+ link.type === SPOC_TYPE ||
+ 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 if (faviconSize >= MIN_SMALL_FAVICON_SIZE) {
+ showSmallFavicon = true;
+ smallFaviconStyle = { backgroundImage: `url(${link.favicon})` };
+ } else {
+ selectedColor = this.generateColor();
+ imageClassName = "";
+ }
+
+ return {
+ showSmallFavicon,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor,
+ };
+ }
+
+ render() {
+ const { children, className, isDraggable, link, onClick, title } =
+ this.props;
+ const topSiteOuterClassName = `top-site-outer${
+ className ? ` ${className}` : ""
+ }${link.isDragged ? " dragged" : ""}${
+ link.searchTopSite ? " search-shortcut" : ""
+ }`;
+ const [letterFallback] = title;
+ const {
+ showSmallFavicon,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor,
+ } = this.calculateStyle();
+
+ let draggableProps = {};
+ if (isDraggable) {
+ draggableProps = {
+ onClick: this.onDragEvent,
+ onDragEnd: this.onDragEvent,
+ onDragStart: this.onDragEvent,
+ onMouseDown: this.onDragEvent,
+ };
+ }
+
+ let impressionStats = null;
+ if (link.type === SPOC_TYPE) {
+ // Record impressions for Pocket tiles.
+ impressionStats = (
+ <ImpressionStats
+ flightId={link.flightId}
+ rows={[
+ {
+ id: link.id,
+ pos: link.pos,
+ shim: link.shim && link.shim.impression,
+ advertiser: title.toLocaleLowerCase(),
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={TOP_SITES_SOURCE}
+ />
+ );
+ } else if (isSponsored(link)) {
+ // Record impressions for non-Pocket sponsored tiles.
+ impressionStats = (
+ <TopSiteImpressionWrapper
+ actionType={at.TOP_SITES_SPONSORED_IMPRESSION_STATS}
+ tile={{
+ position: this.props.index,
+ tile_id: link.sponsored_tile_id || -1,
+ reporting_url: link.sponsored_impression_url,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE,
+ }}
+ // For testing.
+ IntersectionObserver={this.props.IntersectionObserver}
+ document={this.props.document}
+ dispatch={this.props.dispatch}
+ />
+ );
+ } else {
+ // Record impressions for organic tiles.
+ impressionStats = (
+ <TopSiteImpressionWrapper
+ actionType={at.TOP_SITES_ORGANIC_IMPRESSION_STATS}
+ tile={{
+ position: this.props.index,
+ source: NEWTAB_SOURCE,
+ }}
+ // For testing.
+ IntersectionObserver={this.props.IntersectionObserver}
+ document={this.props.document}
+ dispatch={this.props.dispatch}
+ />
+ );
+ }
+
+ 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}
+ data-is-sponsored-link={!!link.sponsored_tile_id}
+ >
+ <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={smallFaviconStyle ? "" : letterFallback}
+ style={smallFaviconStyle}
+ />
+ )}
+ </div>
+ {link.searchTopSite && (
+ <div className="top-site-icon search-topsite" />
+ )}
+ </div>
+ <div
+ className={`title${link.isPinned ? " has-icon pinned" : ""}${
+ link.type === SPOC_TYPE || link.show_sponsored_label
+ ? " sponsored"
+ : ""
+ }`}
+ >
+ <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>
+ </a>
+ {children}
+ {impressionStats}
+ </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 (isSponsored(this.props.link)) {
+ 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 },
+ }),
+ })
+ );
+
+ if (this.props.link.type === SPOC_TYPE) {
+ // Record a Pocket-specific click.
+ 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,
+ },
+ ],
+ })
+ );
+
+ // Record a click for a Pocket sponsored tile.
+ const title = this.props.link.label || this.props.link.hostname;
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.link.pos,
+ tile_id: this.props.link.id,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE,
+ },
+ })
+ );
+ } else if (isSponsored(this.props.link)) {
+ // Record a click for a non-Pocket sponsored tile.
+ const title = this.props.link.label || this.props.link.hostname;
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.index,
+ tile_id: this.props.link.sponsored_tile_id || -1,
+ reporting_url: this.props.link.sponsored_click_url,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE,
+ },
+ })
+ );
+ } else {
+ // Record a click for an organic tile.
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.TOP_SITES_ORGANIC_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.index,
+ source: NEWTAB_SOURCE,
+ },
+ })
+ );
+ }
+
+ 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="dialog"
+ 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 || isSponsored(site)) ? site : null
+ );
+ const unpinned = topSites.filter(
+ site => site && !site.isPinned && !isSponsored(site)
+ );
+ 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 (isSponsored(preview[nextIndex])) {
+ 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,
+ };
+ // 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";
+ }
+
+ let topSiteLink;
+ // Use a placeholder if the link is empty or it's rendering a sponsored
+ // tile for the about:home startup cache.
+ if (!link || (props.App.isForStartupCache && isSponsored(link))) {
+ topSiteLink = <TopSitePlaceholder {...slotProps} {...commonProps} />;
+ } else {
+ topSiteLink = (
+ <TopSite
+ link={link}
+ activeIndex={this.state.activeIndex}
+ onActivate={this.onActivate}
+ {...slotProps}
+ {...commonProps}
+ colors={props.colors}
+ />
+ );
+ }
+
+ topSitesUI.push(topSiteLink);
+ }
+ return (
+ <ul
+ className={`top-sites-list${
+ this.state.draggedSite ? " dnd-active" : ""
+ }`}
+ >
+ {topSitesUI}
+ </ul>
+ );
+ }
+}
+
+export const TopSiteList = connect(state => ({
+ App: state.App,
+}))(_TopSiteList);
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..7dd61bdc93
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSiteForm.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,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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;
+
+ const addTopsitesHeaderL10nId = "newtab-topsites-add-shortcut-header";
+ const editTopsitesHeaderL10nId = "newtab-topsites-edit-shortcut-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"
+ autoFocusOnOpen={true}
+ />
+ <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}
+ />
+ </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..c680edc7e4
--- /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.autoFocusOnOpen}
+ 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/TopSiteImpressionWrapper.jsx b/browser/components/newtab/content-src/components/TopSites/TopSiteImpressionWrapper.jsx
new file mode 100644
index 0000000000..580809dd57
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSiteImpressionWrapper.jsx
@@ -0,0 +1,149 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+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 a TopSite tile.
+ *
+ * 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.
+ */
+export class TopSiteImpressionWrapper extends React.PureComponent {
+ _dispatchImpressionStats() {
+ const { actionType, tile } = this.props;
+ if (!actionType) {
+ return;
+ }
+
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: actionType,
+ data: {
+ type: "impression",
+ ...tile,
+ },
+ })
+ );
+ }
+
+ setImpressionObserverOrAddListener() {
+ const { props } = this;
+
+ if (!props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === VISIBLE) {
+ 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) {
+ 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.tile) {
+ return;
+ }
+
+ this._handleIntersect = entries => {
+ if (
+ entries.some(
+ entry =>
+ entry.isIntersecting &&
+ entry.intersectionRatio >= INTERSECTION_RATIO
+ )
+ ) {
+ this._dispatchImpressionStats();
+ this.impressionObserver.unobserve(this.refs.topsite_impression_wrapper);
+ }
+ };
+
+ const options = { threshold: INTERSECTION_RATIO };
+ this.impressionObserver = new props.IntersectionObserver(
+ this._handleIntersect,
+ options
+ );
+ this.impressionObserver.observe(this.refs.topsite_impression_wrapper);
+ }
+
+ componentDidMount() {
+ if (this.props.tile) {
+ this.setImpressionObserverOrAddListener();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._handleIntersect && this.impressionObserver) {
+ this.impressionObserver.unobserve(this.refs.topsite_impression_wrapper);
+ }
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ render() {
+ return (
+ <div
+ ref={"topsite_impression_wrapper"}
+ className="topsite-impression-observer"
+ >
+ {this.props.children}
+ </div>
+ );
+ }
+}
+
+TopSiteImpressionWrapper.defaultProps = {
+ IntersectionObserver: global.IntersectionObserver,
+ document: global.document,
+ actionType: null,
+ tile: null,
+};
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..fd1e3048a5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSites.jsx
@@ -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/. */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { 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.sys.mjs";
+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) {
+ 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: 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 colors = props.Prefs.values["newNewtabExperience.colors"];
+
+ if (props.Prefs.values["improvesearch.topSiteSearchShortcuts"]) {
+ extraMenuOptions.push("AddSearchShortcut");
+ }
+
+ return (
+ <ComponentPerfTimer
+ id="topsites"
+ initialized={props.TopSites.initialized}
+ dispatch={props.dispatch}
+ >
+ <CollapsibleSection
+ className="top-sites"
+ id="topsites"
+ title={props.title || { id: "newtab-section-header-topsites" }}
+ hideTitle={true}
+ extraMenuOptions={extraMenuOptions}
+ showPrefName="feeds.topsites"
+ eventSource={TOP_SITES_SOURCE}
+ collapsed={false}
+ isFixed={props.isFixed}
+ isFirst={props.isFirst}
+ isLast={props.isLast}
+ dispatch={props.dispatch}
+ >
+ <TopSiteList
+ TopSites={props.TopSites}
+ TopSitesRows={props.TopSitesRows}
+ dispatch={props.dispatch}
+ topSiteIconType={topSiteIconType}
+ 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}
+ />
+ </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) => ({
+ TopSites: 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..f488896238
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js
@@ -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/. */
+
+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 = [
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "ShowPrivacyInfo",
+];
+export const TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS = [
+ "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
+export const MIN_SMALL_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..b893b6b33e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/_TopSites.scss
@@ -0,0 +1,628 @@
+@use 'sass:math';
+
+$top-sites-size: $grid-unit-small;
+$top-sites-border-radius: 8px;
+$top-sites-icon-border-radius: 4px;
+$rich-icon-size: 96px;
+$default-icon-wrapper-size: 32px;
+$default-icon-size: 32px;
+$default-icon-offset: 6px;
+$half-base-gutter: math.div($base-gutter, 2);
+$hover-transition-duration: 150ms;
+$letter-fallback-color: $white;
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 (-$half-base-gutter);
+ padding: 0;
+
+ a {
+ text-decoration: none;
+ }
+
+ &:not(.dnd-active) {
+ .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-element-hover-color);
+ }
+ }
+
+ // 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 {
+ width: 120px;
+ padding: 20px $half-base-gutter 4px;
+ border-radius: 8px;
+ display: inline-block;
+
+ // container for context menu
+ .top-site-inner {
+ position: relative;
+
+ > a {
+ color: inherit;
+ display: block;
+ outline: none;
+ }
+ }
+
+ &:is(:hover) {
+ .context-menu-button {
+ opacity: 1;
+ }
+ }
+
+ .context-menu-button {
+ background-image: url('chrome://global/skin/icons/more.svg');
+ border: 0;
+ border-radius: 4px;
+ cursor: pointer;
+ fill: var(--newtab-text-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-element-hover-color);
+ fill: var(--newtab-primary-action-background);
+ }
+ }
+
+ .tile {
+ border-radius: $top-sites-border-radius;
+ box-shadow: $shadow-card;
+ background-color: var(--newtab-background-color-secondary);
+ justify-content: center;
+ margin: 0 auto;
+ height: $top-sites-size;
+ width: $top-sites-size;
+ cursor: pointer;
+ position: relative;
+
+ // For letter fallback
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ text-transform: uppercase;
+
+ .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;
+ 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-background-color-secondary);
+ background-position: center center;
+ background-repeat: no-repeat;
+ border-radius: $top-sites-icon-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('chrome://global/skin/icons/search-glass.svg');
+ background-size: 16px;
+ background-color: var(--newtab-primary-action-background);
+ border-radius: $default-icon-wrapper-size;
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ box-shadow: $shadow-card;
+ transition-duration: $hover-transition-duration;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 32px;
+ width: 32px;
+ bottom: -$default-icon-offset;
+ inset-inline-end: -$default-icon-offset;
+ }
+
+ &.placeholder {
+ .tile {
+ box-shadow: $inner-box-shadow;
+ }
+ }
+
+ .title {
+ color: var(--newtab-text-primary-color);
+ padding-top: 8px;
+ font: caption;
+ text-align: center;
+ position: relative;
+
+ .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-text-primary-color);
+ }
+
+ span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .sponsored-label {
+ color: var(--newtab-text-secondary-color);
+ 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('chrome://global/skin/icons/edit.svg');
+ }
+
+ &.dragged {
+ .tile {
+ *,
+ &::before {
+ display: none;
+ }
+ }
+
+ .title {
+ visibility: hidden;
+ }
+ }
+}
+
+.edit-topsites-wrapper {
+ .top-site-inner > .top-site-button > .tile {
+ border: 1px solid var(--newtab-border-color);
+ }
+
+ .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: var(--newtab-primary-action-background);
+ 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-background-color-secondary);
+ 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: var(--newtab-status-error);
+ border-radius: 2px;
+ color: $white;
+ inset-inline-start: 3px;
+ padding: 5px 12px;
+ position: absolute;
+ top: 44px;
+ z-index: 1;
+
+ // tooltip caret
+ &::before {
+ background: var(--newtab-status-error);
+ 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;
+ content: '';
+ height: 21px;
+ left: $checkbox-offset;
+ position: absolute;
+ top: $checkbox-offset;
+ width: 21px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-action-background);
+ z-index: 2;
+
+ [dir='rtl'] & {
+ left: auto;
+ right: $checkbox-offset;
+ }
+ }
+
+ // when selected, highlight the tile
+ [type='checkbox']:checked + label {
+ .tile {
+ box-shadow: $shadow-focus;
+ }
+ }
+
+ // 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-primary-action-background);
+ }
+}
+
+// used for tooltips below form element
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+// used for TopSites impression wrapper
+.topsite-impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
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..205f42e600
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Topics/_Topics.scss
@@ -0,0 +1,24 @@
+.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..840aee0f19
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/aboutwelcome-utils.js
@@ -0,0 +1,119 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// If the container has a "page" data attribute, then this is
+// a Spotlight modal or Feature Callout. Otherwise, this is
+// about:welcome and we should return the current page.
+const page =
+ document.querySelector(
+ "#multi-stage-message-root.onboardingContainer[data-page]"
+ )?.dataset.page || document.location.href;
+
+export const AboutWelcomeUtils = {
+ handleUserAction(action) {
+ return window.AWSendToParent("SPECIAL_ACTION", action);
+ },
+ sendImpressionTelemetry(messageId, context) {
+ window.AWSendEventTelemetry?.({
+ event: "IMPRESSION",
+ event_context: {
+ ...context,
+ page,
+ },
+ message_id: messageId,
+ });
+ },
+ sendActionTelemetry(messageId, elementId, eventName = "CLICK_BUTTON") {
+ const ping = {
+ event: eventName,
+ event_context: {
+ source: elementId,
+ page,
+ },
+ message_id: messageId,
+ };
+ window.AWSendEventTelemetry?.(ping);
+ },
+ sendDismissTelemetry(messageId, elementId) {
+ // Don't send DISMISS telemetry in spotlight modals since they already send
+ // their own equivalent telemetry.
+ if (page !== "spotlight") {
+ this.sendActionTelemetry(messageId, elementId, "DISMISS");
+ }
+ },
+ 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);
+ }
+ } catch (e) {
+ flowParams = null;
+ }
+ return flowParams;
+ },
+ sendEvent(type, detail) {
+ document.dispatchEvent(
+ new CustomEvent(`AWPage:${type}`, {
+ bubbles: true,
+ detail,
+ })
+ );
+ },
+};
+
+export const DEFAULT_RTAMO_CONTENT = {
+ template: "return_to_amo",
+ utm_term: "rtamo",
+ content: {
+ position: "split",
+ title: { string_id: "mr1-return-to-amo-subtitle" },
+ has_noodles: false,
+ subtitle: {
+ string_id: "mr1-return-to-amo-addon-title",
+ },
+ backdrop:
+ "var(--mr-welcome-background-color) var(--mr-welcome-background-gradient)",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-rtamo-background-image.svg') no-repeat center",
+ progress_bar: true,
+ primary_button: {
+ label: { string_id: "mr1-return-to-amo-add-extension-label" },
+ source_id: "ADD_EXTENSION_BUTTON",
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: null, telemetrySource: "rtamo" },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ source_id: "RTAMO_START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR",
+ },
+ },
+ secondary_button_top: {
+ label: {
+ string_id: "mr1-onboarding-sign-in-button-label",
+ },
+ source_id: "RTAMO_FXA_SIGNIN_BUTTON",
+ action: {
+ data: {
+ entrypoint: "activity-stream-firstrun",
+ where: "tab",
+ },
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: 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..2c96160b4b
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/constants.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/. */
+
+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_card_background: {
+ r: 66,
+ g: 65,
+ b: 77,
+ 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..43aa388967
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/detect-user-session-start.js
@@ -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/. */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..77ae5363bf
--- /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/remote-page */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.sys.mjs";
+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);
+ 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..792522b52d
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/link-menu-options.js
@@ -0,0 +1,292 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs";
+
+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,
+ sponsored_tile_id: site.sponsored_tile_id,
+ },
+ }),
+ 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,
+ // used by PlacesFeed and TopSitesFeed for sponsored top sites blocking.
+ isSponsoredTopSite: site.sponsored_position,
+ ...(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 = "CARDGRID") => ({
+ 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, source) =>
+ site.pocket_id
+ ? LinkMenuOptions.DeleteFromPocket(site)
+ : LinkMenuOptions.SaveToPocket(site, index, source),
+ CheckBookmarkOrArchive: site =>
+ site.pocket_id
+ ? LinkMenuOptions.ArchiveFromPocket(site)
+ : LinkMenuOptions.CheckBookmark(site),
+ CheckArchiveFromPocket: site =>
+ site.pocket_id
+ ? LinkMenuOptions.ArchiveFromPocket(site)
+ : LinkMenuOptions.EmptyItem(),
+ CheckDeleteFromPocket: site =>
+ site.pocket_id
+ ? LinkMenuOptions.DeleteFromPocket(site)
+ : LinkMenuOptions.EmptyItem(),
+ 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/selectLayoutRender.js b/browser/components/newtab/content-src/lib/selectLayoutRender.js
new file mode 100644
index 0000000000..aa3eb927d2
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/selectLayoutRender.js
@@ -0,0 +1,255 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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",
+ "HorizontalRule",
+ "PrivacyLink",
+ ];
+
+ const filterArray = [];
+
+ if (!prefs["feeds.topsites"]) {
+ filterArray.push("TopSites");
+ }
+
+ 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/_activity-stream.scss b/browser/components/newtab/content-src/styles/_activity-stream.scss
new file mode 100644
index 0000000000..1261b6e916
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_activity-stream.scss
@@ -0,0 +1,177 @@
+@import './normalize';
+@import './variables';
+@import './theme';
+@import './icons';
+@import './mixins';
+
+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;
+}
+
+.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-primary-action-background);
+ border: solid 1px var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+ 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
+// stylelint-disable no-invalid-position-at-import-rule
+@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/Highlights/Highlights';
+@import '../components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule';
+@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';
+@import '../components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink';
+@import '../components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget';
+
+// 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';
+// stylelint-enable no-invalid-position-at-import-rule
diff --git a/browser/components/newtab/content-src/styles/_feature-callout-theme.scss b/browser/components/newtab/content-src/styles/_feature-callout-theme.scss
new file mode 100644
index 0000000000..b62591f3ac
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_feature-callout-theme.scss
@@ -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/.
+
+// stylelint-disable color-hex-length -- we want to preserve these values
+// exactly, since they're drawn from other parts of the browser.
+
+@mixin light-theme {
+ --fc-background: var(--fc-background-light, #FFF);
+ --fc-color: var(--fc-color-light, #15141A);
+ --fc-border: var(--fc-border-light, #CFCFD8);
+ --fc-accent-color: var(--fc-accent-color-light, #0061E0);
+ --fc-button-background: var(--fc-button-background-light, #F0F0F4);
+ --fc-button-color: var(--fc-button-color-light, #15141A);
+ --fc-button-border: var(--fc-button-border-light, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-light, #E0E0E6);
+ --fc-button-color-hover: var(--fc-button-color-hover-light, #15141A);
+ --fc-button-border-hover: var(--fc-button-border-hover-light, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-light, #CFCFD8);
+ --fc-button-color-active: var(--fc-button-color-active-light, #15141A);
+ --fc-button-border-active: var(--fc-button-border-active-light, transparent);
+ --fc-step-color: color-mix(in srgb, currentColor 50%, transparent);
+}
+
+@mixin dark-theme {
+ --fc-background: var(--fc-background-dark, #42414D);
+ --fc-color: var(--fc-color-dark, #FBFBFE);
+ --fc-border: var(--fc-border-dark, #3A3944);
+ --fc-accent-color: var(--fc-accent-color-dark, #00DDFF);
+ --fc-button-background: var(--fc-button-background-dark, #2B2A33);
+ --fc-button-color: var(--fc-button-color-dark, #FBFBFE);
+ --fc-button-border: var(--fc-button-border-dark, transparent);
+ --fc-button-background-hover: var(--fc-button-background-hover-dark, #52525E);
+ --fc-button-color-hover: var(--fc-button-color-hover-dark, #FBFBFE);
+ --fc-button-border-hover: var(--fc-button-border-hover-dark, transparent);
+ --fc-button-background-active: var(--fc-button-background-active-dark, #5B5B66);
+ --fc-button-color-active: var(--fc-button-color-active-dark, #FBFBFE);
+ --fc-button-border-active: var(--fc-button-border-active-dark, transparent);
+}
+
+@mixin hcm-theme {
+ --fc-background: var(--fc-background-hcm, -moz-dialog);
+ --fc-color: var(--fc-color-hcm, -moz-dialogtext);
+ --fc-border: var(--fc-border-hcm, -moz-dialogtext);
+ --fc-accent-color: var(--fc-accent-color-hcm, LinkText);
+ --fc-button-background: var(--fc-button-background-hcm, ButtonFace);
+ --fc-button-color: var(--fc-button-color-hcm, ButtonText);
+ --fc-button-border: var(--fc-button-border-hcm, ButtonText);
+ --fc-button-background-hover: var(--fc-button-background-hover-hcm, ButtonText);
+ --fc-button-color-hover: var(--fc-button-color-hover-hcm, ButtonFace);
+ --fc-button-border-hover: var(--fc-button-border-hover-hcm, ButtonText);
+ --fc-button-background-active: var(--fc-button-background-active-hcm, ButtonText);
+ --fc-button-color-active: var(--fc-button-color-active-hcm, ButtonFace);
+ --fc-button-border-active: var(--fc-button-border-active-hcm, ButtonText);
+ --fc-step-color: var(--fc-accent-color-hcm, LinkText);
+}
diff --git a/browser/components/newtab/content-src/styles/_feature-callout.scss b/browser/components/newtab/content-src/styles/_feature-callout.scss
new file mode 100644
index 0000000000..aa0ba0ed1e
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_feature-callout.scss
@@ -0,0 +1,314 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.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 'feature-callout-theme';
+
+$max-z-index: 2147483647;
+
+.onboardingContainer.featureCallout {
+ // See _feature-callout-theme.scss for the theme mixins and
+ // FeatureCallout.sys.mjs for the color values
+ @include light-theme;
+
+ position: absolute;
+ transition: opacity 0.5s ease;
+ z-index: $max-z-index - 2;
+ outline: none;
+ color: var(--fc-color);
+
+ @media (prefers-color-scheme: dark) {
+ @include dark-theme;
+ }
+
+ @media (prefers-contrast) {
+ @include hcm-theme;
+ }
+
+ // Account for feature callouts that may be rendered in the chrome but
+ // displayed on top of content. Each context has its own color scheme, so they
+ // may not match. In that case, we use the special media query below.
+ &.simulateContent {
+ @media (-moz-content-prefers-color-scheme: light) {
+ @include light-theme;
+ }
+
+ @media (-moz-content-prefers-color-scheme: dark) {
+ @include dark-theme;
+ }
+
+ @media (prefers-contrast) {
+ @include hcm-theme;
+ }
+ }
+
+ &.hidden {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ &,
+ & .outer-wrapper {
+ // auto height to allow for arrow positioning based on height
+ height: auto;
+ }
+
+ .screen {
+ // override transform in about:welcome
+ &:dir(rtl) {
+ transform: none;
+ }
+
+ &[pos='callout'] {
+ height: fit-content;
+ min-height: unset;
+ overflow: visible;
+
+ .logo-container {
+ display: flex;
+ justify-content: center;
+
+ .brand-logo {
+ margin: 30px 45px 0;
+
+ // This may not work for all future messages, so we may want to make
+ // flipping the logo image in RTL mode configurable
+ &:dir(rtl) {
+ transform: rotateY(180deg);
+ }
+ }
+ }
+
+ .welcome-text {
+ align-items: baseline;
+ text-align: start;
+ margin-inline: 30px;
+ padding: 20px 0 0;
+
+ h1,
+ h2 {
+ font-size: 0.8em;
+ margin: 0;
+ color: inherit;
+ }
+
+ h1 {
+ font-weight: bold;
+ }
+
+ h2 {
+ margin-block: 10px;
+ }
+ }
+
+ // Secondary section is not included in callouts
+ .section-secondary {
+ display: none;
+ }
+
+ .section-main {
+ height: fit-content;
+ width: fit-content;
+
+ .main-content {
+ position: relative;
+ overflow: hidden;
+ border: 1px solid var(--fc-border);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 15%);
+ border-radius: 4px;
+ padding-top: 0;
+ // Subtract 4px, the block margin of buttons
+ padding-bottom: 30px - 4px;
+ width: 25em;
+ background-color: var(--fc-background);
+
+ .steps {
+ height: auto;
+ position: absolute;
+ // 30px is the margin of the CTAs from the bottom. The CTAs are 32px
+ // tall, and the steps are 8px tall. So we need to offset the steps
+ // by half the difference in order to center them. = 36px
+ bottom: 30px + math.div(32px, 2) - math.div(8px, 2);
+ margin: 0 30px;
+ padding-block: 0;
+
+ .indicator {
+ // using border will show up in Windows High Contrast Mode to improve accessibility.
+ border: 4px solid var(--fc-step-color);
+
+ &.current {
+ border-color: var(--fc-accent-color);
+ }
+ }
+
+ & .indicator.current,
+ &.progress-bar .indicator.complete {
+ border-color: var(--fc-accent-color);
+ }
+ }
+ }
+
+ .dismiss-button {
+ font-size: 1em;
+ top: 0;
+ margin-block: 15px 0;
+ margin-inline: 0 15px;
+ z-index: $max-z-index;
+ background-color: var(--fc-background);
+ }
+ }
+
+ .action-buttons {
+ .primary,
+ .secondary-cta .secondary {
+ padding: 4px 16px;
+ font-size: 0.8em;
+ height: 2em;
+ background-color: var(--fc-button-background);
+ }
+
+ .primary {
+ font-weight: bold;
+ float: inline-end;
+ margin-inline: 10px 30px;
+ padding: 4px 16px;
+ font-size: 0.8em;
+ line-height: 16px;
+ min-height: 32px;
+ }
+
+ .secondary-cta {
+ float: inline-end;
+ }
+ }
+
+ .action-buttons .primary,
+ .action-buttons .secondary-cta .secondary,
+ .dismiss-button {
+ border-radius: 4px;
+ border: 1px solid var(--fc-button-border);
+ cursor: pointer;
+ color: var(--fc-button-color);
+
+ &:hover {
+ background-color: var(--fc-button-background-hover);
+ color: var(--fc-button-color-hover);
+ border: 1px solid var(--fc-button-border-hover);
+
+ &:active {
+ background-color: var(--fc-button-background-active);
+ color: var(--fc-button-color-active);
+ border: 1px solid var(--fc-button-border-active);
+ }
+ }
+
+ &:focus-visible {
+ box-shadow: none;
+ outline: 2px solid var(--fc-accent-color);
+ outline-offset: 2px;
+ }
+ }
+ }
+ }
+
+ $arrow-size: 24px;
+ $arrow-inset-size: math.div($arrow-size, 2);
+ // the arrow already overlaps the callout by 12px (see above), but to account
+ // for different pixel scaling factors, we can overlap by 1px more, since the
+ // border is drawn underneath the callout (on ::after). this is either added
+ // to or subtracted from absolute coordinates, depending on the direction.
+ $arrow-overlap-inset: -$arrow-inset-size + 1px;
+
+ // applied to all callout arrow foreground and background
+ &.callout-arrow::before,
+ &.callout-arrow::after {
+ content: '';
+ position: absolute;
+ width: $arrow-size;
+ height: $arrow-size;
+ transform: rotate(45deg);
+ // keep the border crisp under transformation
+ transform-style: preserve-3d;
+ }
+
+ // color for all arrow foreground
+ &.callout-arrow::before {
+ z-index: $max-z-index;
+ background-color: var(--fc-background);
+ }
+
+ // styles for all arrow backgrounds
+ &.callout-arrow::after {
+ background: transparent;
+ outline: 1px solid var(--fc-border);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 15%);
+ z-index: -1;
+ }
+
+ // up arrow positioning
+ &.arrow-top::before,
+ &.arrow-top::after {
+ top: $arrow-overlap-inset;
+ inset-inline-start: calc(50% - $arrow-inset-size);
+ }
+
+ // down arrow positioning
+ &.arrow-bottom::before,
+ &.arrow-bottom::after {
+ bottom: $arrow-overlap-inset;
+ inset-inline-start: calc(50% - $arrow-inset-size);
+ }
+
+ // end arrow positioning
+ &.arrow-inline-end::before,
+ &.arrow-inline-end::after {
+ top: calc(50% - $arrow-inset-size);
+ inset-inline-end: $arrow-overlap-inset;
+ }
+
+ // start arrow positioning
+ &.arrow-inline-start::before,
+ &.arrow-inline-start::after {
+ top: calc(50% - $arrow-inset-size);
+ inset-inline-start: $arrow-overlap-inset;
+ }
+
+ // top-end arrow positioning
+ &.arrow-top-end::before,
+ &.arrow-top-end::after {
+ top: $arrow-overlap-inset;
+ inset-inline-end: $arrow-inset-size;
+ }
+
+ // top-start arrow positioning
+ &.arrow-top-start::before,
+ &.arrow-top-start::after {
+ top: $arrow-overlap-inset;
+ inset-inline-start: $arrow-inset-size;
+ }
+
+ // hidden arrow display
+ &.hidden-arrow::before,
+ &.hidden-arrow::after {
+ display: none;
+ }
+
+ &:focus-visible {
+ .screen {
+ &[pos='callout'] {
+ .section-main .main-content {
+ outline: 2px solid var(--fc-accent-color);
+ border-color: transparent;
+
+ @media (prefers-contrast) {
+ border-color: var(--fc-background);
+ }
+ }
+ }
+ }
+
+ &.callout-arrow::after {
+ outline: 2px solid var(--fc-accent-color);
+ }
+ }
+}
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..4074f0a6a6
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_icons.scss
@@ -0,0 +1,211 @@
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: $icon-size;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-text-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-text-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://global/skin/icons/close-fill.svg');
+ }
+
+ &.icon-delete {
+ background-image: url('chrome://global/skin/icons/delete.svg');
+ }
+
+ &.icon-search {
+ background-image: url('chrome://global/skin/icons/search-glass.svg');
+ }
+
+ &.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-modal-delete-20.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://global/skin/icons/close.svg');
+ }
+
+ &.icon-info {
+ background-image: url('chrome://global/skin/icons/info.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://global/skin/icons/edit.svg');
+ }
+
+ &.icon-pocket {
+ background-image: url('chrome://global/skin/icons/pocket.svg');
+ }
+
+ &.icon-pocket-save {
+ background-image: url('chrome://global/skin/icons/pocket.svg');
+ fill: $white;
+ }
+
+ &.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://browser/skin/trending.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://browser/skin/topsites.svg');
+ }
+
+ &.icon-pin-small {
+ @include flip-icon;
+
+ background-image: url('chrome://browser/skin/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/downloads.svg');
+ }
+
+ &.icon-copy {
+ background-image: url('chrome://global/skin/icons/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://global/skin/icons/highlights.svg');
+ }
+
+ &.icon-arrowhead-down {
+ background-image: url('chrome://global/skin/icons/arrow-down.svg');
+ }
+
+ &.icon-arrowhead-down-small {
+ background-image: url('chrome://global/skin/icons/arrow-down-12.svg');
+ background-size: $smaller-icon-size;
+ height: $smaller-icon-size;
+ width: $smaller-icon-size;
+ }
+
+ &.icon-arrowhead-forward-small {
+ background-image: url('chrome://global/skin/icons/arrow-right-12.svg');
+ background-size: $smaller-icon-size;
+ height: $smaller-icon-size;
+ width: $smaller-icon-size;
+
+ &:dir(rtl) {
+ background-image: url('chrome://global/skin/icons/arrow-left-12.svg');
+ }
+ }
+
+ &.icon-arrowhead-up {
+ background-image: url('chrome://global/skin/icons/arrow-up.svg');
+ }
+
+ &.icon-add {
+ background-image: url('chrome://global/skin/icons/plus.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://global/skin/icons/arrow-right-12.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..d2b2748a60
--- /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-element-secondary-color);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: $shadow-image-inset;
+}
+
+// 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..a47166ef7b
--- /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; // stylelint-disable-line declaration-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..e5761b3d3b
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_theme.scss
@@ -0,0 +1,99 @@
+@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-color);
+$border-secondary: 1px solid var(--newtab-border-color);
+$inner-box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color);
+$input-border: 1px solid var(--newtab-border-color);
+$input-border-active: 1px solid var(--newtab-textbox-focus-color);
+$input-error-border: 1px solid var(--newtab-status-error);
+$input-error-boxshadow: textbox-shadow(var(--newtab-status-error));
+$shadow-primary: 0 0 0 5px var(--newtab-element-secondary-color);
+$shadow-secondary: 0 1px 4px 0 $grey-90-20;
+$shadow-large: 0 2px 14px 0 $black-20;
+$shadow-focus: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+$shadow-card: 0 2px 6px rgba(0, 0, 0, 15%);
+$shadow-image-inset: inset 0 0 0 0.5px $black-15;
+
+// Default theme
+:root {
+ // General styles
+ --newtab-background-color: #{$in-content-page-background};
+ --newtab-background-color-secondary: #{$newtab-background-secondary};
+ --newtab-text-primary-color: #{$in-content-page-color};
+ --newtab-primary-action-background: #{$primary-blue};
+ // A button colour closer to the Pocket brand for usage in the Pocket section.
+ --newtab-primary-action-background-pocket: #{$primary-green};
+ --newtab-text-secondary-color: color-mix(in srgb, var(--newtab-text-primary-color) 70%, transparent);
+
+ // --newtab-element-*-color is used when an element needs to be set off from
+ // the primary background color.
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 90%, #{$black});
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 80%, #{$black});
+
+ // --newtab-element-secondary*-color is used when an element needs to be set
+ // off from the secondary background color.
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 5%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 12%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 25%, transparent);
+
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 90%, #{$black});
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 90%, #{$black});
+ --newtab-primary-element-active-color: color-mix(in srgb, var(--newtab-primary-action-background) 80%, #{$black});
+ --newtab-primary-element-text-color: #{$white};
+ // --newtab-primary-action-background-dimmed is used for soft focus borders.
+ --newtab-primary-action-background-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 25%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #{$black});
+ --newtab-wordmark-color: #{$newtab-wordmark-default-color};
+ --newtab-status-success: #{$status-green};
+ --newtab-status-error: #{$red-60};
+ --newtab-inner-box-shadow-color: #{$black-10};
+ --newtab-overlay-color: color-mix(in srgb, var(--newtab-background-color) 85%, transparent);
+ --newtab-text-emphasis-background: #{$yellow-50};
+ --newtab-text-emphasis-text-color: #{$grey-90};
+
+ @include textbox-focus(var(--newtab-primary-action-background));
+
+ // Buttons
+ --newtab-button-secondary-color: inherit;
+
+ &[lwt-newtab-brighttext] {
+ // General styles
+ --newtab-background-color: #{$in-content-page-background-dark};
+ --newtab-background-color-secondary: #{$newtab-background-secondary-dark};
+ --newtab-text-primary-color: #{$in-content-page-color-dark};
+
+ --newtab-primary-action-background: #{$primary-blue-dark};
+ --newtab-primary-action-background-pocket: #{$primary-blue-dark};
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 55%, #{$white});
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 55%, #{$white});
+
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 80%, #{$white});
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 60%, #{$white});
+
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 10%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 17%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 30%, transparent);
+
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #{$white});
+ --newtab-primary-element-text-color: #{$primary-text-color-dark};
+ --newtab-wordmark-color: #{$newtab-wordmark-darktheme-color};
+ --newtab-status-success: #{$status-dark-green};
+ }
+}
+
+@media (prefers-contrast) {
+ :root {
+ --newtab-text-secondary-color: var(--newtab-text-primary-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..321b1ff7b8
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_variables.scss
@@ -0,0 +1,217 @@
+@use 'sass:math';
+
+$primary-blue: rgb(0, 97, 224);
+$primary-green: rgb(0, 128, 120);
+$primary-blue-dark: rgb(0, 221, 255);
+$primary-text-color-dark: rgb(43, 42, 51);
+
+// -------------------------------------------------------------------------- //
+// Photon colors from http://design.firefox.com/photon/visuals/color.html
+
+$blue-40: #45A1FF;
+$blue-50: #0A84FF;
+$grey-30: #D7D7DB;
+$grey-60: #4A4A4F;
+$grey-90: #0C0C0D;
+$red-60: #D70022;
+$yellow-50: #FFE900;
+
+$grey-90-10: rgba($grey-90, 0.1);
+$grey-90-20: rgba($grey-90, 0.2);
+
+$blue-40-40: rgba($blue-40, 0.4);
+$blue-50-30: rgba($blue-50, 0.3);
+
+$black: #000;
+$black-10: rgba($black, 0.1);
+$black-15: rgba($black, 0.15);
+$black-20: rgba($black, 0.2);
+$black-30: rgba($black, 0.3);
+$black-40: rgba($black, 0.4);
+
+// -------------------------------------------------------------------------- //
+// Other colors
+
+$white: #FFF;
+$status-green: #058B00;
+$status-dark-green: #7C6;
+$bookmark-icon-fill: #0A84FF;
+$download-icon-fill: #12BC00;
+$pocket-icon-fill: #EF4056;
+$email-input-invalid: rgba($red-60, 0.3);
+
+$newtab-wordmark-default-color: #20123A;
+$newtab-wordmark-darktheme-color: rgb(251, 251, 254);
+
+$in-content-page-color: rgb(21, 20, 26);
+$in-content-page-color-dark: rgb(251, 251, 254);
+
+// -------------------------------------------------------------------------- //
+// These colors should match the colors in the default themes
+// (toolkit/mozapps/extensions/...). Note that they could get replaced by other
+// themes. The color set in --tabpanel-background-color (tabs.inc.css) should
+// match these colors here to avoid flashing.
+
+$in-content-page-background: #F9F9FB;
+$in-content-page-background-dark: #2B2A33;
+
+$newtab-background-secondary: #FFF;
+$newtab-background-secondary-dark: rgb(66, 65, 77);
+
+// 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) - 24px;
+$searchbar-width-medium: ($grid-unit * 4 + $base-gutter * 3) - 120px;
+$searchbar-width-large: ($grid-unit * 6 + $base-gutter * 5) - 136px;
+$searchbar-width-largest: ($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: 17px;
+
+$card-width: $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 rgba(0, 0, 0, 15%);
+
+@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 {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+
+@mixin context-menu-button {
+ .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-background-color-secondary);
+ 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-text-primary-color);
+ height: $context-menu-button-size;
+ inset-inline-end: math.div(-$context-menu-button-size, 2);
+ opacity: 0;
+ position: absolute;
+ top: math.div(-$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 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..89128d9d04
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-linux.scss
@@ -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/. */
+
+/* This is the linux variant */
+
+$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..d95665f36f
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-mac.scss
@@ -0,0 +1,16 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 */
+
+$os-infopanel-arrow-height: 10px;
+$os-infopanel-arrow-offset-end: 7px;
+$os-infopanel-arrow-width: 18px;
+
+[lwt-newtab-brighttext] {
+ -moz-osx-font-smoothing: grayscale;
+}
+
+// stylelint-disable-next-line no-invalid-position-at-import-rule
+@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..9252bdd0f6
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-windows.scss
@@ -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/. */
+
+/* This is the windows variant */
+
+$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/css/activity-stream-linux.css b/browser/components/newtab/css/activity-stream-linux.css
new file mode 100644
index 0000000000..ed8570f1ef
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-linux.css
@@ -0,0 +1,4812 @@
+@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;
+}
+
+:root {
+ --newtab-background-color: #F9F9FB;
+ --newtab-background-color-secondary: #FFF;
+ --newtab-text-primary-color: #15141a;
+ --newtab-primary-action-background: #0061e0;
+ --newtab-primary-action-background-pocket: #008078;
+ --newtab-text-secondary-color: color-mix(in srgb, var(--newtab-text-primary-color) 70%, transparent);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 90%, #000);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 80%, #000);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 5%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 12%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 90%, #000);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 90%, #000);
+ --newtab-primary-element-active-color: color-mix(in srgb, var(--newtab-primary-action-background) 80%, #000);
+ --newtab-primary-element-text-color: #FFF;
+ --newtab-primary-action-background-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 25%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #000);
+ --newtab-wordmark-color: #20123A;
+ --newtab-status-success: #058B00;
+ --newtab-status-error: #D70022;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-overlay-color: color-mix(in srgb, var(--newtab-background-color) 85%, transparent);
+ --newtab-text-emphasis-background: #FFE900;
+ --newtab-text-emphasis-text-color: #0C0C0D;
+ --newtab-textbox-focus-color: var(--newtab-primary-action-background);
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px var(--newtab-primary-action-background), 0 0 0 4px rgba(var(--newtab-primary-action-background), 0.3);
+ --newtab-button-secondary-color: inherit;
+}
+:root[lwt-newtab-brighttext] {
+ --newtab-background-color: #2B2A33;
+ --newtab-background-color-secondary: #42414d;
+ --newtab-text-primary-color: #fbfbfe;
+ --newtab-primary-action-background: #00ddff;
+ --newtab-primary-action-background-pocket: #00ddff;
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 55%, #FFF);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 55%, #FFF);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 80%, #FFF);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 60%, #FFF);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 10%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 17%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 30%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #FFF);
+ --newtab-primary-element-text-color: #2b2a33;
+ --newtab-wordmark-color: #fbfbfe;
+ --newtab-status-success: #7C6;
+}
+
+@media (prefers-contrast) {
+ :root {
+ --newtab-text-secondary-color: var(--newtab-text-primary-color);
+ }
+}
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-text-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-text-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://global/skin/icons/close-fill.svg");
+}
+.icon.icon-delete {
+ background-image: url("chrome://global/skin/icons/delete.svg");
+}
+.icon.icon-search {
+ background-image: url("chrome://global/skin/icons/search-glass.svg");
+}
+.icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-20.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://global/skin/icons/close.svg");
+}
+.icon.icon-info {
+ background-image: url("chrome://global/skin/icons/info.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://global/skin/icons/edit.svg");
+}
+.icon.icon-pocket {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+}
+.icon.icon-pocket-save {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #FFF;
+}
+.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://browser/skin/trending.svg");
+ transform: translateY(2px);
+}
+.icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg");
+}
+.icon.icon-topsites {
+ background-image: url("chrome://browser/skin/topsites.svg");
+}
+.icon.icon-pin-small {
+ background-image: url("chrome://browser/skin/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/downloads.svg");
+}
+.icon.icon-copy {
+ background-image: url("chrome://global/skin/icons/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://global/skin/icons/highlights.svg");
+}
+.icon.icon-arrowhead-down {
+ background-image: url("chrome://global/skin/icons/arrow-down.svg");
+}
+.icon.icon-arrowhead-down-small {
+ background-image: url("chrome://global/skin/icons/arrow-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://global/skin/icons/arrow-right-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small:dir(rtl) {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+.icon.icon-arrowhead-up {
+ background-image: url("chrome://global/skin/icons/arrow-up.svg");
+}
+.icon.icon-add {
+ background-image: url("chrome://global/skin/icons/plus.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://global/skin/icons/arrow-right-12.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;
+}
+
+.inner-border {
+ border: 1px solid var(--newtab-border-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-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-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-element-secondary-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-primary-action-background);
+ border: solid 1px var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+ 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-primary-action-background);
+}
+.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-primary-action-background);
+}
+
+main {
+ margin: auto;
+ width: 274px;
+ padding: 0;
+}
+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;
+ }
+}
+main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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: 0;
+}
+@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;
+ }
+}
+.ds-outer-wrapper-breakpoint-override main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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);
+}
+
+.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-secondary-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-secondary-color);
+ text-decoration: underline;
+}
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0;
+}
+.top-sites-list a {
+ text-decoration: none;
+}
+.top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-element-hover-color);
+}
+@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: 802px) {
+ .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) {
+ .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) {
+ .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) {
+ .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) {
+ .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 {
+ width: 120px;
+ padding: 20px 16px 4px;
+ border-radius: 8px;
+ 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:is(:hover) .context-menu-button {
+ opacity: 1;
+}
+.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-text-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms;
+}
+.top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-element-hover-color);
+ fill: var(--newtab-primary-action-background);
+}
+.top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-background-color-secondary);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px;
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ 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-background-color-secondary);
+ 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: 32px;
+ width: 32px;
+ 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://global/skin/icons/search-glass.svg");
+ background-size: 16px;
+ background-color: var(--newtab-primary-action-background);
+ border-radius: 32px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 32px;
+ width: 32px;
+ bottom: -6px;
+ inset-inline-end: -6px;
+}
+.top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color);
+}
+.top-site-outer .title {
+ color: var(--newtab-text-primary-color);
+ padding-top: 8px;
+ font: caption;
+ text-align: center;
+ position: relative;
+}
+.top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-text-primary-color);
+}
+.top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.top-site-outer .title .sponsored-label {
+ color: var(--newtab-text-secondary-color);
+ 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://global/skin/icons/edit.svg");
+}
+.top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none;
+}
+.top-site-outer.dragged .title {
+ visibility: hidden;
+}
+
+.edit-topsites-wrapper .top-site-inner > .top-site-button > .tile {
+ border: 1px solid var(--newtab-border-color);
+}
+.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: 17px;
+}
+.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: var(--newtab-primary-action-background);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-border-color);
+ box-shadow: none;
+ opacity: 0.4;
+}
+.topsite-form .form-wrapper .invalid input[type=text] {
+ border: 1px solid var(--newtab-status-error);
+ box-shadow: 0 0 0 1px var(--newtab-status-error), 0 0 0 4px rgba(var(--newtab-status-error), 0.3);
+}
+.topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: var(--newtab-status-error);
+ 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: var(--newtab-status-error);
+ 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-border-color);
+ 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-primary-action-background);
+ 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-primary-action-background-dimmed);
+}
+.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-primary-action-background);
+}
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px);
+ }
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.topsite-impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 192px);
+ 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: 1250px) {
+ .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: 1506px) {
+ .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-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-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-text-primary-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-primary-action-background);
+ 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;
+}
+
+.search-wrapper {
+ padding: 34px 0 38px;
+}
+.only-search .search-wrapper {
+ padding: 0 0 38px;
+}
+.search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px;
+}
+.search-wrapper .logo-and-wordmark .logo {
+ display: inline-block;
+ height: 82px;
+ width: 82px;
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 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-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: 52px;
+ margin: 0 auto;
+ position: relative;
+ width: 200px;
+}
+@media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 360px;
+ }
+}
+@media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 600px;
+ }
+}
+@media (min-width: 1122px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 720px;
+ }
+}
+.search-wrapper .search-handoff-button,
+.search-wrapper input {
+ background: var(--newtab-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ padding-block: 0;
+ width: 100%;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-text-primary-color);
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-secondary-color);
+}
+.search-wrapper .search-handoff-button:dir(rtl),
+.search-wrapper input:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper .search-inner-wrapper:active input,
+.search-wrapper input:focus {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.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-text-secondary-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px;
+}
+.search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ cursor: pointer;
+}
+.search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+ border: 1px solid var(--newtab-primary-action-background);
+ border-radius: 0 8px 8px 0;
+}
+.search-wrapper .search-button:active {
+ background-color: var(--newtab-element-hover-color);
+}
+.search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1);
+}
+.search-wrapper.fake-focus:not(.search.disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-primary-action-background);
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.search-wrapper .search-handoff-button {
+ padding-inline-end: 15px;
+ color: var(--newtab-text-primary-color);
+ fill: var(--newtab-text-secondary-color);
+ -moz-context-properties: fill;
+}
+.search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px;
+}
+.search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color);
+}
+
+.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-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ border: solid 1px transparent;
+ 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;
+ width: 100%;
+}
+.search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+}
+.fake-focus:not(.search-disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+}
+.fake-focus:not(.search-disabled) .search-handoff-button .fake-caret {
+ display: block;
+}
+.search-disabled .search-handoff-button {
+ opacity: 0.5;
+ box-shadow: none;
+}
+.search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent;
+}
+.search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ inset: 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: 124px;
+ }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 254px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-color);
+ padding: 27px 0;
+ background-color: var(--newtab-overlay-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: 45px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ 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 .search-handoff-button {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px;
+ }
+}
+.contentSearchSuggestionTable {
+ 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);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchHeader {
+ color: var(--newtab-text-secondary-color);
+ background-color: var(--newtab-background-color-secondary);
+}
+.contentSearchSuggestionTable .contentSearchHeader,
+.contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-color);
+}
+.contentSearchSuggestionTable .contentSearchSuggestionsList {
+ color: var(--newtab-text-primary-color);
+ border: 0;
+}
+.contentSearchSuggestionTable .contentSearchOneOffsTable {
+ border-top: solid 1px var(--newtab-border-color);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-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-text-secondary-color);
+}
+.contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-color) 18%, var(--newtab-border-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-background-color-secondary);
+ 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-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-secondary-hover-color);
+}
+.context-menu > ul > li > a:active,
+.context-menu > ul > li > button:active {
+ background: var(--newtab-element-secondary-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 1px 4px 0 rgba(12, 12, 13, 0.2);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002;
+}
+
+@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 {
+ border: 0;
+ border-radius: 4px;
+ background-color: transparent;
+ padding: 15px;
+}
+.personalize-button:hover {
+ background-color: var(--newtab-element-hover-color);
+}
+.personalize-button:active {
+ background-color: var(--newtab-element-active-color);
+}
+.personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.personalize-button.personalize-animate-exit-done {
+ visibility: hidden;
+}
+
+.customize-menu {
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color-secondary);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default;
+}
+@media (prefers-reduced-motion: no-preference) {
+ .customize-menu {
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 250ms;
+ }
+}
+@media (forced-colors: active) {
+ .customize-menu {
+ border-inline-start: solid 1px;
+ }
+}
+.customize-menu:dir(rtl) {
+ transform: translateX(-435px);
+}
+.customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ visibility: visible;
+ transform: translateX(0);
+}
+.customize-menu.customize-animate-exit-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+}
+.customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--newtab-element-secondary-color);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ font-weight: 600;
+}
+.customize-menu .close-button:hover {
+ background-color: var(--newtab-element-secondary-hover-color);
+}
+.customize-menu .close-button:hover:active {
+ background-color: var(--newtab-element-secondary-active-color);
+}
+
+.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-element-secondary-color);
+}
+.home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+}
+@media (forced-colors: active) {
+ .home-section .section .sponsored-checkbox:checked {
+ fill: #000;
+ }
+}
+.home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: var(--newtab-element-secondary-color);
+}
+.home-section .section .selector {
+ color: var(--newtab-text-primary-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ margin-bottom: 2px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/arrow-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--newtab-background-color-secondary);
+}
+.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-element-secondary-color);
+}
+.home-section .section .slider::before {
+ position: absolute;
+ content: "";
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--newtab-primary-element-text-color);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+}
+.home-section .section .switch input:focus-visible + .slider {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-primary-action-background);
+}
+.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;
+}
+.home-section .section .more-info-top-wrapper .more-information,
+.home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: margin-top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895);
+}
+.home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px;
+}
+.home-section .divider {
+ border-top: 1px var(--newtab-border-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(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px;
+ text-decoration: underline;
+}
+@media (forced-colors: active) {
+ .home-section .external-link {
+ padding: 8px 10px;
+ padding-inline-start: 21px;
+ }
+}
+.home-section .external-link:dir(rtl) {
+ background-position-x: right;
+}
+.home-section .external-link:hover {
+ text-decoration: none;
+}
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+
+.card-outer {
+ background: var(--newtab-background-color-secondary);
+ border-radius: 8px;
+ 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-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.card-outer:hover {
+ box-shadow: none;
+ transition: none;
+}
+.card-outer.placeholder {
+ background: transparent;
+}
+.card-outer.placeholder .card-preview-image-outer,
+.card-outer.placeholder .card-context {
+ display: none;
+}
+.card-outer .card {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ height: 100%;
+}
+.card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%;
+}
+.card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+.card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-primary-action-background);
+}
+.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-primary-action-background);
+}
+.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: var(--newtab-element-secondary-color);
+ border-radius: 8px 8px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative;
+}
+.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-background-color-secondary);
+ 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: #EF4056;
+}
+.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;
+ }
+}
+
+.collapsible-section {
+ padding: 10px 25px;
+}
+.collapsible-section .section-title-container {
+ margin: 0;
+}
+.collapsible-section .section-title-container.has-subtitle {
+ display: flex;
+ flex-direction: column;
+}
+@media (min-width: 866px) {
+ .collapsible-section .section-title-container.has-subtitle {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ }
+}
+.collapsible-section .section-title {
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--newtab-text-primary-color);
+}
+.collapsible-section .section-title.grey-title {
+ color: var(--newtab-text-primary-color);
+ display: inline-block;
+ fill: var(--newtab-text-primary-color);
+ vertical-align: middle;
+}
+.collapsible-section .section-title .section-title-contents {
+ vertical-align: top;
+}
+@media (max-width: 609px) {
+ .collapsible-section .section-title .section-title-contents {
+ display: block;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper {
+ display: block;
+ text-align: center;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0;
+ }
+}
+.collapsible-section .section-sub-title {
+ font-size: 14px;
+ line-height: 16px;
+ color: var(--newtab-text-secondary-color);
+ opacity: 0.3;
+}
+.collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative;
+}
+.collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+}
+.collapsible-section .learn-more-link {
+ font-size: 13px;
+ margin-inline-start: 12px;
+}
+.collapsible-section .learn-more-link a {
+ color: var(--newtab-primary-action-background);
+}
+.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[data-section-id=topsites] .section-top-bar {
+ display: none;
+}
+@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://global/skin/icons/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-background-color-secondary);
+}
+.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: var(--newtab-element-hover-color);
+ 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-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-background-color-secondary);
+}
+.asrouter-admin table.errorReporting td {
+ padding: 4px;
+}
+.asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.asrouter-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-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-color);
+}
+.asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-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-background-color-secondary);
+ 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 var(--newtab-status-error);
+}
+.asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.asrouter-admin .helpLink a {
+ text-decoration: underline;
+}
+.asrouter-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.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: var(--newtab-primary-action-background);
+ 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.2307692308;
+}
+.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.2307692308;
+}
+.more-recommendations::after {
+ background: url("chrome://global/skin/icons/arrow-right-12.svg") no-repeat center center;
+ content: "";
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-primary-action-background);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px;
+}
+.more-recommendations:dir(rtl)::after {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+
+.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: var(--newtab-text-primary-color);
+ font-size: 17px;
+ font-weight: 600;
+ line-height: 20px;
+}
+.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-primary-action-background);
+ font-weight: 500;
+}
+.collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: none;
+}
+
+.ds-onboarding-container,
+.ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container,
+[lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none;
+}
+.ds-onboarding-container:not(.placeholder),
+.ds-card-grid .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+[lwt-newtab-brighttext] .ds-onboarding-container:not(.placeholder),
+[lwt-newtab-brighttext] .ds-card-grid .ds-card:not(.placeholder) {
+ background: var(--newtab-background-color-secondary);
+}
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img img,
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img .placeholder-image,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img img,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img .placeholder-image {
+ border-radius: 8px 8px 0 0;
+}
+
+.ds-onboarding-container {
+ padding-inline-start: 16px;
+ padding-inline-end: 16px;
+ margin-bottom: 24px;
+ position: relative;
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container {
+ padding-inline-end: 48px;
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container {
+ padding-inline-end: 56px;
+ }
+}
+.ds-onboarding-container .ds-onboarding {
+ position: static;
+ display: flex;
+}
+.ds-onboarding-container .ds-onboarding .ds-dismiss-button {
+ inset-inline-end: 8px;
+ top: 8px;
+}
+.ds-onboarding-container header {
+ display: flex;
+ margin: 32px 0 8px;
+ font-size: 17px;
+ line-height: 23.8px;
+ font-weight: 600;
+ color: #EF4056;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container header {
+ color: var(--newtab-background-color-primary);
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container header {
+ margin: 16px 0 8px;
+ display: block;
+ height: 24px;
+ }
+}
+.ds-onboarding-container p {
+ margin: 8px 0 16px;
+ font-size: 13px;
+ line-height: 19.5px;
+}
+.ds-onboarding-container .icon-pocket {
+ fill: #EF4056;
+ margin-top: 3px;
+ margin-inline-end: 8px;
+ height: 22px;
+ width: 22px;
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ background-size: contain;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ [lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (forced-colors: active) {
+ .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container .icon-pocket {
+ margin-top: -5px;
+ margin-inline-start: -2px;
+ margin-inline-end: 15px;
+ height: 30px;
+ width: 30px;
+ }
+}
+.ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif");
+ border-radius: 8px;
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: center;
+ height: 120px;
+ width: 200px;
+ margin-top: 16px;
+ margin-bottom: 16px;
+ margin-inline-start: 54px;
+ flex-shrink: 0;
+ display: none;
+}
+@media (min-resolution: 2x) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif");
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ display: block;
+ }
+}
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px;
+}
+.ds-card-grid.ds-card-grid-compact {
+ grid-gap: 20px;
+}
+@media (min-width: 610px) and (max-width: 866px) {
+ .ds-card-grid.ds-card-grid-recent-saves .ds-card:last-child:nth-child(2n-1) {
+ display: none;
+ }
+}
+.ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+ border-radius: 8px;
+}
+.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-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(4, 1fr);
+ }
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card.placeholder {
+ min-height: 247px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-footer {
+ margin-top: 8px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .info-wrap {
+ flex-grow: 0;
+}
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (max-height: 1065px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt {
+ display: none;
+ }
+}
+@media (max-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+@media (min-width: 1122px) and (max-height: 964px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder),
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) {
+ box-shadow: none;
+ background: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus {
+ box-shadow: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta {
+ padding: 12px 0 0;
+}
+
+.ds-layout .ds-sub-header {
+ margin-top: 24px;
+}
+.ds-layout .ds-sub-header .section-title-container {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ display: flex;
+}
+.ds-layout .ds-sub-header .section-sub-link {
+ color: var(--newtab-primary-action-background);
+ font-size: 14px;
+ line-height: 16px;
+ cursor: pointer;
+}
+.ds-layout .ds-sub-header .section-sub-link:hover {
+ text-decoration: underline;
+}
+.ds-layout .ds-sub-header .section-sub-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+
+.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: var(--newtab-text-primary-color);
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px;
+}
+.ds-collection-card-grid .ds-header .ds-context {
+ color: var(--newtab-text-secondary-color);
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px;
+}
+
+.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 .section .section-list .card-outer a {
+ text-decoration: none;
+}
+.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-navigation {
+ color: var(--newtab-text-primary-color);
+ font-size: 11.5px;
+ font-weight: 500;
+ line-height: 22px;
+ padding: 4px 0;
+}
+@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: none;
+}
+.ds-navigation ul li a:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px;
+}
+.ds-navigation .ds-navigation-privacy {
+ padding-inline-start: 6px;
+ float: inline-end;
+}
+.ds-navigation .ds-navigation-privacy:hover {
+ text-decoration: none;
+}
+.ds-navigation.ds-navigation-new-topics {
+ display: block;
+ padding-top: 32px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-header {
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: 700;
+ display: inline-block;
+ margin-bottom: 8px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ text-align: center;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 16px auto 28px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family span {
+ margin: 0 6px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo,
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ height: 20px;
+ width: 20px;
+ background-size: cover;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo {
+ background-image: url("chrome://activity-stream/content/data/content/assets/firefox.svg");
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #EF4056;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ font-weight: 400;
+ display: block;
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ display: inline;
+ }
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ margin-top: 43px;
+ }
+}
+.ds-navigation.ds-navigation-new-topics ul {
+ display: grid;
+ grid-gap: 0 24px;
+ grid-auto-flow: column;
+ grid-template: repeat(8, 1fr)/repeat(1, 1fr);
+}
+.ds-navigation.ds-navigation-new-topics ul li {
+ border-top: 1px solid var(--newtab-border-color);
+ line-height: 24px;
+ font-size: 13px;
+ font-weight: 500;
+}
+.ds-navigation.ds-navigation-new-topics ul li::after {
+ content: "";
+ padding: 0;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: none;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(1) {
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(3, 1fr)/repeat(2, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(3) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 866px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(3, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(odd) {
+ border-bottom: 0;
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(even) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(4, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: block;
+ }
+}
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px;
+}
+.ds-section-title .title {
+ color: var(--newtab-text-primary-color);
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+}
+.ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 4px;
+}
+
+.outer-wrapper .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-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px var(--newtab-background-color-secondary);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none;
+}
+.outer-wrapper .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-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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-card .context-menu-button:is(:active, :focus),
+.ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1);
+}
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0;
+}
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1;
+}
+.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-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1;
+}
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none;
+}
+.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-card {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+}
+.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 .card-stp-button-hover-background {
+ opacity: 0;
+ width: 100%;
+ position: absolute;
+ top: 0;
+ height: 0;
+ transition: opacity;
+ transition-duration: 0s;
+ padding-top: 50%;
+ pointer-events: none;
+ background: rgba(0, 0, 0, 0.4);
+ border-radius: 8px 8px 0 0;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button-position-wrapper {
+ position: absolute;
+ inset-inline-end: 10px;
+ top: 10px;
+ display: flex;
+ justify-content: end;
+ align-items: center;
+}
+.ds-card .card-stp-button-hover-background .icon-pocket-save,
+.ds-card .card-stp-button-hover-background .icon-pocket {
+ margin-inline-end: 4px;
+ height: 15px;
+ width: 15px;
+ background-size: 15px;
+ fill: #FFF;
+}
+.ds-card .card-stp-button-hover-background .context-menu-button {
+ position: static;
+ transition: none;
+ border-radius: 3px;
+}
+.ds-card .card-stp-button-hover-background .context-menu-position-container {
+ position: relative;
+}
+.ds-card .card-stp-button-hover-background .context-menu {
+ margin-inline-start: 18.5px;
+ inset-inline-start: auto;
+ position: absolute;
+ top: 20.25px;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button {
+ display: flex;
+ margin-inline-end: 7px;
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 16px;
+ background-color: #EF4056;
+ border: 0;
+ border-radius: 4px;
+ padding: 6px;
+ white-space: nowrap;
+ color: #FFF;
+}
+.ds-card .card-stp-button-hover-background button,
+.ds-card .card-stp-button-hover-background .context-menu {
+ pointer-events: auto;
+}
+.ds-card .card-stp-button-hover-background button {
+ cursor: pointer;
+}
+.ds-card.last-item .card-stp-button-hover-background .context-menu {
+ margin-inline-start: auto;
+ margin-inline-end: 18.5px;
+}
+.ds-card.active .card-stp-button-hover-background, .ds-card:focus-within .card-stp-button-hover-background, .ds-card:hover .card-stp-button-hover-background {
+ display: block;
+ opacity: 1;
+ transition-duration: 0.3s;
+}
+.ds-card.active .card-stp-button-hover-background .context-menu-button, .ds-card:focus-within .card-stp-button-hover-background .context-menu-button, .ds-card:hover .card-stp-button-hover-background .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+}
+.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;
+ text-decoration: none;
+}
+.ds-card .ds-card-link:hover header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.ds-card .ds-card-link:focus header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:active header {
+ color: var(--newtab-primary-element-active-color);
+}
+.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: var(--newtab-text-secondary-color);
+}
+.ds-card .meta .source span {
+ display: inline-block;
+}
+.ds-card .meta .new-sponsored-label {
+ font-size: 13px;
+ margin-bottom: 2px;
+}
+.ds-card.ds-card-title-lines-2 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 2;
+ line-height: 24px;
+}
+.ds-card.ds-card-title-lines-1 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 1;
+ line-height: 24px;
+}
+.ds-card.ds-card-desc-lines-2 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+}
+.ds-card.ds-card-desc-lines-1 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+}
+.ds-card.ds-card-compact-image .img {
+ padding-top: 47%;
+}
+.ds-card.ds-card-image-gradient img {
+ mask-image: linear-gradient(to top, rgba(0, 0, 0, 0), black 40px);
+}
+.ds-card.ds-card-image-gradient .meta {
+ padding: 3px 15px 11px;
+}
+.ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: var(--newtab-text-primary-color);
+}
+.ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+}
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative;
+}
+.story-footer .story-sponsored-label span {
+ display: inline-block;
+}
+.story-footer .story-sponsored-label,
+.story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: var(--newtab-text-secondary-color);
+}
+.story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px;
+}
+.story-footer .status-message .story-badge-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 16px;
+ margin-inline-end: 6px;
+}
+.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: var(--newtab-text-secondary-color);
+ 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-animate-enter-active .story-badge-icon,
+.story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s;
+}
+@keyframes color {
+ 0% {
+ color: var(--newtab-status-success);
+ fill: var(--newtab-status-success);
+ }
+ 100% {
+ color: var(--newtab-text-secondary-color);
+ fill: var(--newtab-text-secondary-color);
+ }
+}
+
+.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 .placeholder-image,
+.ds-image .broken-image {
+ background-color: var(--newtab-element-secondary-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.ds-image .placeholder-image {
+ overflow: hidden;
+ background-color: var(--placeholderBackgroundColor);
+}
+.ds-image .placeholder-image::before {
+ content: "";
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-swoosh.svg");
+ background-repeat: no-repeat;
+ background-position: center;
+ transform: rotate(var(--placeholderBackgroundRotation));
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ margin-left: var(--placeholderBackgroundOffsetx);
+ margin-top: var(--placeholderBackgroundOffsety);
+ background-size: var(--placeholderBackgroundScale);
+}
+
+.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: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: CurrentColor;
+ }
+}
+.ds-dismiss .ds-dismiss-button:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-dismiss .ds-dismiss-button:active {
+ background: var(--newtab-element-active-color);
+}
+.ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+}
+
+.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: var(--newtab-text-secondary-color);
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat;
+}
+.ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: var(--newtab-text-secondary-color);
+ font-weight: 600;
+ padding-right: 12px;
+}
+.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-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-button-secondary-color);
+ color: var(--newtab-text-primary-color);
+ 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 var(--newtab-element-secondary-color);
+ 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-text-secondary-color);
+}
+.section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-element-secondary-color);
+ color: transparent;
+ 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: var(--newtab-element-hover-color);
+}
+.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 {
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px;
+}
+.ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: var(--newtab-text-primary-color);
+}
+
+.ds-chevron-link {
+ color: var(--newtab-primary-action-background);
+ display: inline-block;
+ outline: 0;
+}
+.ds-chevron-link:hover {
+ text-decoration: underline;
+}
+.ds-chevron-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:active::after {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ border-radius: 2px;
+}
+.ds-chevron-link::after {
+ background-color: var(--newtab-primary-action-background);
+ content: " ";
+ mask: url("chrome://global/skin/icons/arrow-right-12.svg") 0 -8px no-repeat;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block;
+}
+
+.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: var(--newtab-text-secondary-color);
+ 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: var(--newtab-primary-action-background);
+ 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: var(--newtab-primary-action-background);
+ 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://global/skin/icons/info.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;
+}
+
+.ds-privacy-link {
+ text-align: center;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 24px;
+}
+.ds-privacy-link a:hover {
+ text-decoration: none;
+}
+
+.ds-topics-widget {
+ display: flex;
+ position: relative;
+ flex-direction: column;
+}
+.ds-topics-widget .ds-topics-widget-header {
+ font-size: 18px;
+ line-height: 20px;
+}
+.ds-topics-widget hr {
+ background-color: color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ height: 1px;
+ border: 0;
+ margin: 10px 0 0;
+}
+.ds-topics-widget .ds-topics-widget-list-container {
+ flex-grow: 1;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul {
+ margin: 14px 0 0;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ grid-gap: 10px;
+ flex-wrap: wrap;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li {
+ display: flex;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a {
+ font-size: 14px;
+ line-height: 16px;
+ text-decoration: none;
+ padding: 8px 15px;
+ background: var(--newtab-background-color-secondary);
+ border: 1px solid color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ color: var(--newtab-text-primary-color);
+ border-radius: 8px;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: box-shadow 150ms;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+}
+@media (min-width: 610px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: none;
+ }
+}
+@media (min-width: 1122px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+ }
+}
+.ds-topics-widget .ds-topics-widget-button {
+ margin: 14px 0 0;
+ font-size: 16px;
+ line-height: 24px;
+ text-align: center;
+ padding: 8px;
+ border-radius: 4px;
+ background-color: var(--newtab-primary-action-background-pocket);
+ border: 0;
+}
+.ds-topics-widget .ds-topics-widget-button:hover {
+ background: var(--newtab-primary-element-hover-pocket-color);
+}
+.ds-topics-widget .ds-topics-widget-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-pocket-dimmed), 0 0 0 1px var(--newtab-primary-action-background-pocket);
+ transition: box-shadow 150ms;
+}
+
+.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-primary-action-background);
+ background-color: var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+}
+.ASRouterButton.primary:hover {
+ background-color: var(--newtab-primary-element-hover-color);
+}
+.ASRouterButton.primary:active {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ASRouterButton.slim {
+ border: 1px solid var(--newtab-border-color);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px;
+}
+.ASRouterButton.slim:hover, .ASRouterButton.slim:focus {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-background-color-secondary);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid transparent;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center;
+}
+.SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-primary-action-background);
+}
+.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: 20px;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://global/skin/icons/close.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: var(--newtab-text-primary-color);
+ background: var(--newtab-background-color-secondary);
+ 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-background-color-secondary);
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ 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: var(--newtab-text-primary-color);
+ 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 var(--newtab-border-color);
+ 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 var(--newtab-element-secondary-color);
+ 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: 0 2px 6px rgba(0, 0, 0, 0.15);
+ 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 5px var(--newtab-element-secondary-color);
+ 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: var(--newtab-text-emphasis-text-color);
+ font-style: normal;
+ background: var(--newtab-text-emphasis-background);
+}
+.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.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-block: 8px;
+}
+.SimpleSnippet.bold .icon, .SimpleSnippet.takeover .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-text-primary-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0;
+}
+.SimpleSnippet .section-title a {
+ color: var(--newtab-text-primary-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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-text-primary-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: var(--newtab-text-primary-color);
+ margin-inline-end: 18px;
+ border: 1px solid var(--newtab-border-color);
+ padding: 5px 14px;
+ background: var(--newtab-background-color-secondary);
+ cursor: pointer;
+}
+.EOYSnippetForm input[type=radio] {
+ opacity: 0;
+ margin-inline-end: -18px;
+}
+.EOYSnippetForm input[type=radio]:checked + .donation-amount {
+ background: var(--newtab-text-secondary-color);
+ color: var(--newtab-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+}
+.EOYSnippetForm input[type=radio]:checked:focus + .donation-amount, .EOYSnippetForm input[type=radio]:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-primary-action-background);
+}
+.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..dbe6e65f50
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-mac.css
@@ -0,0 +1,4816 @@
+@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;
+}
+
+:root {
+ --newtab-background-color: #F9F9FB;
+ --newtab-background-color-secondary: #FFF;
+ --newtab-text-primary-color: #15141a;
+ --newtab-primary-action-background: #0061e0;
+ --newtab-primary-action-background-pocket: #008078;
+ --newtab-text-secondary-color: color-mix(in srgb, var(--newtab-text-primary-color) 70%, transparent);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 90%, #000);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 80%, #000);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 5%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 12%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 90%, #000);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 90%, #000);
+ --newtab-primary-element-active-color: color-mix(in srgb, var(--newtab-primary-action-background) 80%, #000);
+ --newtab-primary-element-text-color: #FFF;
+ --newtab-primary-action-background-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 25%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #000);
+ --newtab-wordmark-color: #20123A;
+ --newtab-status-success: #058B00;
+ --newtab-status-error: #D70022;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-overlay-color: color-mix(in srgb, var(--newtab-background-color) 85%, transparent);
+ --newtab-text-emphasis-background: #FFE900;
+ --newtab-text-emphasis-text-color: #0C0C0D;
+ --newtab-textbox-focus-color: var(--newtab-primary-action-background);
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px var(--newtab-primary-action-background), 0 0 0 4px rgba(var(--newtab-primary-action-background), 0.3);
+ --newtab-button-secondary-color: inherit;
+}
+:root[lwt-newtab-brighttext] {
+ --newtab-background-color: #2B2A33;
+ --newtab-background-color-secondary: #42414d;
+ --newtab-text-primary-color: #fbfbfe;
+ --newtab-primary-action-background: #00ddff;
+ --newtab-primary-action-background-pocket: #00ddff;
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 55%, #FFF);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 55%, #FFF);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 80%, #FFF);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 60%, #FFF);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 10%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 17%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 30%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #FFF);
+ --newtab-primary-element-text-color: #2b2a33;
+ --newtab-wordmark-color: #fbfbfe;
+ --newtab-status-success: #7C6;
+}
+
+@media (prefers-contrast) {
+ :root {
+ --newtab-text-secondary-color: var(--newtab-text-primary-color);
+ }
+}
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-text-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-text-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://global/skin/icons/close-fill.svg");
+}
+.icon.icon-delete {
+ background-image: url("chrome://global/skin/icons/delete.svg");
+}
+.icon.icon-search {
+ background-image: url("chrome://global/skin/icons/search-glass.svg");
+}
+.icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-20.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://global/skin/icons/close.svg");
+}
+.icon.icon-info {
+ background-image: url("chrome://global/skin/icons/info.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://global/skin/icons/edit.svg");
+}
+.icon.icon-pocket {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+}
+.icon.icon-pocket-save {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #FFF;
+}
+.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://browser/skin/trending.svg");
+ transform: translateY(2px);
+}
+.icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg");
+}
+.icon.icon-topsites {
+ background-image: url("chrome://browser/skin/topsites.svg");
+}
+.icon.icon-pin-small {
+ background-image: url("chrome://browser/skin/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/downloads.svg");
+}
+.icon.icon-copy {
+ background-image: url("chrome://global/skin/icons/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://global/skin/icons/highlights.svg");
+}
+.icon.icon-arrowhead-down {
+ background-image: url("chrome://global/skin/icons/arrow-down.svg");
+}
+.icon.icon-arrowhead-down-small {
+ background-image: url("chrome://global/skin/icons/arrow-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://global/skin/icons/arrow-right-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small:dir(rtl) {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+.icon.icon-arrowhead-up {
+ background-image: url("chrome://global/skin/icons/arrow-up.svg");
+}
+.icon.icon-add {
+ background-image: url("chrome://global/skin/icons/plus.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://global/skin/icons/arrow-right-12.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;
+}
+
+.inner-border {
+ border: 1px solid var(--newtab-border-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-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-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-element-secondary-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-primary-action-background);
+ border: solid 1px var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+ 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-primary-action-background);
+}
+.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-primary-action-background);
+}
+
+main {
+ margin: auto;
+ width: 274px;
+ padding: 0;
+}
+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;
+ }
+}
+main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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: 0;
+}
+@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;
+ }
+}
+.ds-outer-wrapper-breakpoint-override main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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);
+}
+
+.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-secondary-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-secondary-color);
+ text-decoration: underline;
+}
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0;
+}
+.top-sites-list a {
+ text-decoration: none;
+}
+.top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-element-hover-color);
+}
+@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: 802px) {
+ .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) {
+ .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) {
+ .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) {
+ .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) {
+ .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 {
+ width: 120px;
+ padding: 20px 16px 4px;
+ border-radius: 8px;
+ 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:is(:hover) .context-menu-button {
+ opacity: 1;
+}
+.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-text-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms;
+}
+.top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-element-hover-color);
+ fill: var(--newtab-primary-action-background);
+}
+.top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-background-color-secondary);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px;
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ 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-background-color-secondary);
+ 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: 32px;
+ width: 32px;
+ 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://global/skin/icons/search-glass.svg");
+ background-size: 16px;
+ background-color: var(--newtab-primary-action-background);
+ border-radius: 32px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 32px;
+ width: 32px;
+ bottom: -6px;
+ inset-inline-end: -6px;
+}
+.top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color);
+}
+.top-site-outer .title {
+ color: var(--newtab-text-primary-color);
+ padding-top: 8px;
+ font: caption;
+ text-align: center;
+ position: relative;
+}
+.top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-text-primary-color);
+}
+.top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.top-site-outer .title .sponsored-label {
+ color: var(--newtab-text-secondary-color);
+ 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://global/skin/icons/edit.svg");
+}
+.top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none;
+}
+.top-site-outer.dragged .title {
+ visibility: hidden;
+}
+
+.edit-topsites-wrapper .top-site-inner > .top-site-button > .tile {
+ border: 1px solid var(--newtab-border-color);
+}
+.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: 17px;
+}
+.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: var(--newtab-primary-action-background);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-border-color);
+ box-shadow: none;
+ opacity: 0.4;
+}
+.topsite-form .form-wrapper .invalid input[type=text] {
+ border: 1px solid var(--newtab-status-error);
+ box-shadow: 0 0 0 1px var(--newtab-status-error), 0 0 0 4px rgba(var(--newtab-status-error), 0.3);
+}
+.topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: var(--newtab-status-error);
+ 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: var(--newtab-status-error);
+ 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-border-color);
+ 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-primary-action-background);
+ 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-primary-action-background-dimmed);
+}
+.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-primary-action-background);
+}
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px);
+ }
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.topsite-impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 192px);
+ 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: 1250px) {
+ .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: 1506px) {
+ .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-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-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-text-primary-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-primary-action-background);
+ 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;
+}
+
+.search-wrapper {
+ padding: 34px 0 38px;
+}
+.only-search .search-wrapper {
+ padding: 0 0 38px;
+}
+.search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px;
+}
+.search-wrapper .logo-and-wordmark .logo {
+ display: inline-block;
+ height: 82px;
+ width: 82px;
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 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-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: 52px;
+ margin: 0 auto;
+ position: relative;
+ width: 200px;
+}
+@media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 360px;
+ }
+}
+@media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 600px;
+ }
+}
+@media (min-width: 1122px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 720px;
+ }
+}
+.search-wrapper .search-handoff-button,
+.search-wrapper input {
+ background: var(--newtab-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ padding-block: 0;
+ width: 100%;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-text-primary-color);
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-secondary-color);
+}
+.search-wrapper .search-handoff-button:dir(rtl),
+.search-wrapper input:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper .search-inner-wrapper:active input,
+.search-wrapper input:focus {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.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-text-secondary-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px;
+}
+.search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ cursor: pointer;
+}
+.search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+ border: 1px solid var(--newtab-primary-action-background);
+ border-radius: 0 8px 8px 0;
+}
+.search-wrapper .search-button:active {
+ background-color: var(--newtab-element-hover-color);
+}
+.search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1);
+}
+.search-wrapper.fake-focus:not(.search.disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-primary-action-background);
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.search-wrapper .search-handoff-button {
+ padding-inline-end: 15px;
+ color: var(--newtab-text-primary-color);
+ fill: var(--newtab-text-secondary-color);
+ -moz-context-properties: fill;
+}
+.search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px;
+}
+.search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color);
+}
+
+.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-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ border: solid 1px transparent;
+ 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;
+ width: 100%;
+}
+.search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+}
+.fake-focus:not(.search-disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+}
+.fake-focus:not(.search-disabled) .search-handoff-button .fake-caret {
+ display: block;
+}
+.search-disabled .search-handoff-button {
+ opacity: 0.5;
+ box-shadow: none;
+}
+.search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent;
+}
+.search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ inset: 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: 124px;
+ }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 254px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-color);
+ padding: 27px 0;
+ background-color: var(--newtab-overlay-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: 45px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ 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 .search-handoff-button {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px;
+ }
+}
+.contentSearchSuggestionTable {
+ 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);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchHeader {
+ color: var(--newtab-text-secondary-color);
+ background-color: var(--newtab-background-color-secondary);
+}
+.contentSearchSuggestionTable .contentSearchHeader,
+.contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-color);
+}
+.contentSearchSuggestionTable .contentSearchSuggestionsList {
+ color: var(--newtab-text-primary-color);
+ border: 0;
+}
+.contentSearchSuggestionTable .contentSearchOneOffsTable {
+ border-top: solid 1px var(--newtab-border-color);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-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-text-secondary-color);
+}
+.contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-color) 18%, var(--newtab-border-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-background-color-secondary);
+ 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-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-secondary-hover-color);
+}
+.context-menu > ul > li > a:active,
+.context-menu > ul > li > button:active {
+ background: var(--newtab-element-secondary-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 1px 4px 0 rgba(12, 12, 13, 0.2);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002;
+}
+
+@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 {
+ border: 0;
+ border-radius: 4px;
+ background-color: transparent;
+ padding: 15px;
+}
+.personalize-button:hover {
+ background-color: var(--newtab-element-hover-color);
+}
+.personalize-button:active {
+ background-color: var(--newtab-element-active-color);
+}
+.personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.personalize-button.personalize-animate-exit-done {
+ visibility: hidden;
+}
+
+.customize-menu {
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color-secondary);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default;
+}
+@media (prefers-reduced-motion: no-preference) {
+ .customize-menu {
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 250ms;
+ }
+}
+@media (forced-colors: active) {
+ .customize-menu {
+ border-inline-start: solid 1px;
+ }
+}
+.customize-menu:dir(rtl) {
+ transform: translateX(-435px);
+}
+.customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ visibility: visible;
+ transform: translateX(0);
+}
+.customize-menu.customize-animate-exit-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+}
+.customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--newtab-element-secondary-color);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ font-weight: 600;
+}
+.customize-menu .close-button:hover {
+ background-color: var(--newtab-element-secondary-hover-color);
+}
+.customize-menu .close-button:hover:active {
+ background-color: var(--newtab-element-secondary-active-color);
+}
+
+.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-element-secondary-color);
+}
+.home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+}
+@media (forced-colors: active) {
+ .home-section .section .sponsored-checkbox:checked {
+ fill: #000;
+ }
+}
+.home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: var(--newtab-element-secondary-color);
+}
+.home-section .section .selector {
+ color: var(--newtab-text-primary-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ margin-bottom: 2px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/arrow-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--newtab-background-color-secondary);
+}
+.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-element-secondary-color);
+}
+.home-section .section .slider::before {
+ position: absolute;
+ content: "";
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--newtab-primary-element-text-color);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+}
+.home-section .section .switch input:focus-visible + .slider {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-primary-action-background);
+}
+.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;
+}
+.home-section .section .more-info-top-wrapper .more-information,
+.home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: margin-top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895);
+}
+.home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px;
+}
+.home-section .divider {
+ border-top: 1px var(--newtab-border-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(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px;
+ text-decoration: underline;
+}
+@media (forced-colors: active) {
+ .home-section .external-link {
+ padding: 8px 10px;
+ padding-inline-start: 21px;
+ }
+}
+.home-section .external-link:dir(rtl) {
+ background-position-x: right;
+}
+.home-section .external-link:hover {
+ text-decoration: none;
+}
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+
+.card-outer {
+ background: var(--newtab-background-color-secondary);
+ border-radius: 8px;
+ 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-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.card-outer:hover {
+ box-shadow: none;
+ transition: none;
+}
+.card-outer.placeholder {
+ background: transparent;
+}
+.card-outer.placeholder .card-preview-image-outer,
+.card-outer.placeholder .card-context {
+ display: none;
+}
+.card-outer .card {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ height: 100%;
+}
+.card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%;
+}
+.card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+.card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-primary-action-background);
+}
+.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-primary-action-background);
+}
+.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: var(--newtab-element-secondary-color);
+ border-radius: 8px 8px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative;
+}
+.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-background-color-secondary);
+ 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: #EF4056;
+}
+.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;
+ }
+}
+
+.collapsible-section {
+ padding: 10px 25px;
+}
+.collapsible-section .section-title-container {
+ margin: 0;
+}
+.collapsible-section .section-title-container.has-subtitle {
+ display: flex;
+ flex-direction: column;
+}
+@media (min-width: 866px) {
+ .collapsible-section .section-title-container.has-subtitle {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ }
+}
+.collapsible-section .section-title {
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--newtab-text-primary-color);
+}
+.collapsible-section .section-title.grey-title {
+ color: var(--newtab-text-primary-color);
+ display: inline-block;
+ fill: var(--newtab-text-primary-color);
+ vertical-align: middle;
+}
+.collapsible-section .section-title .section-title-contents {
+ vertical-align: top;
+}
+@media (max-width: 609px) {
+ .collapsible-section .section-title .section-title-contents {
+ display: block;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper {
+ display: block;
+ text-align: center;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0;
+ }
+}
+.collapsible-section .section-sub-title {
+ font-size: 14px;
+ line-height: 16px;
+ color: var(--newtab-text-secondary-color);
+ opacity: 0.3;
+}
+.collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative;
+}
+.collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+}
+.collapsible-section .learn-more-link {
+ font-size: 13px;
+ margin-inline-start: 12px;
+}
+.collapsible-section .learn-more-link a {
+ color: var(--newtab-primary-action-background);
+}
+.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[data-section-id=topsites] .section-top-bar {
+ display: none;
+}
+@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://global/skin/icons/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-background-color-secondary);
+}
+.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: var(--newtab-element-hover-color);
+ 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-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-background-color-secondary);
+}
+.asrouter-admin table.errorReporting td {
+ padding: 4px;
+}
+.asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.asrouter-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-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-color);
+}
+.asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-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-background-color-secondary);
+ 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 var(--newtab-status-error);
+}
+.asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.asrouter-admin .helpLink a {
+ text-decoration: underline;
+}
+.asrouter-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.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: var(--newtab-primary-action-background);
+ 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.2307692308;
+}
+.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.2307692308;
+}
+.more-recommendations::after {
+ background: url("chrome://global/skin/icons/arrow-right-12.svg") no-repeat center center;
+ content: "";
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-primary-action-background);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px;
+}
+.more-recommendations:dir(rtl)::after {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+
+.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: var(--newtab-text-primary-color);
+ font-size: 17px;
+ font-weight: 600;
+ line-height: 20px;
+}
+.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-primary-action-background);
+ font-weight: 500;
+}
+.collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: none;
+}
+
+.ds-onboarding-container,
+.ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container,
+[lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none;
+}
+.ds-onboarding-container:not(.placeholder),
+.ds-card-grid .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+[lwt-newtab-brighttext] .ds-onboarding-container:not(.placeholder),
+[lwt-newtab-brighttext] .ds-card-grid .ds-card:not(.placeholder) {
+ background: var(--newtab-background-color-secondary);
+}
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img img,
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img .placeholder-image,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img img,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img .placeholder-image {
+ border-radius: 8px 8px 0 0;
+}
+
+.ds-onboarding-container {
+ padding-inline-start: 16px;
+ padding-inline-end: 16px;
+ margin-bottom: 24px;
+ position: relative;
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container {
+ padding-inline-end: 48px;
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container {
+ padding-inline-end: 56px;
+ }
+}
+.ds-onboarding-container .ds-onboarding {
+ position: static;
+ display: flex;
+}
+.ds-onboarding-container .ds-onboarding .ds-dismiss-button {
+ inset-inline-end: 8px;
+ top: 8px;
+}
+.ds-onboarding-container header {
+ display: flex;
+ margin: 32px 0 8px;
+ font-size: 17px;
+ line-height: 23.8px;
+ font-weight: 600;
+ color: #EF4056;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container header {
+ color: var(--newtab-background-color-primary);
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container header {
+ margin: 16px 0 8px;
+ display: block;
+ height: 24px;
+ }
+}
+.ds-onboarding-container p {
+ margin: 8px 0 16px;
+ font-size: 13px;
+ line-height: 19.5px;
+}
+.ds-onboarding-container .icon-pocket {
+ fill: #EF4056;
+ margin-top: 3px;
+ margin-inline-end: 8px;
+ height: 22px;
+ width: 22px;
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ background-size: contain;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ [lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (forced-colors: active) {
+ .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container .icon-pocket {
+ margin-top: -5px;
+ margin-inline-start: -2px;
+ margin-inline-end: 15px;
+ height: 30px;
+ width: 30px;
+ }
+}
+.ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif");
+ border-radius: 8px;
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: center;
+ height: 120px;
+ width: 200px;
+ margin-top: 16px;
+ margin-bottom: 16px;
+ margin-inline-start: 54px;
+ flex-shrink: 0;
+ display: none;
+}
+@media (min-resolution: 2x) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif");
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ display: block;
+ }
+}
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px;
+}
+.ds-card-grid.ds-card-grid-compact {
+ grid-gap: 20px;
+}
+@media (min-width: 610px) and (max-width: 866px) {
+ .ds-card-grid.ds-card-grid-recent-saves .ds-card:last-child:nth-child(2n-1) {
+ display: none;
+ }
+}
+.ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+ border-radius: 8px;
+}
+.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-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(4, 1fr);
+ }
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card.placeholder {
+ min-height: 247px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-footer {
+ margin-top: 8px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .info-wrap {
+ flex-grow: 0;
+}
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (max-height: 1065px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt {
+ display: none;
+ }
+}
+@media (max-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+@media (min-width: 1122px) and (max-height: 964px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder),
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) {
+ box-shadow: none;
+ background: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus {
+ box-shadow: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta {
+ padding: 12px 0 0;
+}
+
+.ds-layout .ds-sub-header {
+ margin-top: 24px;
+}
+.ds-layout .ds-sub-header .section-title-container {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ display: flex;
+}
+.ds-layout .ds-sub-header .section-sub-link {
+ color: var(--newtab-primary-action-background);
+ font-size: 14px;
+ line-height: 16px;
+ cursor: pointer;
+}
+.ds-layout .ds-sub-header .section-sub-link:hover {
+ text-decoration: underline;
+}
+.ds-layout .ds-sub-header .section-sub-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+
+.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: var(--newtab-text-primary-color);
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px;
+}
+.ds-collection-card-grid .ds-header .ds-context {
+ color: var(--newtab-text-secondary-color);
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px;
+}
+
+.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 .section .section-list .card-outer a {
+ text-decoration: none;
+}
+.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-navigation {
+ color: var(--newtab-text-primary-color);
+ font-size: 11.5px;
+ font-weight: 500;
+ line-height: 22px;
+ padding: 4px 0;
+}
+@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: none;
+}
+.ds-navigation ul li a:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px;
+}
+.ds-navigation .ds-navigation-privacy {
+ padding-inline-start: 6px;
+ float: inline-end;
+}
+.ds-navigation .ds-navigation-privacy:hover {
+ text-decoration: none;
+}
+.ds-navigation.ds-navigation-new-topics {
+ display: block;
+ padding-top: 32px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-header {
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: 700;
+ display: inline-block;
+ margin-bottom: 8px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ text-align: center;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 16px auto 28px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family span {
+ margin: 0 6px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo,
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ height: 20px;
+ width: 20px;
+ background-size: cover;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo {
+ background-image: url("chrome://activity-stream/content/data/content/assets/firefox.svg");
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #EF4056;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ font-weight: 400;
+ display: block;
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ display: inline;
+ }
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ margin-top: 43px;
+ }
+}
+.ds-navigation.ds-navigation-new-topics ul {
+ display: grid;
+ grid-gap: 0 24px;
+ grid-auto-flow: column;
+ grid-template: repeat(8, 1fr)/repeat(1, 1fr);
+}
+.ds-navigation.ds-navigation-new-topics ul li {
+ border-top: 1px solid var(--newtab-border-color);
+ line-height: 24px;
+ font-size: 13px;
+ font-weight: 500;
+}
+.ds-navigation.ds-navigation-new-topics ul li::after {
+ content: "";
+ padding: 0;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: none;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(1) {
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(3, 1fr)/repeat(2, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(3) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 866px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(3, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(odd) {
+ border-bottom: 0;
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(even) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(4, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: block;
+ }
+}
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px;
+}
+.ds-section-title .title {
+ color: var(--newtab-text-primary-color);
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+}
+.ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 4px;
+}
+
+.outer-wrapper .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-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px var(--newtab-background-color-secondary);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none;
+}
+.outer-wrapper .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-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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-card .context-menu-button:is(:active, :focus),
+.ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1);
+}
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0;
+}
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1;
+}
+.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-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1;
+}
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none;
+}
+.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-card {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+}
+.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 .card-stp-button-hover-background {
+ opacity: 0;
+ width: 100%;
+ position: absolute;
+ top: 0;
+ height: 0;
+ transition: opacity;
+ transition-duration: 0s;
+ padding-top: 50%;
+ pointer-events: none;
+ background: rgba(0, 0, 0, 0.4);
+ border-radius: 8px 8px 0 0;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button-position-wrapper {
+ position: absolute;
+ inset-inline-end: 10px;
+ top: 10px;
+ display: flex;
+ justify-content: end;
+ align-items: center;
+}
+.ds-card .card-stp-button-hover-background .icon-pocket-save,
+.ds-card .card-stp-button-hover-background .icon-pocket {
+ margin-inline-end: 4px;
+ height: 15px;
+ width: 15px;
+ background-size: 15px;
+ fill: #FFF;
+}
+.ds-card .card-stp-button-hover-background .context-menu-button {
+ position: static;
+ transition: none;
+ border-radius: 3px;
+}
+.ds-card .card-stp-button-hover-background .context-menu-position-container {
+ position: relative;
+}
+.ds-card .card-stp-button-hover-background .context-menu {
+ margin-inline-start: 18.5px;
+ inset-inline-start: auto;
+ position: absolute;
+ top: 20.25px;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button {
+ display: flex;
+ margin-inline-end: 7px;
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 16px;
+ background-color: #EF4056;
+ border: 0;
+ border-radius: 4px;
+ padding: 6px;
+ white-space: nowrap;
+ color: #FFF;
+}
+.ds-card .card-stp-button-hover-background button,
+.ds-card .card-stp-button-hover-background .context-menu {
+ pointer-events: auto;
+}
+.ds-card .card-stp-button-hover-background button {
+ cursor: pointer;
+}
+.ds-card.last-item .card-stp-button-hover-background .context-menu {
+ margin-inline-start: auto;
+ margin-inline-end: 18.5px;
+}
+.ds-card.active .card-stp-button-hover-background, .ds-card:focus-within .card-stp-button-hover-background, .ds-card:hover .card-stp-button-hover-background {
+ display: block;
+ opacity: 1;
+ transition-duration: 0.3s;
+}
+.ds-card.active .card-stp-button-hover-background .context-menu-button, .ds-card:focus-within .card-stp-button-hover-background .context-menu-button, .ds-card:hover .card-stp-button-hover-background .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+}
+.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;
+ text-decoration: none;
+}
+.ds-card .ds-card-link:hover header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.ds-card .ds-card-link:focus header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:active header {
+ color: var(--newtab-primary-element-active-color);
+}
+.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: var(--newtab-text-secondary-color);
+}
+.ds-card .meta .source span {
+ display: inline-block;
+}
+.ds-card .meta .new-sponsored-label {
+ font-size: 13px;
+ margin-bottom: 2px;
+}
+.ds-card.ds-card-title-lines-2 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 2;
+ line-height: 24px;
+}
+.ds-card.ds-card-title-lines-1 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 1;
+ line-height: 24px;
+}
+.ds-card.ds-card-desc-lines-2 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+}
+.ds-card.ds-card-desc-lines-1 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+}
+.ds-card.ds-card-compact-image .img {
+ padding-top: 47%;
+}
+.ds-card.ds-card-image-gradient img {
+ mask-image: linear-gradient(to top, rgba(0, 0, 0, 0), black 40px);
+}
+.ds-card.ds-card-image-gradient .meta {
+ padding: 3px 15px 11px;
+}
+.ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: var(--newtab-text-primary-color);
+}
+.ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+}
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative;
+}
+.story-footer .story-sponsored-label span {
+ display: inline-block;
+}
+.story-footer .story-sponsored-label,
+.story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: var(--newtab-text-secondary-color);
+}
+.story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px;
+}
+.story-footer .status-message .story-badge-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 16px;
+ margin-inline-end: 6px;
+}
+.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: var(--newtab-text-secondary-color);
+ 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-animate-enter-active .story-badge-icon,
+.story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s;
+}
+@keyframes color {
+ 0% {
+ color: var(--newtab-status-success);
+ fill: var(--newtab-status-success);
+ }
+ 100% {
+ color: var(--newtab-text-secondary-color);
+ fill: var(--newtab-text-secondary-color);
+ }
+}
+
+.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 .placeholder-image,
+.ds-image .broken-image {
+ background-color: var(--newtab-element-secondary-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.ds-image .placeholder-image {
+ overflow: hidden;
+ background-color: var(--placeholderBackgroundColor);
+}
+.ds-image .placeholder-image::before {
+ content: "";
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-swoosh.svg");
+ background-repeat: no-repeat;
+ background-position: center;
+ transform: rotate(var(--placeholderBackgroundRotation));
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ margin-left: var(--placeholderBackgroundOffsetx);
+ margin-top: var(--placeholderBackgroundOffsety);
+ background-size: var(--placeholderBackgroundScale);
+}
+
+.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: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: CurrentColor;
+ }
+}
+.ds-dismiss .ds-dismiss-button:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-dismiss .ds-dismiss-button:active {
+ background: var(--newtab-element-active-color);
+}
+.ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+}
+
+.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: var(--newtab-text-secondary-color);
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat;
+}
+.ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: var(--newtab-text-secondary-color);
+ font-weight: 600;
+ padding-right: 12px;
+}
+.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-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-button-secondary-color);
+ color: var(--newtab-text-primary-color);
+ 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 var(--newtab-element-secondary-color);
+ 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-text-secondary-color);
+}
+.section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-element-secondary-color);
+ color: transparent;
+ 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: var(--newtab-element-hover-color);
+}
+.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 {
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px;
+}
+.ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: var(--newtab-text-primary-color);
+}
+
+.ds-chevron-link {
+ color: var(--newtab-primary-action-background);
+ display: inline-block;
+ outline: 0;
+}
+.ds-chevron-link:hover {
+ text-decoration: underline;
+}
+.ds-chevron-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:active::after {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ border-radius: 2px;
+}
+.ds-chevron-link::after {
+ background-color: var(--newtab-primary-action-background);
+ content: " ";
+ mask: url("chrome://global/skin/icons/arrow-right-12.svg") 0 -8px no-repeat;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block;
+}
+
+.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: var(--newtab-text-secondary-color);
+ 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: var(--newtab-primary-action-background);
+ 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: var(--newtab-primary-action-background);
+ 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://global/skin/icons/info.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;
+}
+
+.ds-privacy-link {
+ text-align: center;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 24px;
+}
+.ds-privacy-link a:hover {
+ text-decoration: none;
+}
+
+.ds-topics-widget {
+ display: flex;
+ position: relative;
+ flex-direction: column;
+}
+.ds-topics-widget .ds-topics-widget-header {
+ font-size: 18px;
+ line-height: 20px;
+}
+.ds-topics-widget hr {
+ background-color: color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ height: 1px;
+ border: 0;
+ margin: 10px 0 0;
+}
+.ds-topics-widget .ds-topics-widget-list-container {
+ flex-grow: 1;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul {
+ margin: 14px 0 0;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ grid-gap: 10px;
+ flex-wrap: wrap;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li {
+ display: flex;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a {
+ font-size: 14px;
+ line-height: 16px;
+ text-decoration: none;
+ padding: 8px 15px;
+ background: var(--newtab-background-color-secondary);
+ border: 1px solid color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ color: var(--newtab-text-primary-color);
+ border-radius: 8px;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: box-shadow 150ms;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+}
+@media (min-width: 610px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: none;
+ }
+}
+@media (min-width: 1122px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+ }
+}
+.ds-topics-widget .ds-topics-widget-button {
+ margin: 14px 0 0;
+ font-size: 16px;
+ line-height: 24px;
+ text-align: center;
+ padding: 8px;
+ border-radius: 4px;
+ background-color: var(--newtab-primary-action-background-pocket);
+ border: 0;
+}
+.ds-topics-widget .ds-topics-widget-button:hover {
+ background: var(--newtab-primary-element-hover-pocket-color);
+}
+.ds-topics-widget .ds-topics-widget-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-pocket-dimmed), 0 0 0 1px var(--newtab-primary-action-background-pocket);
+ transition: box-shadow 150ms;
+}
+
+.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-primary-action-background);
+ background-color: var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+}
+.ASRouterButton.primary:hover {
+ background-color: var(--newtab-primary-element-hover-color);
+}
+.ASRouterButton.primary:active {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ASRouterButton.slim {
+ border: 1px solid var(--newtab-border-color);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px;
+}
+.ASRouterButton.slim:hover, .ASRouterButton.slim:focus {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-background-color-secondary);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid transparent;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center;
+}
+.SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-primary-action-background);
+}
+.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: 20px;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://global/skin/icons/close.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: var(--newtab-text-primary-color);
+ background: var(--newtab-background-color-secondary);
+ 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-background-color-secondary);
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ 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: var(--newtab-text-primary-color);
+ 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 var(--newtab-border-color);
+ 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 var(--newtab-element-secondary-color);
+ 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: 0 2px 6px rgba(0, 0, 0, 0.15);
+ 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 5px var(--newtab-element-secondary-color);
+ 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: var(--newtab-text-emphasis-text-color);
+ font-style: normal;
+ background: var(--newtab-text-emphasis-background);
+}
+.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.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-block: 8px;
+}
+.SimpleSnippet.bold .icon, .SimpleSnippet.takeover .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-text-primary-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0;
+}
+.SimpleSnippet .section-title a {
+ color: var(--newtab-text-primary-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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-text-primary-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: var(--newtab-text-primary-color);
+ margin-inline-end: 18px;
+ border: 1px solid var(--newtab-border-color);
+ padding: 5px 14px;
+ background: var(--newtab-background-color-secondary);
+ cursor: pointer;
+}
+.EOYSnippetForm input[type=radio] {
+ opacity: 0;
+ margin-inline-end: -18px;
+}
+.EOYSnippetForm input[type=radio]:checked + .donation-amount {
+ background: var(--newtab-text-secondary-color);
+ color: var(--newtab-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+}
+.EOYSnippetForm input[type=radio]:checked:focus + .donation-amount, .EOYSnippetForm input[type=radio]:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-primary-action-background);
+}
+.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..baa03fc9a6
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-windows.css
@@ -0,0 +1,4812 @@
+@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;
+}
+
+:root {
+ --newtab-background-color: #F9F9FB;
+ --newtab-background-color-secondary: #FFF;
+ --newtab-text-primary-color: #15141a;
+ --newtab-primary-action-background: #0061e0;
+ --newtab-primary-action-background-pocket: #008078;
+ --newtab-text-secondary-color: color-mix(in srgb, var(--newtab-text-primary-color) 70%, transparent);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 90%, #000);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 80%, #000);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 5%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 12%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 90%, #000);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 90%, #000);
+ --newtab-primary-element-active-color: color-mix(in srgb, var(--newtab-primary-action-background) 80%, #000);
+ --newtab-primary-element-text-color: #FFF;
+ --newtab-primary-action-background-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 25%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #000);
+ --newtab-wordmark-color: #20123A;
+ --newtab-status-success: #058B00;
+ --newtab-status-error: #D70022;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-overlay-color: color-mix(in srgb, var(--newtab-background-color) 85%, transparent);
+ --newtab-text-emphasis-background: #FFE900;
+ --newtab-text-emphasis-text-color: #0C0C0D;
+ --newtab-textbox-focus-color: var(--newtab-primary-action-background);
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px var(--newtab-primary-action-background), 0 0 0 4px rgba(var(--newtab-primary-action-background), 0.3);
+ --newtab-button-secondary-color: inherit;
+}
+:root[lwt-newtab-brighttext] {
+ --newtab-background-color: #2B2A33;
+ --newtab-background-color-secondary: #42414d;
+ --newtab-text-primary-color: #fbfbfe;
+ --newtab-primary-action-background: #00ddff;
+ --newtab-primary-action-background-pocket: #00ddff;
+ --newtab-primary-action-background-pocket-dimmed: color-mix(in srgb, var(--newtab-primary-action-background) 25%, transparent);
+ --newtab-primary-element-hover-color: color-mix(in srgb, var(--newtab-primary-action-background) 55%, #FFF);
+ --newtab-primary-element-hover-pocket-color: color-mix(in srgb, var(--newtab-primary-action-background-pocket) 55%, #FFF);
+ --newtab-element-hover-color: color-mix(in srgb, var(--newtab-background-color) 80%, #FFF);
+ --newtab-element-active-color: color-mix(in srgb, var(--newtab-background-color) 60%, #FFF);
+ --newtab-element-secondary-color: color-mix(in srgb, currentColor 10%, transparent);
+ --newtab-element-secondary-hover-color: color-mix(in srgb, currentColor 17%, transparent);
+ --newtab-element-secondary-active-color: color-mix(in srgb, currentColor 30%, transparent);
+ --newtab-border-color: color-mix(in srgb, var(--newtab-background-color) 75%, #FFF);
+ --newtab-primary-element-text-color: #2b2a33;
+ --newtab-wordmark-color: #fbfbfe;
+ --newtab-status-success: #7C6;
+}
+
+@media (prefers-contrast) {
+ :root {
+ --newtab-text-secondary-color: var(--newtab-text-primary-color);
+ }
+}
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-text-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-text-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://global/skin/icons/close-fill.svg");
+}
+.icon.icon-delete {
+ background-image: url("chrome://global/skin/icons/delete.svg");
+}
+.icon.icon-search {
+ background-image: url("chrome://global/skin/icons/search-glass.svg");
+}
+.icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-20.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://global/skin/icons/close.svg");
+}
+.icon.icon-info {
+ background-image: url("chrome://global/skin/icons/info.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://global/skin/icons/edit.svg");
+}
+.icon.icon-pocket {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+}
+.icon.icon-pocket-save {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #FFF;
+}
+.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://browser/skin/trending.svg");
+ transform: translateY(2px);
+}
+.icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg");
+}
+.icon.icon-topsites {
+ background-image: url("chrome://browser/skin/topsites.svg");
+}
+.icon.icon-pin-small {
+ background-image: url("chrome://browser/skin/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/downloads.svg");
+}
+.icon.icon-copy {
+ background-image: url("chrome://global/skin/icons/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://global/skin/icons/highlights.svg");
+}
+.icon.icon-arrowhead-down {
+ background-image: url("chrome://global/skin/icons/arrow-down.svg");
+}
+.icon.icon-arrowhead-down-small {
+ background-image: url("chrome://global/skin/icons/arrow-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://global/skin/icons/arrow-right-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px;
+}
+.icon.icon-arrowhead-forward-small:dir(rtl) {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+.icon.icon-arrowhead-up {
+ background-image: url("chrome://global/skin/icons/arrow-up.svg");
+}
+.icon.icon-add {
+ background-image: url("chrome://global/skin/icons/plus.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://global/skin/icons/arrow-right-12.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;
+}
+
+.inner-border {
+ border: 1px solid var(--newtab-border-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-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-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-element-secondary-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-primary-action-background);
+ border: solid 1px var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+ 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-primary-action-background);
+}
+.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-primary-action-background);
+}
+
+main {
+ margin: auto;
+ width: 274px;
+ padding: 0;
+}
+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;
+ }
+}
+main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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: 0;
+}
+@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;
+ }
+}
+.ds-outer-wrapper-breakpoint-override main.has-snippet {
+ padding-bottom: 68px;
+}
+
+.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);
+}
+
+.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-secondary-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-secondary-color);
+ text-decoration: underline;
+}
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0;
+}
+.top-sites-list a {
+ text-decoration: none;
+}
+.top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-element-hover-color);
+}
+@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: 802px) {
+ .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) {
+ .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) {
+ .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) {
+ .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) {
+ .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 {
+ width: 120px;
+ padding: 20px 16px 4px;
+ border-radius: 8px;
+ 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:is(:hover) .context-menu-button {
+ opacity: 1;
+}
+.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-text-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms;
+}
+.top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-element-hover-color);
+ fill: var(--newtab-primary-action-background);
+}
+.top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-background-color-secondary);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px;
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ 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-background-color-secondary);
+ 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: 32px;
+ width: 32px;
+ 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://global/skin/icons/search-glass.svg");
+ background-size: 16px;
+ background-color: var(--newtab-primary-action-background);
+ border-radius: 32px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 32px;
+ width: 32px;
+ bottom: -6px;
+ inset-inline-end: -6px;
+}
+.top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color);
+}
+.top-site-outer .title {
+ color: var(--newtab-text-primary-color);
+ padding-top: 8px;
+ font: caption;
+ text-align: center;
+ position: relative;
+}
+.top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-text-primary-color);
+}
+.top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.top-site-outer .title .sponsored-label {
+ color: var(--newtab-text-secondary-color);
+ 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://global/skin/icons/edit.svg");
+}
+.top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none;
+}
+.top-site-outer.dragged .title {
+ visibility: hidden;
+}
+
+.edit-topsites-wrapper .top-site-inner > .top-site-button > .tile {
+ border: 1px solid var(--newtab-border-color);
+}
+.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: 17px;
+}
+.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: var(--newtab-primary-action-background);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-border-color);
+ box-shadow: none;
+ opacity: 0.4;
+}
+.topsite-form .form-wrapper .invalid input[type=text] {
+ border: 1px solid var(--newtab-status-error);
+ box-shadow: 0 0 0 1px var(--newtab-status-error), 0 0 0 4px rgba(var(--newtab-status-error), 0.3);
+}
+.topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: var(--newtab-status-error);
+ 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: var(--newtab-status-error);
+ 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-border-color);
+ 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-primary-action-background);
+ 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-primary-action-background-dimmed);
+}
+.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-primary-action-background);
+}
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px);
+ }
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.topsite-impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 192px);
+ 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: 1250px) {
+ .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: 1506px) {
+ .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-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-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-text-primary-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-primary-action-background);
+ 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;
+}
+
+.search-wrapper {
+ padding: 34px 0 38px;
+}
+.only-search .search-wrapper {
+ padding: 0 0 38px;
+}
+.search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px;
+}
+.search-wrapper .logo-and-wordmark .logo {
+ display: inline-block;
+ height: 82px;
+ width: 82px;
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 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-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: 52px;
+ margin: 0 auto;
+ position: relative;
+ width: 200px;
+}
+@media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 360px;
+ }
+}
+@media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 600px;
+ }
+}
+@media (min-width: 1122px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 720px;
+ }
+}
+.search-wrapper .search-handoff-button,
+.search-wrapper input {
+ background: var(--newtab-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ padding-block: 0;
+ width: 100%;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-text-primary-color);
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-secondary-color);
+}
+.search-wrapper .search-handoff-button:dir(rtl),
+.search-wrapper input:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper .search-inner-wrapper:active input,
+.search-wrapper input:focus {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.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-text-secondary-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px;
+}
+.search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ cursor: pointer;
+}
+.search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+ border: 1px solid var(--newtab-primary-action-background);
+ border-radius: 0 8px 8px 0;
+}
+.search-wrapper .search-button:active {
+ background-color: var(--newtab-element-hover-color);
+}
+.search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1);
+}
+.search-wrapper.fake-focus:not(.search.disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-primary-action-background);
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.search-wrapper .search-handoff-button {
+ padding-inline-end: 15px;
+ color: var(--newtab-text-primary-color);
+ fill: var(--newtab-text-secondary-color);
+ -moz-context-properties: fill;
+}
+.search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px;
+}
+.search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px;
+}
+.search-wrapper.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color);
+}
+
+.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-background-color-secondary) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ border: solid 1px transparent;
+ 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;
+ width: 100%;
+}
+.search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+}
+.fake-focus:not(.search-disabled) .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+}
+.fake-focus:not(.search-disabled) .search-handoff-button .fake-caret {
+ display: block;
+}
+.search-disabled .search-handoff-button {
+ opacity: 0.5;
+ box-shadow: none;
+}
+.search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent;
+}
+.search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ inset: 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: 124px;
+ }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 254px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-color);
+ padding: 27px 0;
+ background-color: var(--newtab-overlay-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: 45px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ 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 .search-handoff-button {
+ background-position-x: 16px;
+ background-size: 24px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 16px;
+ }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px;
+ }
+}
+.contentSearchSuggestionTable {
+ 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);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchHeader {
+ color: var(--newtab-text-secondary-color);
+ background-color: var(--newtab-background-color-secondary);
+}
+.contentSearchSuggestionTable .contentSearchHeader,
+.contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-color);
+}
+.contentSearchSuggestionTable .contentSearchSuggestionsList {
+ color: var(--newtab-text-primary-color);
+ border: 0;
+}
+.contentSearchSuggestionTable .contentSearchOneOffsTable {
+ border-top: solid 1px var(--newtab-border-color);
+ background-color: var(--newtab-background-color);
+}
+.contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-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-text-secondary-color);
+}
+.contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-color) 18%, var(--newtab-border-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-background-color-secondary);
+ 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-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-secondary-hover-color);
+}
+.context-menu > ul > li > a:active,
+.context-menu > ul > li > button:active {
+ background: var(--newtab-element-secondary-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 1px 4px 0 rgba(12, 12, 13, 0.2);
+ 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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002;
+}
+
+@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 {
+ border: 0;
+ border-radius: 4px;
+ background-color: transparent;
+ padding: 15px;
+}
+.personalize-button:hover {
+ background-color: var(--newtab-element-hover-color);
+}
+.personalize-button:active {
+ background-color: var(--newtab-element-active-color);
+}
+.personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.personalize-button.personalize-animate-exit-done {
+ visibility: hidden;
+}
+
+.customize-menu {
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color-secondary);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default;
+}
+@media (prefers-reduced-motion: no-preference) {
+ .customize-menu {
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 250ms;
+ }
+}
+@media (forced-colors: active) {
+ .customize-menu {
+ border-inline-start: solid 1px;
+ }
+}
+.customize-menu:dir(rtl) {
+ transform: translateX(-435px);
+}
+.customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ visibility: visible;
+ transform: translateX(0);
+}
+.customize-menu.customize-animate-exit-active {
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+}
+.customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--newtab-element-secondary-color);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ font-weight: 600;
+}
+.customize-menu .close-button:hover {
+ background-color: var(--newtab-element-secondary-hover-color);
+}
+.customize-menu .close-button:hover:active {
+ background-color: var(--newtab-element-secondary-active-color);
+}
+
+.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-element-secondary-color);
+}
+.home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--newtab-primary-element-text-color);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+}
+@media (forced-colors: active) {
+ .home-section .section .sponsored-checkbox:checked {
+ fill: #000;
+ }
+}
+.home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: var(--newtab-element-secondary-color);
+}
+.home-section .section .selector {
+ color: var(--newtab-text-primary-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ margin-bottom: 2px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/arrow-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--newtab-background-color-secondary);
+}
+.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-element-secondary-color);
+}
+.home-section .section .slider::before {
+ position: absolute;
+ content: "";
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--newtab-primary-element-text-color);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+}
+.home-section .section .switch input:focus-visible + .slider {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+.home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-primary-action-background);
+}
+.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;
+}
+.home-section .section .more-info-top-wrapper .more-information,
+.home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: margin-top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895);
+}
+.home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px;
+}
+.home-section .divider {
+ border-top: 1px var(--newtab-border-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(--newtab-text-primary-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px;
+ text-decoration: underline;
+}
+@media (forced-colors: active) {
+ .home-section .external-link {
+ padding: 8px 10px;
+ padding-inline-start: 21px;
+ }
+}
+.home-section .external-link:dir(rtl) {
+ background-position-x: right;
+}
+.home-section .external-link:hover {
+ text-decoration: none;
+}
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-primary-action-background);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-primary-action-background-dimmed);
+}
+
+.card-outer {
+ background: var(--newtab-background-color-secondary);
+ border-radius: 8px;
+ 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-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.card-outer:hover {
+ box-shadow: none;
+ transition: none;
+}
+.card-outer.placeholder {
+ background: transparent;
+}
+.card-outer.placeholder .card-preview-image-outer,
+.card-outer.placeholder .card-context {
+ display: none;
+}
+.card-outer .card {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+ height: 100%;
+}
+.card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%;
+}
+.card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+.card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-primary-action-background);
+}
+.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-primary-action-background);
+}
+.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: var(--newtab-element-secondary-color);
+ border-radius: 8px 8px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative;
+}
+.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-background-color-secondary);
+ 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: #EF4056;
+}
+.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;
+ }
+}
+
+.collapsible-section {
+ padding: 10px 25px;
+}
+.collapsible-section .section-title-container {
+ margin: 0;
+}
+.collapsible-section .section-title-container.has-subtitle {
+ display: flex;
+ flex-direction: column;
+}
+@media (min-width: 866px) {
+ .collapsible-section .section-title-container.has-subtitle {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ }
+}
+.collapsible-section .section-title {
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--newtab-text-primary-color);
+}
+.collapsible-section .section-title.grey-title {
+ color: var(--newtab-text-primary-color);
+ display: inline-block;
+ fill: var(--newtab-text-primary-color);
+ vertical-align: middle;
+}
+.collapsible-section .section-title .section-title-contents {
+ vertical-align: top;
+}
+@media (max-width: 609px) {
+ .collapsible-section .section-title .section-title-contents {
+ display: block;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper {
+ display: block;
+ text-align: center;
+ }
+ .collapsible-section .section-title .section-title-contents .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0;
+ }
+}
+.collapsible-section .section-sub-title {
+ font-size: 14px;
+ line-height: 16px;
+ color: var(--newtab-text-secondary-color);
+ opacity: 0.3;
+}
+.collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative;
+}
+.collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+}
+.collapsible-section .learn-more-link {
+ font-size: 13px;
+ margin-inline-start: 12px;
+}
+.collapsible-section .learn-more-link a {
+ color: var(--newtab-primary-action-background);
+}
+.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[data-section-id=topsites] .section-top-bar {
+ display: none;
+}
+@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://global/skin/icons/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-background-color-secondary);
+}
+.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: var(--newtab-element-hover-color);
+ 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-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-background-color-secondary);
+}
+.asrouter-admin table.errorReporting td {
+ padding: 4px;
+}
+.asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.asrouter-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-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-color);
+}
+.asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-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-background-color-secondary);
+ 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 var(--newtab-status-error);
+}
+.asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.asrouter-admin .helpLink a {
+ text-decoration: underline;
+}
+.asrouter-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.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: var(--newtab-primary-action-background);
+ 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.2307692308;
+}
+.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.2307692308;
+}
+.more-recommendations::after {
+ background: url("chrome://global/skin/icons/arrow-right-12.svg") no-repeat center center;
+ content: "";
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-primary-action-background);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px;
+}
+.more-recommendations:dir(rtl)::after {
+ background-image: url("chrome://global/skin/icons/arrow-left-12.svg");
+}
+
+.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: var(--newtab-text-primary-color);
+ font-size: 17px;
+ font-weight: 600;
+ line-height: 20px;
+}
+.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-primary-action-background);
+ font-weight: 500;
+}
+.collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: none;
+}
+
+.ds-onboarding-container,
+.ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container,
+[lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none;
+}
+.ds-onboarding-container:not(.placeholder),
+.ds-card-grid .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+[lwt-newtab-brighttext] .ds-onboarding-container:not(.placeholder),
+[lwt-newtab-brighttext] .ds-card-grid .ds-card:not(.placeholder) {
+ background: var(--newtab-background-color-secondary);
+}
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img img,
+.ds-onboarding-container:not(.placeholder) .img-wrapper .img .placeholder-image,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img img,
+.ds-card-grid .ds-card:not(.placeholder) .img-wrapper .img .placeholder-image {
+ border-radius: 8px 8px 0 0;
+}
+
+.ds-onboarding-container {
+ padding-inline-start: 16px;
+ padding-inline-end: 16px;
+ margin-bottom: 24px;
+ position: relative;
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container {
+ padding-inline-end: 48px;
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container {
+ padding-inline-end: 56px;
+ }
+}
+.ds-onboarding-container .ds-onboarding {
+ position: static;
+ display: flex;
+}
+.ds-onboarding-container .ds-onboarding .ds-dismiss-button {
+ inset-inline-end: 8px;
+ top: 8px;
+}
+.ds-onboarding-container header {
+ display: flex;
+ margin: 32px 0 8px;
+ font-size: 17px;
+ line-height: 23.8px;
+ font-weight: 600;
+ color: #EF4056;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container header {
+ color: var(--newtab-background-color-primary);
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container header {
+ margin: 16px 0 8px;
+ display: block;
+ height: 24px;
+ }
+}
+.ds-onboarding-container p {
+ margin: 8px 0 16px;
+ font-size: 13px;
+ line-height: 19.5px;
+}
+.ds-onboarding-container .icon-pocket {
+ fill: #EF4056;
+ margin-top: 3px;
+ margin-inline-end: 8px;
+ height: 22px;
+ width: 22px;
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ background-size: contain;
+}
+[lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ [lwt-newtab-brighttext] .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (forced-colors: active) {
+ .ds-onboarding-container .icon-pocket {
+ fill: CurrentColor;
+ }
+}
+@media (min-width: 610px) {
+ .ds-onboarding-container .icon-pocket {
+ margin-top: -5px;
+ margin-inline-start: -2px;
+ margin-inline-end: 15px;
+ height: 30px;
+ width: 30px;
+ }
+}
+.ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif");
+ border-radius: 8px;
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: center;
+ height: 120px;
+ width: 200px;
+ margin-top: 16px;
+ margin-bottom: 16px;
+ margin-inline-start: 54px;
+ flex-shrink: 0;
+ display: none;
+}
+@media (min-resolution: 2x) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif");
+ }
+}
+@media (min-width: 866px) {
+ .ds-onboarding-container .ds-onboarding-graphic {
+ display: block;
+ }
+}
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px;
+}
+.ds-card-grid.ds-card-grid-compact {
+ grid-gap: 20px;
+}
+@media (min-width: 610px) and (max-width: 866px) {
+ .ds-card-grid.ds-card-grid-recent-saves .ds-card:last-child:nth-child(2n-1) {
+ display: none;
+ }
+}
+.ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+ border-radius: 8px;
+}
+.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-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-10 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-11 .ds-card-grid.ds-card-grid-four-card-variant, .ds-column-12 .ds-card-grid.ds-card-grid-four-card-variant {
+ grid-template-columns: repeat(4, 1fr);
+ }
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card.placeholder {
+ min-height: 247px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-footer {
+ margin-top: 8px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .source,
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+}
+.ds-card-grid.ds-card-grid-four-card-variant .ds-card .meta .info-wrap {
+ flex-grow: 0;
+}
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(1, 1fr);
+}
+@media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+@media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+@media (max-height: 1065px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .excerpt {
+ display: none;
+ }
+}
+@media (max-width: 1122px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+@media (min-width: 1122px) and (max-height: 964px) {
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card.placeholder {
+ min-height: 247px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-footer {
+ margin-top: 8px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ color: var(--newtab-text-secondary-color);
+ -webkit-line-clamp: 2;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .source,
+.ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-sponsored-label {
+ font-size: 13px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .status-message .story-context-label {
+ font-size: 11.7px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .story-badge-icon {
+ margin-inline-end: 2px;
+ margin-bottom: 2px;
+ height: 14px;
+ width: 14px;
+ background-size: 14px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .title {
+ font-size: 14px;
+ line-height: 20px;
+ }
+ .ds-column-9 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-10 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-11 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap, .ds-column-12 .ds-card-grid.ds-card-grid-hybrid-layout .ds-card .meta .info-wrap {
+ flex-grow: 0;
+ }
+}
+
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder),
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) {
+ box-shadow: none;
+ background: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus {
+ box-shadow: none;
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .ds-card-link:focus .img-wrapper .img img {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+.outer-wrapper .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta,
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-hide-background .ds-card:not(.placeholder) .meta {
+ padding: 12px 0 0;
+}
+
+.ds-layout .ds-sub-header {
+ margin-top: 24px;
+}
+.ds-layout .ds-sub-header .section-title-container {
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: space-between;
+ display: flex;
+}
+.ds-layout .ds-sub-header .section-sub-link {
+ color: var(--newtab-primary-action-background);
+ font-size: 14px;
+ line-height: 16px;
+ cursor: pointer;
+}
+.ds-layout .ds-sub-header .section-sub-link:hover {
+ text-decoration: underline;
+}
+.ds-layout .ds-sub-header .section-sub-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+
+.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: var(--newtab-text-primary-color);
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px;
+}
+.ds-collection-card-grid .ds-header .ds-context {
+ color: var(--newtab-text-secondary-color);
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px;
+}
+
+.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 .section .section-list .card-outer a {
+ text-decoration: none;
+}
+.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-navigation {
+ color: var(--newtab-text-primary-color);
+ font-size: 11.5px;
+ font-weight: 500;
+ line-height: 22px;
+ padding: 4px 0;
+}
+@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: none;
+}
+.ds-navigation ul li a:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px;
+}
+.ds-navigation .ds-navigation-privacy {
+ padding-inline-start: 6px;
+ float: inline-end;
+}
+.ds-navigation .ds-navigation-privacy:hover {
+ text-decoration: none;
+}
+.ds-navigation.ds-navigation-new-topics {
+ display: block;
+ padding-top: 32px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-header {
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: 700;
+ display: inline-block;
+ margin-bottom: 8px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ text-align: center;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 16px auto 28px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family span {
+ margin: 0 6px;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo,
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ height: 20px;
+ width: 20px;
+ background-size: cover;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .firefox-logo {
+ background-image: url("chrome://activity-stream/content/data/content/assets/firefox.svg");
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .pocket-logo {
+ background-image: url("chrome://global/skin/icons/pocket.svg");
+ fill: #EF4056;
+}
+.ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ font-weight: 400;
+ display: block;
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family .ds-navigation-family-message {
+ display: inline;
+ }
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics .ds-navigation-family {
+ margin-top: 43px;
+ }
+}
+.ds-navigation.ds-navigation-new-topics ul {
+ display: grid;
+ grid-gap: 0 24px;
+ grid-auto-flow: column;
+ grid-template: repeat(8, 1fr)/repeat(1, 1fr);
+}
+.ds-navigation.ds-navigation-new-topics ul li {
+ border-top: 1px solid var(--newtab-border-color);
+ line-height: 24px;
+ font-size: 13px;
+ font-weight: 500;
+}
+.ds-navigation.ds-navigation-new-topics ul li::after {
+ content: "";
+ padding: 0;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: none;
+}
+.ds-navigation.ds-navigation-new-topics ul li:nth-last-child(1) {
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+@media (min-width: 610px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(3, 1fr)/repeat(2, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(3) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 866px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(3, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(odd) {
+ border-bottom: 0;
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-child(even) {
+ border-bottom: 1px solid var(--newtab-border-color);
+ }
+}
+@media (min-width: 1122px) {
+ .ds-navigation.ds-navigation-new-topics ul {
+ grid-template: repeat(2, 1fr)/repeat(4, 1fr);
+ }
+ .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(2), .ds-navigation.ds-navigation-new-topics ul li:nth-last-child(3) {
+ display: block;
+ }
+}
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px;
+}
+.ds-section-title .title {
+ color: var(--newtab-text-primary-color);
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+}
+.ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 4px;
+}
+
+.outer-wrapper .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-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+}
+.outer-wrapper .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px var(--newtab-background-color-secondary);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none;
+}
+.outer-wrapper .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-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-background-color-secondary);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-text-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-card .context-menu-button:is(:active, :focus),
+.ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1);
+}
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0;
+}
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1;
+}
+.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-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1;
+}
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none;
+}
+.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-card {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+}
+.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 .card-stp-button-hover-background {
+ opacity: 0;
+ width: 100%;
+ position: absolute;
+ top: 0;
+ height: 0;
+ transition: opacity;
+ transition-duration: 0s;
+ padding-top: 50%;
+ pointer-events: none;
+ background: rgba(0, 0, 0, 0.4);
+ border-radius: 8px 8px 0 0;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button-position-wrapper {
+ position: absolute;
+ inset-inline-end: 10px;
+ top: 10px;
+ display: flex;
+ justify-content: end;
+ align-items: center;
+}
+.ds-card .card-stp-button-hover-background .icon-pocket-save,
+.ds-card .card-stp-button-hover-background .icon-pocket {
+ margin-inline-end: 4px;
+ height: 15px;
+ width: 15px;
+ background-size: 15px;
+ fill: #FFF;
+}
+.ds-card .card-stp-button-hover-background .context-menu-button {
+ position: static;
+ transition: none;
+ border-radius: 3px;
+}
+.ds-card .card-stp-button-hover-background .context-menu-position-container {
+ position: relative;
+}
+.ds-card .card-stp-button-hover-background .context-menu {
+ margin-inline-start: 18.5px;
+ inset-inline-start: auto;
+ position: absolute;
+ top: 20.25px;
+}
+.ds-card .card-stp-button-hover-background .card-stp-button {
+ display: flex;
+ margin-inline-end: 7px;
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 16px;
+ background-color: #EF4056;
+ border: 0;
+ border-radius: 4px;
+ padding: 6px;
+ white-space: nowrap;
+ color: #FFF;
+}
+.ds-card .card-stp-button-hover-background button,
+.ds-card .card-stp-button-hover-background .context-menu {
+ pointer-events: auto;
+}
+.ds-card .card-stp-button-hover-background button {
+ cursor: pointer;
+}
+.ds-card.last-item .card-stp-button-hover-background .context-menu {
+ margin-inline-start: auto;
+ margin-inline-end: 18.5px;
+}
+.ds-card.active .card-stp-button-hover-background, .ds-card:focus-within .card-stp-button-hover-background, .ds-card:hover .card-stp-button-hover-background {
+ display: block;
+ opacity: 1;
+ transition-duration: 0.3s;
+}
+.ds-card.active .card-stp-button-hover-background .context-menu-button, .ds-card:focus-within .card-stp-button-hover-background .context-menu-button, .ds-card:hover .card-stp-button-hover-background .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+}
+.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;
+ text-decoration: none;
+}
+.ds-card .ds-card-link:hover header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: none;
+}
+.ds-card .ds-card-link:focus header {
+ color: var(--newtab-primary-action-background);
+}
+.ds-card .ds-card-link:active header {
+ color: var(--newtab-primary-element-active-color);
+}
+.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: var(--newtab-text-secondary-color);
+}
+.ds-card .meta .source span {
+ display: inline-block;
+}
+.ds-card .meta .new-sponsored-label {
+ font-size: 13px;
+ margin-bottom: 2px;
+}
+.ds-card.ds-card-title-lines-2 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 2;
+ line-height: 24px;
+}
+.ds-card.ds-card-title-lines-1 .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 1;
+ line-height: 24px;
+}
+.ds-card.ds-card-desc-lines-2 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+}
+.ds-card.ds-card-desc-lines-1 .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+}
+.ds-card.ds-card-compact-image .img {
+ padding-top: 47%;
+}
+.ds-card.ds-card-image-gradient img {
+ mask-image: linear-gradient(to top, rgba(0, 0, 0, 0), black 40px);
+}
+.ds-card.ds-card-image-gradient .meta {
+ padding: 3px 15px 11px;
+}
+.ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: var(--newtab-text-primary-color);
+}
+.ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+}
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative;
+}
+.story-footer .story-sponsored-label span {
+ display: inline-block;
+}
+.story-footer .story-sponsored-label,
+.story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: var(--newtab-text-secondary-color);
+}
+.story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px;
+}
+.story-footer .status-message .story-badge-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 16px;
+ margin-inline-end: 6px;
+}
+.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: var(--newtab-text-secondary-color);
+ 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-animate-enter-active .story-badge-icon,
+.story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s;
+}
+@keyframes color {
+ 0% {
+ color: var(--newtab-status-success);
+ fill: var(--newtab-status-success);
+ }
+ 100% {
+ color: var(--newtab-text-secondary-color);
+ fill: var(--newtab-text-secondary-color);
+ }
+}
+
+.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 .placeholder-image,
+.ds-image .broken-image {
+ background-color: var(--newtab-element-secondary-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.ds-image .placeholder-image {
+ overflow: hidden;
+ background-color: var(--placeholderBackgroundColor);
+}
+.ds-image .placeholder-image::before {
+ content: "";
+ background-image: url("chrome://activity-stream/content/data/content/assets/pocket-swoosh.svg");
+ background-repeat: no-repeat;
+ background-position: center;
+ transform: rotate(var(--placeholderBackgroundRotation));
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ margin-left: var(--placeholderBackgroundOffsetx);
+ margin-top: var(--placeholderBackgroundOffsety);
+ background-size: var(--placeholderBackgroundScale);
+}
+
+.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: var(--newtab-text-primary-color);
+}
+@media (forced-colors: active) {
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: CurrentColor;
+ }
+}
+.ds-dismiss .ds-dismiss-button:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-dismiss .ds-dismiss-button:active {
+ background: var(--newtab-element-active-color);
+}
+.ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+}
+
+.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: var(--newtab-text-secondary-color);
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat;
+}
+.ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: var(--newtab-text-secondary-color);
+ font-weight: 600;
+ padding-right: 12px;
+}
+.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-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-button-secondary-color);
+ color: var(--newtab-text-primary-color);
+ 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 var(--newtab-element-secondary-color);
+ 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-text-secondary-color);
+}
+.section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-element-secondary-color);
+ color: transparent;
+ 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: var(--newtab-element-hover-color);
+}
+.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 {
+ color: var(--newtab-text-primary-color);
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px;
+}
+.ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: var(--newtab-text-primary-color);
+}
+
+.ds-chevron-link {
+ color: var(--newtab-primary-action-background);
+ display: inline-block;
+ outline: 0;
+}
+.ds-chevron-link:hover {
+ text-decoration: underline;
+}
+.ds-chevron-link:active {
+ color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:active::after {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ds-chevron-link:focus {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ border-radius: 2px;
+}
+.ds-chevron-link::after {
+ background-color: var(--newtab-primary-action-background);
+ content: " ";
+ mask: url("chrome://global/skin/icons/arrow-right-12.svg") 0 -8px no-repeat;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block;
+}
+
+.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: var(--newtab-text-secondary-color);
+ 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: var(--newtab-primary-action-background);
+ 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: var(--newtab-primary-action-background);
+ 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://global/skin/icons/info.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;
+}
+
+.ds-privacy-link {
+ text-align: center;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 24px;
+}
+.ds-privacy-link a:hover {
+ text-decoration: none;
+}
+
+.ds-topics-widget {
+ display: flex;
+ position: relative;
+ flex-direction: column;
+}
+.ds-topics-widget .ds-topics-widget-header {
+ font-size: 18px;
+ line-height: 20px;
+}
+.ds-topics-widget hr {
+ background-color: color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ height: 1px;
+ border: 0;
+ margin: 10px 0 0;
+}
+.ds-topics-widget .ds-topics-widget-list-container {
+ flex-grow: 1;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul {
+ margin: 14px 0 0;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ grid-gap: 10px;
+ flex-wrap: wrap;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li {
+ display: flex;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a {
+ font-size: 14px;
+ line-height: 16px;
+ text-decoration: none;
+ padding: 8px 15px;
+ background: var(--newtab-background-color-secondary);
+ border: 1px solid color-mix(in srgb, var(--newtab-border-color) 52%, transparent);
+ color: var(--newtab-text-primary-color);
+ border-radius: 8px;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:hover {
+ background: var(--newtab-element-hover-color);
+}
+.ds-topics-widget .ds-topics-widget-list-container ul li a:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-dimmed), 0 0 0 1px var(--newtab-primary-action-background);
+ transition: box-shadow 150ms;
+}
+.ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+}
+@media (min-width: 610px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: none;
+ }
+}
+@media (min-width: 1122px) {
+ .ds-topics-widget .ds-topics-widget-list-container ul .ds-topics-widget-list-overflow-item {
+ display: flex;
+ }
+}
+.ds-topics-widget .ds-topics-widget-button {
+ margin: 14px 0 0;
+ font-size: 16px;
+ line-height: 24px;
+ text-align: center;
+ padding: 8px;
+ border-radius: 4px;
+ background-color: var(--newtab-primary-action-background-pocket);
+ border: 0;
+}
+.ds-topics-widget .ds-topics-widget-button:hover {
+ background: var(--newtab-primary-element-hover-pocket-color);
+}
+.ds-topics-widget .ds-topics-widget-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-primary-action-background-pocket-dimmed), 0 0 0 1px var(--newtab-primary-action-background-pocket);
+ transition: box-shadow 150ms;
+}
+
+.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-primary-action-background);
+ background-color: var(--newtab-primary-action-background);
+ color: var(--newtab-primary-element-text-color);
+}
+.ASRouterButton.primary:hover {
+ background-color: var(--newtab-primary-element-hover-color);
+}
+.ASRouterButton.primary:active {
+ background-color: var(--newtab-primary-element-active-color);
+}
+.ASRouterButton.slim {
+ border: 1px solid var(--newtab-border-color);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px;
+}
+.ASRouterButton.slim:hover, .ASRouterButton.slim:focus {
+ box-shadow: 0 0 0 5px var(--newtab-element-secondary-color);
+ transition: box-shadow 150ms;
+}
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-background-color-secondary);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid transparent;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center;
+}
+.SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-primary-action-background);
+}
+.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: 20px;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://global/skin/icons/close.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: var(--newtab-text-primary-color);
+ background: var(--newtab-background-color-secondary);
+ 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-background-color-secondary);
+ box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.2);
+ 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: var(--newtab-text-primary-color);
+ 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 var(--newtab-border-color);
+ 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 var(--newtab-element-secondary-color);
+ 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: 0 2px 6px rgba(0, 0, 0, 0.15);
+ 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 5px var(--newtab-element-secondary-color);
+ 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: var(--newtab-text-emphasis-text-color);
+ font-style: normal;
+ background: var(--newtab-text-emphasis-background);
+}
+.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.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-block: 8px;
+}
+.SimpleSnippet.bold .icon, .SimpleSnippet.takeover .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-text-primary-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0;
+}
+.SimpleSnippet .section-title a {
+ color: var(--newtab-text-primary-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-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+ 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-text-primary-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: var(--newtab-text-primary-color);
+ margin-inline-end: 18px;
+ border: 1px solid var(--newtab-border-color);
+ padding: 5px 14px;
+ background: var(--newtab-background-color-secondary);
+ cursor: pointer;
+}
+.EOYSnippetForm input[type=radio] {
+ opacity: 0;
+ margin-inline-end: -18px;
+}
+.EOYSnippetForm input[type=radio]:checked + .donation-amount {
+ background: var(--newtab-text-secondary-color);
+ color: var(--newtab-background-color-secondary);
+ border: 1px solid var(--newtab-border-color);
+}
+.EOYSnippetForm input[type=radio]:checked:focus + .donation-amount, .EOYSnippetForm input[type=radio]:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-primary-action-background);
+}
+.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..e2d52c6fef
--- /dev/null
+++ b/browser/components/newtab/data/content/abouthomecache/page.html.template
@@ -0,0 +1,44 @@
+#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: chrome:; style-src 'unsafe-inline';">
+ <meta name="color-scheme" content="light dark">
+ <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="toolkit/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..e064ee4f20
--- /dev/null
+++ b/browser/components/newtab/data/content/activity-stream.bundle.js
@@ -0,0 +1,15290 @@
+/*! THIS FILE IS AUTO-GENERATED: webpack.system-addon.config.js */
+var NewtabRenderUtils;
+/******/ (() => { // webpackBootstrap
+/******/ "use strict";
+/******/ // The require scope
+/******/ var __webpack_require__ = {};
+/******/
+/************************************************************************/
+/******/ /* webpack/runtime/compat get default export */
+/******/ (() => {
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = (module) => {
+/******/ var getter = module && module.__esModule ?
+/******/ () => (module['default']) :
+/******/ () => (module);
+/******/ __webpack_require__.d(getter, { a: getter });
+/******/ return getter;
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/define property getters */
+/******/ (() => {
+/******/ // define getter functions for harmony exports
+/******/ __webpack_require__.d = (exports, definition) => {
+/******/ for(var key in definition) {
+/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
+/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
+/******/ }
+/******/ }
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/global */
+/******/ (() => {
+/******/ __webpack_require__.g = (function() {
+/******/ if (typeof globalThis === 'object') return globalThis;
+/******/ try {
+/******/ return this || new Function('return this')();
+/******/ } catch (e) {
+/******/ if (typeof window === 'object') return window;
+/******/ }
+/******/ })();
+/******/ })();
+/******/
+/******/ /* webpack/runtime/hasOwnProperty shorthand */
+/******/ (() => {
+/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
+/******/ })();
+/******/
+/******/ /* webpack/runtime/make namespace object */
+/******/ (() => {
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = (exports) => {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/ })();
+/******/
+/************************************************************************/
+var __webpack_exports__ = {};
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// EXPORTS
+__webpack_require__.d(__webpack_exports__, {
+ "NewTab": () => (/* binding */ NewTab),
+ "renderCache": () => (/* binding */ renderCache),
+ "renderWithoutState": () => (/* binding */ renderWithoutState)
+});
+
+;// CONCATENATED MODULE: ./common/Actions.sys.mjs
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 MAIN_MESSAGE_TYPE = "ActivityStream:Main";
+const CONTENT_MESSAGE_TYPE = "ActivityStream:Content";
+const PRELOAD_MESSAGE_TYPE = "ActivityStream:PreloadedBrowser";
+const UI_CODE = 1;
+const 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;
+
+// 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",
+ "DISABLE_SEARCH",
+ "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_EXPERIMENT_DATA",
+ "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_TOGGLE",
+ "DISCOVERY_STREAM_POCKET_STATE_INIT",
+ "DISCOVERY_STREAM_POCKET_STATE_SET",
+ "DISCOVERY_STREAM_PREFS_SETUP",
+ "DISCOVERY_STREAM_RECENT_SAVES",
+ "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",
+ "DISCOVERY_STREAM_USER_EVENT",
+ "DOWNLOAD_CHANGED",
+ "FAKE_FOCUS_SEARCH",
+ "FILL_SEARCH_TERM",
+ "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ "HIDE_PERSONALIZE",
+ "HIDE_PRIVACY_INFO",
+ "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_BOOKMARKS_REMOVED",
+ "PLACES_BOOKMARK_ADDED",
+ "PLACES_HISTORY_CLEARED",
+ "PLACES_LINKS_CHANGED",
+ "PLACES_LINKS_DELETED",
+ "PLACES_LINK_BLOCKED",
+ "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_PERSONALIZE",
+ "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_ORGANIC_IMPRESSION_STATS",
+ "TOP_SITES_PIN",
+ "TOP_SITES_PREFS_UPDATED",
+ "TOP_SITES_SPONSORED_IMPRESSION_STATS",
+ "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,
+ });
+}
+
+/**
+ * DiscoveryStreamUserEvent - A telemetry ping indicating a user action from Discovery Stream. 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 DiscoveryStreamUserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.DISCOVERY_STREAM_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;
+}
+
+const actionCreators = {
+ BroadcastToContent,
+ UserEvent,
+ DiscoveryStreamUserEvent,
+ ASRouterUserEvent,
+ ImpressionStats,
+ AlsoToOneContent,
+ OnlyToOneContent,
+ AlsoToMain,
+ OnlyToMain,
+ AlsoToPreloaded,
+ SetPref,
+ WebExtEvent,
+ DiscoveryStreamImpressionStats,
+ DiscoveryStreamLoadedContent,
+};
+
+// These are helpers to test for certain kinds of actions
+const 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,
+};
+
+;// CONCATENATED MODULE: ./common/ActorConstants.sys.mjs
+/* 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",
+ // PB is Private Browsing
+ "PBNEWTAB_MESSAGE_REQUEST",
+ "DOORHANGER_TELEMETRY",
+ "TOOLBAR_BADGE_TELEMETRY",
+ "TOOLBAR_PANEL_TELEMETRY",
+ "MOMENTS_PAGE_TELEMETRY",
+ "INFOBAR_TELEMETRY",
+ "SPOTLIGHT_TELEMETRY",
+ "TOAST_NOTIFICATION_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",
+ "FORCE_PRIVATE_BROWSING_WINDOW",
+ "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;
+}, {});
+
+;// CONCATENATED MODULE: ./content-src/asrouter/asrouter-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/. */
+
+
+const ASRouterUtils = {
+ addListener(listener) {
+ if (__webpack_require__.g.ASRouterAddParentListener) {
+ __webpack_require__.g.ASRouterAddParentListener(listener);
+ }
+ },
+
+ removeListener(listener) {
+ if (__webpack_require__.g.ASRouterRemoveParentListener) {
+ __webpack_require__.g.ASRouterRemoveParentListener(listener);
+ }
+ },
+
+ sendMessage(action) {
+ if (__webpack_require__.g.ASRouterMessage) {
+ return __webpack_require__.g.ASRouterMessage(action);
+ }
+
+ throw new Error(`Unexpected call:\n${JSON.stringify(action, null, 3)}`);
+ },
+
+ blockById(id, options) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.BLOCK_MESSAGE_BY_ID,
+ data: {
+ id,
+ ...options
+ }
+ });
+ },
+
+ modifyMessageJson(content) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.MODIFY_MESSAGE_JSON,
+ data: {
+ content
+ }
+ });
+ },
+
+ executeAction(button_action) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.USER_ACTION,
+ data: button_action
+ });
+ },
+
+ unblockById(id) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.UNBLOCK_MESSAGE_BY_ID,
+ data: {
+ id
+ }
+ });
+ },
+
+ blockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.BLOCK_BUNDLE,
+ data: {
+ bundle
+ }
+ });
+ },
+
+ unblockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.UNBLOCK_BUNDLE,
+ data: {
+ bundle
+ }
+ });
+ },
+
+ overrideMessage(id) {
+ return ASRouterUtils.sendMessage({
+ type: MESSAGE_TYPE_HASH.OVERRIDE_MESSAGE,
+ data: {
+ id
+ }
+ });
+ },
+
+ sendTelemetry(ping) {
+ return ASRouterUtils.sendMessage(actionCreators.ASRouterUserEvent(ping));
+ },
+
+ getPreviewEndpoint() {
+ if (__webpack_require__.g.document && __webpack_require__.g.document.location && __webpack_require__.g.document.location.href.includes("endpoint")) {
+ const params = new URLSearchParams(__webpack_require__.g.document.location.href.slice(__webpack_require__.g.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(__webpack_require__.g.document.location.href.slice(__webpack_require__.g.document.location.href.indexOf("theme"))).get("theme");
+ },
+
+ getPreviewDir() {
+ return new URLSearchParams(__webpack_require__.g.document.location.href.slice(__webpack_require__.g.document.location.href.indexOf("dir"))).get("dir");
+ }
+
+};
+;// CONCATENATED MODULE: external "ReactRedux"
+const external_ReactRedux_namespaceObject = ReactRedux;
+;// CONCATENATED MODULE: external "React"
+const external_React_namespaceObject = React;
+var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_namespaceObject);
+;// CONCATENATED MODULE: ./content-src/components/ASRouterAdmin/SimpleHashRouter.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 SimpleHashRouter extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onHashChange = this.onHashChange.bind(this);
+ this.state = {
+ hash: __webpack_require__.g.location.hash
+ };
+ }
+
+ onHashChange() {
+ this.setState({
+ hash: __webpack_require__.g.location.hash
+ });
+ }
+
+ componentWillMount() {
+ __webpack_require__.g.addEventListener("hashchange", this.onHashChange);
+ }
+
+ componentWillUnmount() {
+ __webpack_require__.g.removeEventListener("hashchange", this.onHashChange);
+ }
+
+ render() {
+ const [, ...routes] = this.state.hash.split("-");
+ return /*#__PURE__*/external_React_default().cloneElement(this.props.children, {
+ location: {
+ hash: this.state.hash,
+ routes
+ }
+ });
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/ASRouterAdmin/CopyButton.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/. */
+
+const CopyButton = ({
+ className,
+ label,
+ copiedLabel,
+ inputSelector,
+ transformer,
+ ...props
+}) => {
+ const [copied, setCopied] = (0,external_React_namespaceObject.useState)(false);
+ const timeout = (0,external_React_namespaceObject.useRef)(null);
+ const onClick = (0,external_React_namespaceObject.useCallback)(() => {
+ let text = document.querySelector(inputSelector).value;
+ if (transformer) text = transformer(text);
+ navigator.clipboard.writeText(text);
+ clearTimeout(timeout.current);
+ setCopied(true);
+ timeout.current = setTimeout(() => setCopied(false), 1500);
+ }, [inputSelector, transformer]);
+ return /*#__PURE__*/external_React_default().createElement("button", _extends({
+ className: className,
+ onClick: e => onClick()
+ }, props), copied && copiedLabel || label);
+};
+;// CONCATENATED MODULE: ./content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
+function ASRouterAdmin_extends() { ASRouterAdmin_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 ASRouterAdmin_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 => /*#__PURE__*/external_React_default().createElement("tr", ASRouterAdmin_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 (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleClick = this.handleClick.bind(this);
+ }
+
+ handleClick() {
+ this.props.onClick(this.props.story);
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("button", {
+ onClick: this.handleClick
+ }, "collapse/open");
+ }
+
+}
+class ToggleMessageJSON extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("button", {
+ className: "clearButton",
+ onClick: this.handleClick
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: iconName
+ }));
+ }
+
+}
+class TogglePrefCheckbox extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onChange = this.onChange.bind(this);
+ }
+
+ onChange(event) {
+ this.props.onChange(this.props.pref, event.target.checked);
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "checkbox",
+ checked: this.props.checked,
+ onChange: this.onChange,
+ disabled: this.props.disabled
+ }), " ", this.props.pref, " ");
+ }
+
+}
+class Personalization extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.togglePersonalization = this.togglePersonalization.bind(this);
+ }
+
+ togglePersonalization() {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_PERSONALIZATION_TOGGLE
+ }));
+ }
+
+ render() {
+ const {
+ lastUpdated,
+ initialized
+ } = this.props.state.Personalization;
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ colSpan: "2"
+ }, /*#__PURE__*/external_React_default().createElement(TogglePrefCheckbox, {
+ checked: this.props.personalized,
+ pref: "personalized",
+ onChange: this.togglePersonalization
+ }))), /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Personalization Last Updated"), /*#__PURE__*/external_React_default().createElement("td", null, relativeTime(lastUpdated) || "(no data)")), /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Personalization Initialized"), /*#__PURE__*/external_React_default().createElement("td", null, initialized ? "true" : "false")))));
+ }
+
+}
+class DiscoveryStreamAdmin extends (external_React_default()).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(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_CONFIG_SET_VALUE,
+ data: {
+ name,
+ value
+ }
+ }));
+ }
+
+ restorePrefDefaults(event) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS
+ }));
+ }
+
+ refreshCache() {
+ const {
+ config
+ } = this.props.state.DiscoveryStream;
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: config
+ }));
+ }
+
+ dispatchSimpleAction(type) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type
+ }));
+ }
+
+ systemTick() {
+ this.dispatchSimpleAction(actionTypes.DISCOVERY_STREAM_DEV_SYSTEM_TICK);
+ }
+
+ expireCache() {
+ this.dispatchSimpleAction(actionTypes.DISCOVERY_STREAM_DEV_EXPIRE_CACHE);
+ }
+
+ idleDaily() {
+ this.dispatchSimpleAction(actionTypes.DISCOVERY_STREAM_DEV_IDLE_DAILY);
+ }
+
+ syncRemoteSettings() {
+ this.dispatchSimpleAction(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 /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Type"), /*#__PURE__*/external_React_default().createElement("td", null, component.type)), /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Width"), /*#__PURE__*/external_React_default().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) {
+ var _feed$recommendations;
+
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+ const feed = feeds.data[url].data;
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h4", null, "Feed url: ", url), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, (_feed$recommendations = feed.recommendations) === null || _feed$recommendations === void 0 ? void 0 : _feed$recommendations.map(story => this.renderStoryData(story)))));
+ }
+
+ renderFeedsData() {
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "spocs_endpoint"), /*#__PURE__*/external_React_default().createElement("td", null, spocs.spocs_endpoint)), /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Data last fetched"), /*#__PURE__*/external_React_default().createElement("td", null, relativeTime(spocs.lastUpdated))))), /*#__PURE__*/external_React_default().createElement("h4", null, "Spoc data"), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, spocsData.map(spoc => this.renderStoryData(spoc)))), /*#__PURE__*/external_React_default().createElement("h4", null, "Spoc frequency caps"), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item",
+ key: story.id
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "message-id"
+ }, /*#__PURE__*/external_React_default().createElement("span", null, story.id, " ", /*#__PURE__*/external_React_default().createElement("br", null)), /*#__PURE__*/external_React_default().createElement(ToggleStoryButton, {
+ story: story,
+ onClick: this.onStoryToggle
+ })), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "message-summary"
+ }, /*#__PURE__*/external_React_default().createElement("pre", null, storyData)));
+ }
+
+ renderFeed(feed) {
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+
+ if (!feed.url) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Feed url"), /*#__PURE__*/external_React_default().createElement("td", null, feed.url)), /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Data last fetched"), /*#__PURE__*/external_React_default().createElement("td", null, relativeTime(feeds.data[feed.url] ? feeds.data[feed.url].lastUpdated : null) || "(no data)")));
+ }
+
+ render() {
+ const prefToggles = "enabled hardcoded_layout show_spocs collapsible".split(" ");
+ const {
+ config,
+ lastUpdated,
+ layout
+ } = this.props.state.DiscoveryStream;
+ const personalized = this.props.otherPrefs["discoverystream.personalization.enabled"];
+ return /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.restorePrefDefaults
+ }, "Restore Pref Defaults"), " ", /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.refreshCache
+ }, "Refresh Cache"), /*#__PURE__*/external_React_default().createElement("br", null), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.expireCache
+ }, "Expire Cache"), " ", /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.systemTick
+ }, "Trigger System Tick"), " ", /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.idleDaily
+ }, "Trigger Idle Daily"), /*#__PURE__*/external_React_default().createElement("br", null), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.syncRemoteSettings
+ }, "Sync Remote Settings"), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, prefToggles.map(pref => /*#__PURE__*/external_React_default().createElement(Row, {
+ key: pref
+ }, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement(TogglePrefCheckbox, {
+ checked: config[pref],
+ pref: pref,
+ onChange: this.setConfigValue
+ })))))), /*#__PURE__*/external_React_default().createElement("h3", null, "Endpoint variant"), /*#__PURE__*/external_React_default().createElement("p", null, "You can also change this manually by changing this pref:", " ", /*#__PURE__*/external_React_default().createElement("code", null, "browser.newtabpage.activity-stream.discoverystream.config")), /*#__PURE__*/external_React_default().createElement("table", {
+ style: config.enabled && !config.hardcoded_layout ? null : {
+ opacity: 0.5
+ }
+ }, /*#__PURE__*/external_React_default().createElement("tbody", null, Object.keys(LAYOUT_VARIANTS).map(id => /*#__PURE__*/external_React_default().createElement(Row, {
+ key: id
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "radio",
+ value: id,
+ checked: this.isCurrentVariant(id),
+ onChange: this.changeEndpointVariant
+ })), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, id), /*#__PURE__*/external_React_default().createElement("td", null, LAYOUT_VARIANTS[id]))))), /*#__PURE__*/external_React_default().createElement("h3", null, "Caching info"), /*#__PURE__*/external_React_default().createElement("table", {
+ style: config.enabled ? null : {
+ opacity: 0.5
+ }
+ }, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement(Row, null, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Data last fetched"), /*#__PURE__*/external_React_default().createElement("td", null, relativeTime(lastUpdated) || "(no data)")))), /*#__PURE__*/external_React_default().createElement("h3", null, "Layout"), layout.map((row, rowIndex) => /*#__PURE__*/external_React_default().createElement("div", {
+ key: `row-${rowIndex}`
+ }, row.components.map((component, componentIndex) => /*#__PURE__*/external_React_default().createElement("div", {
+ key: `component-${componentIndex}`,
+ className: "ds-component"
+ }, this.renderComponent(row.width, component))))), /*#__PURE__*/external_React_default().createElement("h3", null, "Personalization"), /*#__PURE__*/external_React_default().createElement(Personalization, {
+ personalized: personalized,
+ dispatch: this.props.dispatch,
+ state: {
+ Personalization: this.props.state.Personalization
+ }
+ }), /*#__PURE__*/external_React_default().createElement("h3", null, "Spocs"), this.renderSpocs(), /*#__PURE__*/external_React_default().createElement("h3", null, "Feeds Data"), this.renderFeedsData());
+ }
+
+}
+class ASRouterAdminInner extends (external_React_default()).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.handleOpenPB = this.handleOpenPB.bind(this);
+ this.selectPBMessage = this.selectPBMessage.bind(this);
+ this.resetPBJSON = this.resetPBJSON.bind(this);
+ this.resetPBMessageState = this.resetPBMessageState.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",
+ collapsedMessages: [],
+ modifiedMessages: [],
+ selectedPBMessage: "",
+ evaluationStatus: {},
+ stringTargetingParameters: null,
+ newStringTargetingParameters: null,
+ copiedToClipboard: false,
+ attributionParameters: {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: `rta:${btoa("uBlock0@raymondhill.net")}`,
+ 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)]
+ }));
+ }
+
+ handleOverride(id) {
+ return () => ASRouterUtils.overrideMessage(id).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message
+ });
+ });
+ }
+
+ resetPBMessageState() {
+ // Iterate over Private Browsing messages and block/unblock each one to clear impressions
+ const PBMessages = this.state.messages.filter(message => message.template === "pb_newtab"); // messages from state go here
+
+ PBMessages.forEach(message => {
+ if (message !== null && message !== void 0 && message.id) {
+ ASRouterUtils.blockById(message.id);
+ ASRouterUtils.unblockById(message.id);
+ }
+ }); // Clear the selected messages & radio buttons
+
+ document.getElementById("clear radio").checked = true;
+ this.selectPBMessage("clear");
+ }
+
+ resetPBJSON(msg) {
+ // reset the displayed JSON for the given message
+ document.getElementById(`${msg.id}-textarea`).value = JSON.stringify(msg, null, 2);
+ }
+
+ handleOpenPB() {
+ ASRouterUtils.sendMessage({
+ type: "FORCE_PRIVATE_BROWSING_WINDOW",
+ data: {
+ message: {
+ content: this.state.selectedPBMessage
+ }
+ }
+ });
+ }
+
+ 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.error(`Error parsing value of parameter ${name}`);
+ 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);
+ const aboutMessagePreviewSupported = ["infobar", "spotlight", "cfr_doorhanger"].includes(msg.template);
+ let itemClassName = "message-item";
+
+ if (isBlocked) {
+ itemClassName += " blocked";
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("tr", {
+ className: itemClassName,
+ key: `${msg.id}-${msg.provider}`
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "message-id"
+ }, /*#__PURE__*/external_React_default().createElement("span", null, msg.id, " ", /*#__PURE__*/external_React_default().createElement("br", null))), /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement(ToggleMessageJSON, {
+ msgId: `${msg.id}`,
+ toggleJSON: this.toggleJSON,
+ isCollapsed: isCollapsed
+ })), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "button-column"
+ }, /*#__PURE__*/external_React_default().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 ? /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button restore" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.resetJSON(msg)
+ }, "Reset") : /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button show",
+ onClick: this.handleOverride(msg.id)
+ }, "Show"), isBlocked ? null : /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button modify" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.modifyJson(msg)
+ }, "Modify"), aboutMessagePreviewSupported ? /*#__PURE__*/external_React_default().createElement(CopyButton, {
+ transformer: text => `about:messagepreview?json=${encodeURIComponent(btoa(text))}`,
+ label: "Share",
+ copiedLabel: "Copied!",
+ inputSelector: `#${msg.id}-textarea`,
+ className: "button share"
+ }) : null, /*#__PURE__*/external_React_default().createElement("br", null), "(", impressions, " impressions)"), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "message-summary"
+ }, isBlocked && /*#__PURE__*/external_React_default().createElement("tr", null, "Block reason:", isBlockedByGroup && " Blocked by group", isProviderExcluded && " Excluded by provider", isMessageBlocked && " Message blocked"), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("pre", {
+ className: isCollapsed ? "collapsed" : "expanded"
+ }, /*#__PURE__*/external_React_default().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))))));
+ }
+
+ selectPBMessage(msgId) {
+ if (msgId === "clear") {
+ this.setState({
+ selectedPBMessage: ""
+ });
+ } else {
+ let selected = document.getElementById(`${msgId} radio`);
+ let msg = JSON.parse(document.getElementById(`${msgId}-textarea`).value);
+
+ if (selected.checked) {
+ this.setState({
+ selectedPBMessage: msg === null || msg === void 0 ? void 0 : msg.content
+ });
+ } else {
+ this.setState({
+ selectedPBMessage: ""
+ });
+ }
+ }
+ }
+
+ 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
+ });
+ });
+ }
+
+ renderPBMessageItem(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 /*#__PURE__*/external_React_default().createElement("tr", {
+ className: itemClassName,
+ key: `${msg.id}-${msg.provider}`
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "message-id"
+ }, /*#__PURE__*/external_React_default().createElement("span", null, msg.id, " ", /*#__PURE__*/external_React_default().createElement("br", null), /*#__PURE__*/external_React_default().createElement("br", null), "(", impressions, " impressions)")), /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement(ToggleMessageJSON, {
+ msgId: `${msg.id}`,
+ toggleJSON: this.toggleJSON,
+ isCollapsed: isCollapsed
+ })), /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "radio",
+ id: `${msg.id} radio`,
+ name: "PB_message_radio",
+ style: {
+ marginBottom: 20
+ },
+ onClick: () => this.selectPBMessage(msg.id),
+ disabled: isBlocked
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ className: `button ${isBlocked ? "" : " primary"}`,
+ onClick: isBlocked ? this.handleUnblock(msg) : this.handleBlock(msg)
+ }, isBlocked ? "Unblock" : "Block"), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton slim button",
+ onClick: e => this.resetPBJSON(msg)
+ }, "Reset JSON")), /*#__PURE__*/external_React_default().createElement("td", {
+ className: `message-summary`
+ }, /*#__PURE__*/external_React_default().createElement("pre", {
+ className: isCollapsed ? "collapsed" : "expanded"
+ }, /*#__PURE__*/external_React_default().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 && message.template !== "pb_newtab");
+ return /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton slim" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.toggleAllMessages(messagesToShow)
+ }, "Collapse/Expand All"), /*#__PURE__*/external_React_default().createElement("p", {
+ className: "helpLink"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", /*#__PURE__*/external_React_default().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. Click 'Share' to copy a link to the clipboard that can be used to preview the message by opening the link in Nightly/local builds.")), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, messagesToShow.map(msg => this.renderMessageItem(msg))));
+ }
+
+ renderPBMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ const messagesToShow = this.state.messages.filter(message => message.template === "pb_newtab");
+ return /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, messagesToShow.map(msg => this.renderPBMessageItem(msg))));
+ }
+
+ renderMessageFilter() {
+ if (!this.state.providers) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("p", null, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "unblock-all ASRouterButton test-only",
+ onClick: this.unblockAll
+ }, "Unblock All Snippets"), "Show messages from", " ", /*#__PURE__*/external_React_default().createElement("select", {
+ value: this.state.messageFilter,
+ onChange: this.onChangeMessageFilter
+ }, /*#__PURE__*/external_React_default().createElement("option", {
+ value: "all"
+ }, "all providers"), this.state.providers.map(provider => /*#__PURE__*/external_React_default().createElement("option", {
+ key: provider.id,
+ value: provider.id
+ }, provider.id))), this.state.messageFilter !== "all" && !this.state.messageFilter.includes("_local_testing") ? /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button messages-reset",
+ onClick: this.handleClearAllImpressionsByProvider
+ }, "Reset All") : null);
+ }
+
+ renderMessageGroupsFilter() {
+ if (!this.state.groups) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("p", null, "Show messages from ", /*#__PURE__*/external_React_default().createElement("select", {
+ value: this.state.messageGroupsFilter,
+ onChange: this.onChangeMessageGroupsFilter
+ }, /*#__PURE__*/external_React_default().createElement("option", {
+ value: "all"
+ }, "all groups"), this.state.groups.map(group => /*#__PURE__*/external_React_default().createElement("option", {
+ key: group.id,
+ value: group.id
+ }, group.id))));
+ }
+
+ renderTableHead() {
+ return /*#__PURE__*/external_React_default().createElement("thead", null, /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item"
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Provider ID"), /*#__PURE__*/external_React_default().createElement("td", null, "Source"), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Cohort"), /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Last Updated")));
+ }
+
+ renderProviders() {
+ const providersConfig = this.state.providerPrefs;
+ const providerInfo = this.state.providers;
+ const userPrefInfo = this.state.userPrefs;
+ return /*#__PURE__*/external_React_default().createElement("table", null, this.renderTableHead(), /*#__PURE__*/external_React_default().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 = /*#__PURE__*/external_React_default().createElement("span", null, "endpoint (", /*#__PURE__*/external_React_default().createElement("a", {
+ className: "providerUrl",
+ target: "_blank",
+ href: info.url,
+ rel: "noopener noreferrer"
+ }, info.url), ")");
+ } else if (provider.type === "remote-settings") {
+ label = `remote settings (${provider.collection})`;
+ } else if (provider.type === "remote-experiments") {
+ label = /*#__PURE__*/external_React_default().createElement("span", null, "remote settings (", /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item",
+ key: i
+ }, /*#__PURE__*/external_React_default().createElement("td", null, isTestProvider ? /*#__PURE__*/external_React_default().createElement("input", {
+ type: "checkbox",
+ disabled: true,
+ readOnly: true,
+ checked: true
+ }) : /*#__PURE__*/external_React_default().createElement("input", {
+ type: "checkbox",
+ "data-provider": provider.id,
+ checked: isUserEnabled && isSystemEnabled,
+ onChange: this.handleEnabledToggle
+ })), /*#__PURE__*/external_React_default().createElement("td", null, provider.id), /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: `sourceLabel${isUserEnabled && isSystemEnabled ? "" : " isDisabled"}`
+ }, label)), /*#__PURE__*/external_React_default().createElement("td", null, provider.cohort), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("h2", null, "Evaluate JEXL expression"))), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("p", null, /*#__PURE__*/external_React_default().createElement("textarea", {
+ ref: "expressionInput",
+ rows: "10",
+ cols: "60",
+ placeholder: "Evaluate JEXL expressions and mock parameters by changing their values below"
+ })), /*#__PURE__*/external_React_default().createElement("p", null, "Status:", " ", /*#__PURE__*/external_React_default().createElement("span", {
+ ref: "evaluationStatus"
+ }, success ? "✅" : "❌", ", Result: ", result))), /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton secondary",
+ onClick: this.handleExpressionEval
+ }, "Evaluate"))), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("h2", null, "Modify targeting parameters"))), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().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 ? /*#__PURE__*/external_React_default().createElement("textarea", {
+ name: param,
+ className: className,
+ value: value,
+ rows: "10",
+ cols: "60",
+ onChange: this.onChangeTargetingParameters
+ }) : /*#__PURE__*/external_React_default().createElement("input", {
+ name: param,
+ className: className,
+ value: value,
+ onChange: this.onChangeTargetingParameters
+ });
+ return /*#__PURE__*/external_React_default().createElement("tr", {
+ key: i
+ }, /*#__PURE__*/external_React_default().createElement("td", null, param), /*#__PURE__*/external_React_default().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) {
+ 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 /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tbody", null, /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item"
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Enabled"), /*#__PURE__*/external_React_default().createElement("td", null, config.enabled ? "yes" : "no")), /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item"
+ }, /*#__PURE__*/external_React_default().createElement("td", {
+ className: "min"
+ }, "Endpoint"), /*#__PURE__*/external_React_default().createElement("td", null, config.endpoint || "(empty)")))));
+ }
+
+ renderAttributionParamers() {
+ return /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("h2", null, " Attribution Parameters "), /*#__PURE__*/external_React_default().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 'uBlock Origin'. 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 a string that is 'rta:base64(addonID)', the base64 string of the addonID prefixed with 'rta:'. The addon must currently be a recommended addon on AMO. Then click 'Force Attribution'. Clicking on 'Force Attribution' with blank text boxes reset attribution data."), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Source ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "source",
+ placeholder: "addons.mozilla.org",
+ value: this.state.attributionParameters.source,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Medium ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "medium",
+ placeholder: "referral",
+ value: this.state.attributionParameters.medium,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Campaign ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "campaign",
+ placeholder: "non-fx-button",
+ value: this.state.attributionParameters.campaign,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Content ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "content",
+ placeholder: `rta:${btoa("uBlock0@raymondhill.net")}`,
+ value: this.state.attributionParameters.content,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Experiment ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "experiment",
+ placeholder: "ua-onboarding",
+ value: this.state.attributionParameters.experiment,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Variation ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "variation",
+ placeholder: "chrome",
+ value: this.state.attributionParameters.variation,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " User Agent ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "ua",
+ placeholder: "Google Chrome 123",
+ value: this.state.attributionParameters.ua,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement("b", null, " Download Token ")), /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("input", {
+ type: "text",
+ name: "dltoken",
+ placeholder: "00000000-0000-0000-0000-000000000000",
+ value: this.state.attributionParameters.dltoken,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("td", null, " ", /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton primary button",
+ onClick: this.setAttribution
+ }, " ", "Force Attribution", " "), " "))));
+ }
+
+ renderErrorMessage({
+ id,
+ errors
+ }) {
+ const providerId = /*#__PURE__*/external_React_default().createElement("td", {
+ rowSpan: errors.length
+ }, id); // .reverse() so that the last error (most recent) is first
+
+ return errors.map(({
+ error,
+ timestamp
+ }, cellKey) => /*#__PURE__*/external_React_default().createElement("tr", {
+ key: cellKey
+ }, cellKey === errors.length - 1 ? providerId : null, /*#__PURE__*/external_React_default().createElement("td", null, error.message), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("table", {
+ className: "errorReporting"
+ }, /*#__PURE__*/external_React_default().createElement("thead", null, /*#__PURE__*/external_React_default().createElement("tr", null, /*#__PURE__*/external_React_default().createElement("th", null, "Provider ID"), /*#__PURE__*/external_React_default().createElement("th", null, "Message"), /*#__PURE__*/external_React_default().createElement("th", null, "Timestamp"))), /*#__PURE__*/external_React_default().createElement("tbody", null, providersWithErrors.map(this.renderErrorMessage)));
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("p", null, "No errors");
+ }
+
+ renderPBTab() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ let messagesToShow = this.state.messages.filter(message => message.template === "pb_newtab");
+ return /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("p", {
+ className: "helpLink"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", /*#__PURE__*/external_React_default().createElement("span", null, "To view an available message, select its radio button and click \"Open a Private Browsing Window\".", /*#__PURE__*/external_React_default().createElement("br", null), "To modify a message, make changes to the JSON first, then select the radio button. (To make new changes, click \"Reset Message State\", make your changes, and reselect the radio button.)", /*#__PURE__*/external_React_default().createElement("br", null), "Click \"Reset Message State\" to clear all message impressions and view messages in a clean state.", /*#__PURE__*/external_React_default().createElement("br", null), "Note that ContentSearch functions do not work in debug mode.")), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton primary button",
+ onClick: this.handleOpenPB
+ }, "Open a Private Browsing Window"), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton primary button",
+ style: {
+ marginInlineStart: 12
+ },
+ onClick: this.resetPBMessageState
+ }, "Reset Message State"), /*#__PURE__*/external_React_default().createElement("br", null), /*#__PURE__*/external_React_default().createElement("input", {
+ type: "radio",
+ id: `clear radio`,
+ name: "PB_message_radio",
+ value: "clearPBMessage",
+ style: {
+ display: "none"
+ }
+ }), /*#__PURE__*/external_React_default().createElement("h2", null, "Messages"), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "ASRouterButton slim button" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.toggleAllMessages(messagesToShow)
+ }, "Collapse/Expand All"), this.renderPBMessages()));
+ }
+
+ getSection() {
+ const [section] = this.props.location.routes;
+
+ switch (section) {
+ case "private":
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "Private Browsing Messages"), this.renderPBTab());
+
+ case "targeting":
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "Targeting Utilities"), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "Message Groups"), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "button",
+ onClick: this.resetGroups
+ }, "Reset group impressions"), /*#__PURE__*/external_React_default().createElement("table", null, /*#__PURE__*/external_React_default().createElement("thead", null, /*#__PURE__*/external_React_default().createElement("tr", {
+ className: "message-item"
+ }, /*#__PURE__*/external_React_default().createElement("td", null, "Enabled"), /*#__PURE__*/external_React_default().createElement("td", null, "Impressions count"), /*#__PURE__*/external_React_default().createElement("td", null, "Custom frequency"), /*#__PURE__*/external_React_default().createElement("td", null, "User preferences"))), /*#__PURE__*/external_React_default().createElement("tbody", null, this.state.groups && this.state.groups.map(({
+ id,
+ enabled,
+ frequency,
+ userPreferences = []
+ }, index) => /*#__PURE__*/external_React_default().createElement(Row, {
+ key: id
+ }, /*#__PURE__*/external_React_default().createElement("td", null, /*#__PURE__*/external_React_default().createElement(TogglePrefCheckbox, {
+ checked: enabled,
+ pref: id,
+ disabled: true
+ })), /*#__PURE__*/external_React_default().createElement("td", null, this._getGroupImpressionsCount(id, frequency)), /*#__PURE__*/external_React_default().createElement("td", null, JSON.stringify(frequency, null, 2)), /*#__PURE__*/external_React_default().createElement("td", null, userPreferences.join(", ")))))), this.renderMessageGroupsFilter(), this.renderMessagesByGroup());
+
+ case "ds":
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "Discovery Stream"), /*#__PURE__*/external_React_default().createElement(DiscoveryStreamAdmin, {
+ state: {
+ DiscoveryStream: this.props.DiscoveryStream,
+ Personalization: this.props.Personalization
+ },
+ otherPrefs: this.props.Prefs.values,
+ dispatch: this.props.dispatch
+ }));
+
+ case "errors":
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "ASRouter Errors"), this.renderErrors());
+
+ default:
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", null, "Message Providers", " ", /*#__PURE__*/external_React_default().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, /*#__PURE__*/external_React_default().createElement("h2", null, "Messages"), this.renderMessageFilter(), this.renderMessages());
+ }
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: `asrouter-admin ${this.props.collapsed ? "collapsed" : "expanded"}`
+ }, /*#__PURE__*/external_React_default().createElement("aside", {
+ className: "sidebar"
+ }, /*#__PURE__*/external_React_default().createElement("ul", null, /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools"
+ }, "General")), /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools-private"
+ }, "Private Browsing")), /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools-targeting"
+ }, "Targeting")), /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools-groups"
+ }, "Message Groups")), /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools-ds"
+ }, "Discovery Stream")), /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools-errors"
+ }, "Errors")))), /*#__PURE__*/external_React_default().createElement("main", {
+ className: "main-panel"
+ }, /*#__PURE__*/external_React_default().createElement("h1", null, "AS Router Admin"), /*#__PURE__*/external_React_default().createElement("p", {
+ className: "helpLink"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", /*#__PURE__*/external_React_default().createElement("span", null, "Need help using these tools? Check out our", " ", /*#__PURE__*/external_React_default().createElement("a", {
+ target: "blank",
+ href: "https://firefox-source-docs.mozilla.org/browser/components/newtab/content-src/asrouter/docs/debugging-docs.html"
+ }, "documentation"))), this.getSection()));
+ }
+
+}
+class CollapseToggle extends (external_React_default()).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) {
+ __webpack_require__.g.document.body.classList.add("no-scroll");
+ } else {
+ __webpack_require__.g.document.body.classList.remove("no-scroll");
+ }
+ }
+
+ componentDidMount() {
+ this.setBodyClass();
+ }
+
+ componentDidUpdate() {
+ this.setBodyClass();
+ }
+
+ componentWillUnmount() {
+ __webpack_require__.g.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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("a", {
+ href: "#devtools",
+ title: label,
+ "aria-label": label,
+ className: `asrouter-toggle ${isCollapsed ? "collapsed" : "expanded"}`,
+ onClick: this.renderAdmin ? this.onCollapseToggle : null
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-devtools"
+ })), renderAdmin ? /*#__PURE__*/external_React_default().createElement(ASRouterAdminInner, ASRouterAdmin_extends({}, props, {
+ collapsed: this.state.collapsed
+ })) : null);
+ }
+
+}
+
+const _ASRouterAdmin = props => /*#__PURE__*/external_React_default().createElement(SimpleHashRouter, null, /*#__PURE__*/external_React_default().createElement(CollapseToggle, props));
+
+const ASRouterAdmin = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Personalization: state.Personalization,
+ Prefs: state.Prefs
+}))(_ASRouterAdmin);
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/types.js
+/**
+ * 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 a `FluentType` instance.
+ *
+ * @param value The JavaScript value to wrap.
+ */
+ constructor(value) {
+ this.value = value;
+ }
+ /**
+ * Unwrap the raw value stored by this `FluentType`.
+ */
+
+
+ valueOf() {
+ return this.value;
+ }
+
+}
+/**
+ * A `FluentType` representing no correct value.
+ */
+
+class FluentNone extends FluentType {
+ /**
+ * Create an instance of `FluentNone` with an optional fallback value.
+ * @param value The fallback value of this `FluentNone`.
+ */
+ constructor(value = "???") {
+ super(value);
+ }
+ /**
+ * Format this `FluentNone` to the fallback string.
+ */
+
+
+ toString(scope) {
+ return `{${this.value}}`;
+ }
+
+}
+/**
+ * A `FluentType` representing a number.
+ *
+ * A `FluentNumber` instance stores the number value of the number it
+ * represents. It may also store an option bag of options which will be passed
+ * to `Intl.NumerFormat` when the `FluentNumber` is formatted to a string.
+ */
+
+class FluentNumber extends FluentType {
+ /**
+ * Create an instance of `FluentNumber` with options to the
+ * `Intl.NumberFormat` constructor.
+ *
+ * @param value The number value of this `FluentNumber`.
+ * @param opts Options which will be passed to `Intl.NumberFormat`.
+ */
+ constructor(value, opts = {}) {
+ super(value);
+ this.opts = opts;
+ }
+ /**
+ * Format this `FluentNumber` to a string.
+ */
+
+
+ toString(scope) {
+ try {
+ const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);
+ return nf.format(this.value);
+ } catch (err) {
+ scope.reportError(err);
+ return this.value.toString(10);
+ }
+ }
+
+}
+/**
+ * A `FluentType` representing a date and time.
+ *
+ * A `FluentDateTime` instance stores the number value of the date it
+ * represents, as a numerical timestamp in milliseconds. It may also store an
+ * option bag of options which will be passed to `Intl.DateTimeFormat` when the
+ * `FluentDateTime` is formatted to a string.
+ */
+
+class FluentDateTime extends FluentType {
+ /**
+ * Create an instance of `FluentDateTime` with options to the
+ * `Intl.DateTimeFormat` constructor.
+ *
+ * @param value The number value of this `FluentDateTime`, in milliseconds.
+ * @param opts Options which will be passed to `Intl.DateTimeFormat`.
+ */
+ constructor(value, opts = {}) {
+ super(value);
+ this.opts = opts;
+ }
+ /**
+ * Format this `FluentDateTime` to a string.
+ */
+
+
+ toString(scope) {
+ try {
+ const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);
+ return dtf.format(this.value);
+ } catch (err) {
+ scope.reportError(err);
+ return new Date(this.value).toISOString();
+ }
+ }
+
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resolver.js
+/* global Intl */
+
+/**
+ * @overview
+ *
+ * The role of the Fluent resolver is to format a `Pattern` to an instance of
+ * `FluentValue`. For performance reasons, primitive strings are considered
+ * such instances, too.
+ *
+ * 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 and dates into the bundle's languages.
+ * 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 `FluentValue`. The caller should
+ * use the `toString` method to convert the instance to a native value.
+ *
+ * Functions in this file pass around an instance of the `Scope` class, which
+ * stores the data required for successful resolution and error recovery.
+ */
+ // The maximum number of placeables which can be expanded in a single call to
+// `formatPattern`. The limit protects against the Billion Laughs and Quadratic
+// Blowup attacks. See https://msdn.microsoft.com/en-us/magazine/ee335713.aspx.
+
+const MAX_PLACEABLES = 100; // Unicode bidi isolation characters.
+
+const FSI = "\u2068";
+const PDI = "\u2069"; // Helper: match a variant key to the given selector.
+
+function match(scope, 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 = scope.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 resolvePattern(scope, variants[star].value);
+ }
+
+ scope.reportError(new RangeError("No default"));
+ return new FluentNone();
+} // Helper: resolve arguments to a call expression.
+
+
+function getArguments(scope, args) {
+ const positional = [];
+ const named = Object.create(null);
+
+ for (const arg of args) {
+ if (arg.type === "narg") {
+ named[arg.name] = resolveExpression(scope, arg.value);
+ } else {
+ positional.push(resolveExpression(scope, arg));
+ }
+ }
+
+ return {
+ positional,
+ named
+ };
+} // Resolve an expression to a Fluent type.
+
+
+function resolveExpression(scope, expr) {
+ switch (expr.type) {
+ case "str":
+ return expr.value;
+
+ case "num":
+ return new FluentNumber(expr.value, {
+ minimumFractionDigits: expr.precision
+ });
+
+ case "var":
+ return resolveVariableReference(scope, expr);
+
+ case "mesg":
+ return resolveMessageReference(scope, expr);
+
+ case "term":
+ return resolveTermReference(scope, expr);
+
+ case "func":
+ return resolveFunctionReference(scope, expr);
+
+ case "select":
+ return resolveSelectExpression(scope, expr);
+
+ default:
+ return new FluentNone();
+ }
+} // Resolve a reference to a variable.
+
+
+function resolveVariableReference(scope, {
+ name
+}) {
+ let arg;
+
+ if (scope.params) {
+ // We're inside a TermReference. It's OK to reference undefined parameters.
+ if (Object.prototype.hasOwnProperty.call(scope.params, name)) {
+ arg = scope.params[name];
+ } else {
+ return new FluentNone(`$${name}`);
+ }
+ } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) {
+ // We're in the top-level Pattern or inside a MessageReference. Missing
+ // variables references produce ReferenceErrors.
+ arg = scope.args[name];
+ } else {
+ scope.reportError(new ReferenceError(`Unknown variable: $${name}`));
+ return new FluentNone(`$${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.getTime());
+ }
+
+ // eslint-disable-next-line no-fallthrough
+
+ default:
+ scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));
+ return new FluentNone(`$${name}`);
+ }
+} // Resolve a reference to another message.
+
+
+function resolveMessageReference(scope, {
+ name,
+ attr
+}) {
+ const message = scope.bundle._messages.get(name);
+
+ if (!message) {
+ scope.reportError(new ReferenceError(`Unknown message: ${name}`));
+ return new FluentNone(name);
+ }
+
+ if (attr) {
+ const attribute = message.attributes[attr];
+
+ if (attribute) {
+ return resolvePattern(scope, attribute);
+ }
+
+ scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
+ return new FluentNone(`${name}.${attr}`);
+ }
+
+ if (message.value) {
+ return resolvePattern(scope, message.value);
+ }
+
+ scope.reportError(new ReferenceError(`No value: ${name}`));
+ return new FluentNone(name);
+} // Resolve a call to a Term with key-value arguments.
+
+
+function resolveTermReference(scope, {
+ name,
+ attr,
+ args
+}) {
+ const id = `-${name}`;
+
+ const term = scope.bundle._terms.get(id);
+
+ if (!term) {
+ scope.reportError(new ReferenceError(`Unknown term: ${id}`));
+ return new FluentNone(id);
+ }
+
+ if (attr) {
+ const attribute = term.attributes[attr];
+
+ if (attribute) {
+ // Every TermReference has its own variables.
+ scope.params = getArguments(scope, args).named;
+ const resolved = resolvePattern(scope, attribute);
+ scope.params = null;
+ return resolved;
+ }
+
+ scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
+ return new FluentNone(`${id}.${attr}`);
+ }
+
+ scope.params = getArguments(scope, args).named;
+ const resolved = resolvePattern(scope, term.value);
+ scope.params = null;
+ return resolved;
+} // Resolve a call to a Function with positional and key-value arguments.
+
+
+function resolveFunctionReference(scope, {
+ name,
+ args
+}) {
+ // Some functions are built-in. Others may be provided by the runtime via
+ // the `FluentBundle` constructor.
+ let func = scope.bundle._functions[name];
+
+ if (!func) {
+ scope.reportError(new ReferenceError(`Unknown function: ${name}()`));
+ return new FluentNone(`${name}()`);
+ }
+
+ if (typeof func !== "function") {
+ scope.reportError(new TypeError(`Function ${name}() is not callable`));
+ return new FluentNone(`${name}()`);
+ }
+
+ try {
+ let resolved = getArguments(scope, args);
+ return func(resolved.positional, resolved.named);
+ } catch (err) {
+ scope.reportError(err);
+ return new FluentNone(`${name}()`);
+ }
+} // Resolve a select expression to the member object.
+
+
+function resolveSelectExpression(scope, {
+ selector,
+ variants,
+ star
+}) {
+ let sel = resolveExpression(scope, selector);
+
+ if (sel instanceof FluentNone) {
+ return getDefault(scope, variants, star);
+ } // Match the selector against keys of each variant, in order.
+
+
+ for (const variant of variants) {
+ const key = resolveExpression(scope, variant.key);
+
+ if (match(scope, sel, key)) {
+ return resolvePattern(scope, variant.value);
+ }
+ }
+
+ return getDefault(scope, variants, star);
+} // Resolve a pattern (a complex string with placeables).
+
+
+function resolveComplexPattern(scope, ptn) {
+ if (scope.dirty.has(ptn)) {
+ scope.reportError(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;
+ }
+
+ scope.placeables++;
+
+ if (scope.placeables > MAX_PLACEABLES) {
+ scope.dirty.delete(ptn); // This is a fatal error which causes the resolver to instantly bail out
+ // on this pattern. The length check protects against excessive memory
+ // usage, and throwing protects against eating up the CPU when long
+ // placeables are deeply nested.
+
+ throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`);
+ }
+
+ if (useIsolating) {
+ result.push(FSI);
+ }
+
+ result.push(resolveExpression(scope, elem).toString(scope));
+
+ if (useIsolating) {
+ result.push(PDI);
+ }
+ }
+
+ scope.dirty.delete(ptn);
+ return result.join("");
+} // Resolve a simple or a complex Pattern to a FluentString (which is really the
+// string primitive).
+
+function resolvePattern(scope, value) {
+ // Resolve a simple pattern.
+ if (typeof value === "string") {
+ return scope.bundle._transform(value);
+ }
+
+ return resolveComplexPattern(scope, value);
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/scope.js
+class Scope {
+ constructor(bundle, errors, args) {
+ /** The Set of patterns already encountered during this resolution.
+ * Used to detect and prevent cyclic resolutions. */
+ this.dirty = new WeakSet();
+ /** A dict of parameters passed to a TermReference. */
+
+ this.params = null;
+ /** The running count of placeables resolved so far. Used to detect the
+ * Billion Laughs and Quadratic Blowup attacks. */
+
+ this.placeables = 0;
+ this.bundle = bundle;
+ this.errors = errors;
+ this.args = args;
+ }
+
+ reportError(error) {
+ if (!this.errors || !(error instanceof Error)) {
+ throw error;
+ }
+
+ this.errors.push(error);
+ }
+
+ memoizeIntlObject(ctor, opts) {
+ let cache = this.bundle._intls.get(ctor);
+
+ if (!cache) {
+ cache = {};
+
+ this.bundle._intls.set(ctor, cache);
+ }
+
+ let id = JSON.stringify(opts);
+
+ if (!cache[id]) {
+ cache[id] = new ctor(this.bundle.locales, opts);
+ }
+
+ return cache[id];
+ }
+
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/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
+ * `FluentValue`. Functions must return `FluentValues` as well.
+ */
+
+
+function values(opts, allowed) {
+ const unwrapped = Object.create(null);
+
+ for (const [name, opt] of Object.entries(opts)) {
+ if (allowed.includes(name)) {
+ unwrapped[name] = opt.valueOf();
+ }
+ }
+
+ return unwrapped;
+}
+
+const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"];
+/**
+ * The implementation of the `NUMBER()` builtin available to translations.
+ *
+ * Translations may call the `NUMBER()` builtin in order to specify formatting
+ * options of a number. For example:
+ *
+ * pi = The value of π is {NUMBER($pi, maximumFractionDigits: 2)}.
+ *
+ * The implementation expects an array of `FluentValues` representing the
+ * positional arguments, and an object of named `FluentValues` representing the
+ * named parameters.
+ *
+ * The following options are recognized:
+ *
+ * unitDisplay
+ * currencyDisplay
+ * useGrouping
+ * minimumIntegerDigits
+ * minimumFractionDigits
+ * maximumFractionDigits
+ * minimumSignificantDigits
+ * maximumSignificantDigits
+ *
+ * Other options are ignored.
+ *
+ * @param args The positional arguments passed to this `NUMBER()`.
+ * @param opts The named argments passed to this `NUMBER()`.
+ */
+
+function NUMBER(args, opts) {
+ let arg = args[0];
+
+ if (arg instanceof FluentNone) {
+ return new FluentNone(`NUMBER(${arg.valueOf()})`);
+ }
+
+ if (arg instanceof FluentNumber) {
+ return new FluentNumber(arg.valueOf(), { ...arg.opts,
+ ...values(opts, NUMBER_ALLOWED)
+ });
+ }
+
+ if (arg instanceof FluentDateTime) {
+ return new FluentNumber(arg.valueOf(), { ...values(opts, NUMBER_ALLOWED)
+ });
+ }
+
+ throw new TypeError("Invalid argument to NUMBER");
+}
+const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"];
+/**
+ * The implementation of the `DATETIME()` builtin available to translations.
+ *
+ * Translations may call the `DATETIME()` builtin in order to specify
+ * formatting options of a number. For example:
+ *
+ * now = It's {DATETIME($today, month: "long")}.
+ *
+ * The implementation expects an array of `FluentValues` representing the
+ * positional arguments, and an object of named `FluentValues` representing the
+ * named parameters.
+ *
+ * The following options are recognized:
+ *
+ * dateStyle
+ * timeStyle
+ * fractionalSecondDigits
+ * dayPeriod
+ * hour12
+ * weekday
+ * era
+ * year
+ * month
+ * day
+ * hour
+ * minute
+ * second
+ * timeZoneName
+ *
+ * Other options are ignored.
+ *
+ * @param args The positional arguments passed to this `DATETIME()`.
+ * @param opts The named argments passed to this `DATETIME()`.
+ */
+
+function DATETIME(args, opts) {
+ let arg = args[0];
+
+ if (arg instanceof FluentNone) {
+ return new FluentNone(`DATETIME(${arg.valueOf()})`);
+ }
+
+ if (arg instanceof FluentDateTime) {
+ return new FluentDateTime(arg.valueOf(), { ...arg.opts,
+ ...values(opts, DATETIME_ALLOWED)
+ });
+ }
+
+ if (arg instanceof FluentNumber) {
+ return new FluentDateTime(arg.valueOf(), { ...values(opts, DATETIME_ALLOWED)
+ });
+ }
+
+ throw new TypeError("Invalid argument to DATETIME");
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/memoizer.js
+const cache = new Map();
+function getMemoizerForLocale(locales) {
+ const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales;
+ let memoizer = cache.get(stringLocale);
+
+ if (memoizer === undefined) {
+ memoizer = new Map();
+ cache.set(stringLocale, memoizer);
+ }
+
+ return memoizer;
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/bundle.js
+
+
+
+
+
+/**
+ * Message bundles are single-language stores of translation resources. They are
+ * responsible for formatting message values and attributes to strings.
+ */
+
+class 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:
+ *
+ * let bundle = new FluentBundle(["en-US", "en"]);
+ *
+ * let bundle = new FluentBundle(locales, {useIsolating: false});
+ *
+ * let 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.
+ */
+ constructor(locales, {
+ functions,
+ useIsolating = true,
+ transform = v => v
+ } = {}) {
+ this._terms = new Map();
+ this._messages = new Map();
+ this.locales = Array.isArray(locales) ? locales : [locales];
+ this._functions = {
+ NUMBER: NUMBER,
+ DATETIME: DATETIME,
+ ...functions
+ };
+ this._useIsolating = useIsolating;
+ this._transform = transform;
+ this._intls = getMemoizerForLocale(locales);
+ }
+ /**
+ * Check if a message is present in the bundle.
+ *
+ * @param id - The identifier of the message to check.
+ */
+
+
+ hasMessage(id) {
+ return this._messages.has(id);
+ }
+ /**
+ * Return a raw unformatted message object from the bundle.
+ *
+ * Raw messages are `{value, attributes}` shapes containing translation units
+ * called `Patterns`. `Patterns` are implementation-specific; they should be
+ * treated as black boxes and formatted with `FluentBundle.formatPattern`.
+ *
+ * @param id - The identifier of the message to check.
+ */
+
+
+ getMessage(id) {
+ return this._messages.get(id);
+ }
+ /**
+ * Add a translation resource to the bundle.
+ *
+ * The translation resource must be an instance of `FluentResource`.
+ *
+ * let res = new FluentResource("foo = Foo");
+ * bundle.addResource(res);
+ * bundle.getMessage("foo");
+ * // → {value: .., attributes: {..}}
+ *
+ * Available options:
+ *
+ * - `allowOverrides` - boolean specifying whether it's allowed to override
+ * an existing message or term with a new value. Default: `false`.
+ *
+ * @param res - FluentResource object.
+ * @param options
+ */
+
+
+ addResource(res, {
+ allowOverrides = false
+ } = {}) {
+ const errors = [];
+
+ for (let i = 0; i < res.body.length; i++) {
+ let entry = res.body[i];
+
+ if (entry.id.startsWith("-")) {
+ // Identifiers starting with a dash (-) define terms. Terms are private
+ // and cannot be retrieved from FluentBundle.
+ if (allowOverrides === false && this._terms.has(entry.id)) {
+ errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`));
+ continue;
+ }
+
+ this._terms.set(entry.id, entry);
+ } else {
+ if (allowOverrides === false && this._messages.has(entry.id)) {
+ errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`));
+ continue;
+ }
+
+ this._messages.set(entry.id, entry);
+ }
+ }
+
+ return errors;
+ }
+ /**
+ * Format a `Pattern` to a string.
+ *
+ * Format a raw `Pattern` into a string. `args` will be used to resolve
+ * references to variables passed as arguments to the translation.
+ *
+ * In case of errors `formatPattern` 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.
+ *
+ * let errors = [];
+ * bundle.addResource(
+ * new FluentResource("hello = Hello, {$name}!"));
+ *
+ * let hello = bundle.getMessage("hello");
+ * if (hello.value) {
+ * bundle.formatPattern(hello.value, {name: "Jane"}, errors);
+ * // Returns "Hello, Jane!" and `errors` is empty.
+ *
+ * bundle.formatPattern(hello.value, undefined, errors);
+ * // Returns "Hello, {$name}!" and `errors` is now:
+ * // [<ReferenceError: Unknown variable: name>]
+ * }
+ *
+ * If `errors` is omitted, the first encountered error will be thrown.
+ */
+
+
+ formatPattern(pattern, args = null, errors = null) {
+ // Resolve a simple pattern without creating a scope. No error handling is
+ // required; by definition simple patterns don't have placeables.
+ if (typeof pattern === "string") {
+ return this._transform(pattern);
+ } // Resolve a complex pattern.
+
+
+ let scope = new Scope(this, errors, args);
+
+ try {
+ let value = resolveComplexPattern(scope, pattern);
+ return value.toString(scope);
+ } catch (err) {
+ if (scope.errors && err instanceof Error) {
+ scope.errors.push(err);
+ return new FluentNone().toString(scope);
+ }
+
+ throw err;
+ }
+ }
+
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/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-]*) *= */gm; // 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;
+/**
+ * Fluent Resource is a structure storing parsed localization entries.
+ */
+
+class FluentResource {
+ constructor(source) {
+ this.body = [];
+ RE_MESSAGE_START.lastIndex = 0;
+ 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 {
+ this.body.push(parseMessage(next[1]));
+ } catch (err) {
+ if (err instanceof SyntaxError) {
+ // Don't report any Fluent syntax errors. Skip directly to the
+ // beginning of the next message or term.
+ continue;
+ }
+
+ throw err;
+ }
+ } // The parser implementation is inlined below for performance reasons,
+ // as well as for convenience of accessing `source` and `cursor`.
+ // 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 SyntaxError(`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(id) {
+ let value = parsePattern();
+ let attributes = parseAttributes();
+
+ if (value === null && Object.keys(attributes).length === 0) {
+ throw new SyntaxError("Expected message value or attributes");
+ }
+
+ return {
+ id,
+ value,
+ attributes
+ };
+ }
+
+ function parseAttributes() {
+ let attrs = Object.create(null);
+
+ while (test(RE_ATTRIBUTE_START)) {
+ let name = match1(RE_ATTRIBUTE_START);
+ let value = parsePattern();
+
+ if (value === null) {
+ throw new SyntaxError("Expected attribute value");
+ }
+
+ attrs[name] = value;
+ }
+
+ return attrs;
+ }
+
+ function parsePattern() {
+ let first; // First try to parse any simple text on the same line as the id.
+
+ if (test(RE_TEXT_RUN)) {
+ 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) {
+ while (true) {
+ if (test(RE_TEXT_RUN)) {
+ elements.push(match1(RE_TEXT_RUN));
+ continue;
+ }
+
+ if (source[cursor] === "{") {
+ elements.push(parsePlaceable());
+ continue;
+ }
+
+ if (source[cursor] === "}") {
+ throw new SyntaxError("Unbalanced closing brace");
+ }
+
+ let indent = parseIndent();
+
+ if (indent) {
+ elements.push(indent);
+ commonIndent = Math.min(commonIndent, indent.length);
+ continue;
+ }
+
+ break;
+ }
+
+ let lastIndex = elements.length - 1;
+ let lastElement = elements[lastIndex]; // Trim the trailing spaces in the last element if it's a TextElement.
+
+ if (typeof lastElement === "string") {
+ elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);
+ }
+
+ let baked = [];
+
+ for (let element of elements) {
+ if (element instanceof Indent) {
+ // Dedent indented lines by the maximum common indent.
+ element = element.value.slice(0, element.value.length - commonIndent);
+ }
+
+ if (element) {
+ baked.push(element);
+ }
+ }
+
+ return baked;
+ }
+
+ function parsePlaceable() {
+ consumeToken(TOKEN_BRACE_OPEN, SyntaxError);
+ let selector = parseInlineExpression();
+
+ if (consumeToken(TOKEN_BRACE_CLOSE)) {
+ return selector;
+ }
+
+ if (consumeToken(TOKEN_ARROW)) {
+ let variants = parseVariants();
+ consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);
+ return {
+ type: "select",
+ selector,
+ ...variants
+ };
+ }
+
+ throw new SyntaxError("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 SyntaxError("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 SyntaxError("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 SyntaxError("Expected variant value");
+ }
+
+ variants[count++] = {
+ key,
+ value
+ };
+ }
+
+ if (count === 0) {
+ return null;
+ }
+
+ if (star === undefined) {
+ throw new SyntaxError("Expected default variant");
+ }
+
+ return {
+ variants,
+ star
+ };
+ }
+
+ function parseVariantKey() {
+ consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);
+ let key;
+
+ if (test(RE_NUMBER_LITERAL)) {
+ key = parseNumberLiteral();
+ } else {
+ key = {
+ type: "str",
+ value: match1(RE_IDENTIFIER)
+ };
+ }
+
+ consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);
+ return key;
+ }
+
+ function parseLiteral() {
+ if (test(RE_NUMBER_LITERAL)) {
+ return parseNumberLiteral();
+ }
+
+ if (source[cursor] === '"') {
+ return parseStringLiteral();
+ }
+
+ throw new SyntaxError("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('"', SyntaxError);
+ 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 SyntaxError("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 SyntaxError("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"); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+
+ let length = RE_INDENT.exec(blank)[1].length;
+ return new Indent(value, length);
+ }
+ }
+
+}
+
+class Indent {
+ constructor(value, length) {
+ this.value = value;
+ this.length = length;
+ }
+
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/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
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 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.addResource(new FluentResource(`${key} = ${string}`));
+ });
+ return [bundle];
+}
+;// CONCATENATED MODULE: ./content-src/asrouter/components/ImpressionsWrapper/ImpressionsWrapper.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 VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+/**
+ * Component wrapper used to send telemetry pings on every impression.
+ */
+
+class ImpressionsWrapper extends (external_React_default()).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: __webpack_require__.g.document,
+ sendOnMount: true
+};
+;// CONCATENATED MODULE: ./node_modules/@fluent/sequence/esm/map_sync.js
+/**
+ * Synchronously map an identifier or an array of identifiers to the best
+ * `FluentBundle` instance(s).
+ *
+ * @param bundles - An iterable of bundles to sift through.
+ * @param ids - An id or ids to map.
+ */
+function mapBundleSync(bundles, ids) {
+ if (!Array.isArray(ids)) {
+ return getBundleForId(bundles, ids);
+ }
+
+ return ids.map(id => getBundleForId(bundles, id));
+}
+/*
+ * Find the best `FluentBundle` with the translation for `id`.
+ */
+
+function getBundleForId(bundles, id) {
+ for (const bundle of bundles) {
+ if (bundle.hasMessage(id)) {
+ return bundle;
+ }
+ }
+
+ return null;
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/sequence/esm/map_async.js
+/**
+ * Asynchronously map an identifier or an array of identifiers to the best
+ * `FluentBundle` instance(s).
+ *
+ * @param bundles - An iterable of bundles to sift through.
+ * @param ids - An id or ids to map.
+ */
+async function mapBundleAsync(bundles, ids) {
+ if (!Array.isArray(ids)) {
+ for await (const bundle of bundles) {
+ if (bundle.hasMessage(ids)) {
+ return bundle;
+ }
+ }
+
+ return null;
+ }
+
+ const foundBundles = new Array(ids.length).fill(null);
+ let remainingCount = ids.length;
+
+ for await (const bundle of bundles) {
+ 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 bundles.
+
+
+ if (remainingCount === 0) {
+ return foundBundles;
+ }
+ }
+ }
+
+ return foundBundles;
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/sequence/esm/index.js
+/**
+ * @module fluent-sequence
+ * @overview Manage ordered sequences of FluentBundles.
+ */
+
+
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/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/@fluent/react/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 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/@fluent/react/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 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.");
+ }
+ }
+
+ /**
+ * 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(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 && (await 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/@fluent/react/node_modules/cached-iterable/src/index.mjs
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/markup.js
+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/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 */ const 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 */ const vendor_voidElementTags = (voidElementTags);
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/localization.js
+
+
+
+
+ // Match the opening angle bracket (<) in HTML tags, and HTML entities like
+// &amp;, &#0038;, &#x0026;.
+
+const reMarkup = /<|&#?\w+;/;
+/**
+ * `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.
+ *
+ * The `ReactLocalization` class instances are exposed to `Localized` elements
+ * via the `LocalizationProvider` component.
+ */
+
+class ReactLocalization {
+ constructor(bundles, parseMarkup = createParseMarkup()) {
+ this.bundles = CachedSyncIterable.from(bundles);
+ this.parseMarkup = parseMarkup;
+ }
+
+ getBundle(id) {
+ return mapBundleSync(this.bundles, id);
+ }
+
+ areBundlesEmpty() {
+ // Create an iterator and only peek at the first value to see if it contains
+ // anything.
+ return Boolean(this.bundles[Symbol.iterator]().next().done);
+ }
+
+ getString(id, vars, fallback) {
+ const bundle = this.getBundle(id);
+
+ if (bundle) {
+ const msg = bundle.getMessage(id);
+
+ if (msg && msg.value) {
+ let errors = [];
+ let value = bundle.formatPattern(msg.value, vars, errors);
+
+ for (let error of errors) {
+ this.reportError(error);
+ }
+
+ return value;
+ }
+ } else {
+ if (this.areBundlesEmpty()) {
+ this.reportError(new Error("Attempting to get a string when no localization bundles are " + "present."));
+ } else {
+ this.reportError(new Error(`The id "${id}" did not match any messages in the localization ` + "bundles."));
+ }
+ }
+
+ return fallback || id;
+ }
+
+ getElement(sourceElement, id, args = {}) {
+ const bundle = this.getBundle(id);
+
+ if (bundle === null) {
+ if (!id) {
+ this.reportError(new Error("No string id was provided when localizing a component."));
+ } else if (this.areBundlesEmpty()) {
+ this.reportError(new Error("Attempting to get a localized element when no localization bundles are " + "present."));
+ } else {
+ this.reportError(new Error(`The id "${id}" did not match any messages in the localization ` + "bundles."));
+ }
+
+ return /*#__PURE__*/(0,external_React_namespaceObject.createElement)(external_React_namespaceObject.Fragment, null, sourceElement);
+ } // this.getBundle makes the bundle.hasMessage check which ensures that
+ // bundle.getMessage returns an existing message.
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+
+
+ const msg = bundle.getMessage(id);
+ let errors = [];
+ let localizedProps; // 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 (args.attrs && msg.attributes) {
+ localizedProps = {};
+ errors = [];
+
+ for (const [name, allowed] of Object.entries(args.attrs)) {
+ if (allowed && name in msg.attributes) {
+ localizedProps[name] = bundle.formatPattern(msg.attributes[name], args.vars, errors);
+ }
+ }
+
+ for (let error of errors) {
+ this.reportError(error);
+ }
+ } // If the component to render 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 (typeof sourceElement.type === "string" && sourceElement.type in vendor_voidElementTags) {
+ return /*#__PURE__*/(0,external_React_namespaceObject.cloneElement)(sourceElement, 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 (msg.value === null) {
+ return /*#__PURE__*/(0,external_React_namespaceObject.cloneElement)(sourceElement, localizedProps);
+ }
+
+ errors = [];
+ const messageValue = bundle.formatPattern(msg.value, args.vars, errors);
+
+ for (let error of errors) {
+ this.reportError(error);
+ } // If the message value doesn't contain any markup nor any HTML entities,
+ // insert it as the only child of the component to render.
+
+
+ if (!reMarkup.test(messageValue) || this.parseMarkup === null) {
+ return /*#__PURE__*/(0,external_React_namespaceObject.cloneElement)(sourceElement, localizedProps, messageValue);
+ }
+
+ let elemsLower;
+
+ if (args.elems) {
+ elemsLower = new Map();
+
+ for (let [name, elem] of Object.entries(args.elems)) {
+ // Ignore elems which are not valid React elements.
+ if (! /*#__PURE__*/(0,external_React_namespaceObject.isValidElement)(elem)) {
+ continue;
+ }
+
+ elemsLower.set(name.toLowerCase(), elem);
+ }
+ } // If the message contains markup, parse it and try to match the children
+ // found in the translation with the args passed to this function.
+
+
+ const translationNodes = this.parseMarkup(messageValue);
+ const translatedChildren = translationNodes.map(({
+ nodeName,
+ textContent
+ }) => {
+ if (nodeName === "#text") {
+ return textContent;
+ }
+
+ const childName = nodeName.toLowerCase();
+ const sourceChild = elemsLower === null || elemsLower === void 0 ? void 0 : elemsLower.get(childName); // If the child is not expected just take its textContent.
+
+ if (!sourceChild) {
+ return textContent;
+ } // If the element passed in the elems prop 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 (typeof sourceChild.type === "string" && 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 /*#__PURE__*/(0,external_React_namespaceObject.cloneElement)(sourceChild, undefined, textContent);
+ });
+ return /*#__PURE__*/(0,external_React_namespaceObject.cloneElement)(sourceElement, localizedProps, ...translatedChildren);
+ } // XXX Control this via a prop passed to the LocalizationProvider.
+ // See https://github.com/projectfluent/fluent.js/issues/411.
+
+
+ reportError(error) {
+ /* global console */
+ // eslint-disable-next-line no-console
+ console.warn(`[@fluent/react] ${error.name}: ${error.message}`);
+ }
+
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/context.js
+
+let FluentContext = /*#__PURE__*/(0,external_React_namespaceObject.createContext)(null);
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/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` takes an instance of `ReactLocalization` in the
+ * `l10n` prop. This instance will be made available to `Localized` components
+ * under the provider.
+ *
+ * @example
+ * ```jsx
+ * <LocalizationProvider l10n={…}>
+ * …
+ * </LocalizationProvider>
+ * ```
+ */
+
+function LocalizationProvider(props) {
+ return /*#__PURE__*/(0,external_React_namespaceObject.createElement)(FluentContext.Provider, {
+ value: props.l10n
+ }, props.children);
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/with_localization.js
+
+
+function withLocalization(Inner) {
+ function WithLocalization(props) {
+ const l10n = (0,external_React_namespaceObject.useContext)(FluentContext);
+
+ if (!l10n) {
+ throw new Error("withLocalization was used without wrapping it in a " + "<LocalizationProvider />.");
+ } // Re-bind getString to trigger a re-render of Inner.
+
+
+ const getString = l10n.getString.bind(l10n);
+ return /*#__PURE__*/(0,external_React_namespaceObject.createElement)(Inner, {
+ getString,
+ ...props
+ });
+ }
+
+ WithLocalization.displayName = `WithLocalization(${displayName(Inner)})`;
+ return WithLocalization;
+}
+
+function displayName(component) {
+ return component.displayName || component.name || "Component";
+}
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/localized.js
+
+
+/**
+ * The `Localized` class renders its child with translated props and children.
+ *
+ * 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`.
+ *
+ * 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.
+ *
+ * @example
+ * ```jsx
+ * <Localized id="hello-world">
+ * <p>{'Hello, world!'}</p>
+ * </Localized>
+ *
+ * <Localized id="hello-world" $username={name}>
+ * <p>{'Hello, { $username }!'}</p>
+ * </Localized>
+ * ```
+ */
+
+function Localized(props) {
+ const {
+ id,
+ attrs,
+ vars,
+ elems,
+ children
+ } = props;
+ const l10n = (0,external_React_namespaceObject.useContext)(FluentContext);
+
+ if (!l10n) {
+ throw new Error("The <Localized /> component was not properly wrapped in a <LocalizationProvider />.");
+ }
+
+ let source;
+
+ if (Array.isArray(children)) {
+ if (children.length > 1) {
+ throw new Error("Expected to receive a single React element to localize.");
+ } // If it's an array with zero or one element, we can directly get the first one.
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+
+
+ source = children[0];
+ } else {
+ source = children !== null && children !== void 0 ? children : null;
+ } // Check if the component to render is a valid element -- if not, then
+ // it's either null or a simple fallback string. No need to localize the
+ // attributes or replace.
+
+
+ if (! /*#__PURE__*/(0,external_React_namespaceObject.isValidElement)(source)) {
+ const fallback = typeof source === "string" ? source : undefined;
+ const string = l10n.getString(id, vars, fallback);
+ return /*#__PURE__*/external_React_namespaceObject.createElement(external_React_namespaceObject.Fragment, null, string);
+ }
+
+ return l10n.getElement(source, id, {
+ attrs,
+ vars,
+ elems
+ });
+}
+/* harmony default export */ const localized = (Localized);
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/use_localization.js
+
+
+const useLocalization = () => {
+ const l10n = (0,external_React_namespaceObject.useContext)(FluentContext);
+
+ if (!l10n) {
+ throw new Error("useLocalization was used without wrapping it in a " + "<LocalizationProvider />.");
+ }
+
+ return {
+ l10n
+ };
+};
+;// CONCATENATED MODULE: ./node_modules/@fluent/react/esm/index.js
+/**
+ * @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.
+ *
+ * Consult the documentation of the `LocalizationProvider` and the `Localized`
+ * components for more information.
+ *
+ * @example
+ * ```jsx
+ * <LocalizationProvider l10n={…}>
+ * <Localized id="hello-world">
+ * <p>{'Hello, world!'}</p>
+ * </Localized>
+ * </LocalizationProvider>
+ * ```
+ */
+
+
+
+
+
+;// CONCATENATED MODULE: ./content-src/lib/constants.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/. */
+const IS_NEWTAB = __webpack_require__.g.document && __webpack_require__.g.document.documentURI === "about:newtab";
+const NEWTAB_DARK_THEME = {
+ ntp_background: {
+ r: 42,
+ g: 42,
+ b: 46,
+ a: 1
+ },
+ ntp_card_background: {
+ r: 66,
+ g: 65,
+ b: 77,
+ 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
+ }
+};
+;// CONCATENATED MODULE: external "ReactDOM"
+const external_ReactDOM_namespaceObject = ReactDOM;
+var external_ReactDOM_default = /*#__PURE__*/__webpack_require__.n(external_ReactDOM_namespaceObject);
+;// 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 /*#__PURE__*/external_React_default().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 */ const ConditionalWrapper_ConditionalWrapper = (ConditionalWrapper);
+;// 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) {
+ // eslint-disable-next-line no-console
+ console.warn(`The protocol ${protocol} is not allowed for template URLs.`);
+ }
+
+ return isAllowed ? url : "";
+}
+;// CONCATENATED MODULE: ./content-src/asrouter/components/RichText/RichText.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/. */
+
+
+
+ // Elements allowed in snippet content
+
+const ALLOWED_TAGS = {
+ b: /*#__PURE__*/external_React_default().createElement("b", null),
+ i: /*#__PURE__*/external_React_default().createElement("i", null),
+ u: /*#__PURE__*/external_React_default().createElement("u", null),
+ strong: /*#__PURE__*/external_React_default().createElement("strong", null),
+ em: /*#__PURE__*/external_React_default().createElement("em", null),
+ br: /*#__PURE__*/external_React_default().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] =
+ /*#__PURE__*/
+ // 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().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,
+ rel: "noreferrer",
+ onClick: sendClick
+ });
+ return acc;
+ }, {});
+ }
+
+ return null;
+}
+/**
+ * Message wrapper used to sanitize markup and render HTML.
+ */
+
+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 /*#__PURE__*/external_React_default().createElement(Localized, {
+ id: props.localization_id,
+ elems: { ...ALLOWED_TAGS,
+ ...props.customElements,
+ ...convertLinks(props.links, props.sendClick, props.doNotAutoBlock, props.openNewWindow)
+ }
+ }, /*#__PURE__*/external_React_default().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 extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "footer"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "footer-content"
+ }, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: containerClassName,
+ style: this.props.textStyle
+ }, /*#__PURE__*/external_React_default().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 extends (external_React_default()).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 ? /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "titleIcon icon-light-theme",
+ style: {
+ backgroundImage: `url("${titleIconLight}")`
+ }
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "titleIcon icon-dark-theme",
+ style: {
+ backgroundImage: `url("${titleIconDark}")`
+ }
+ }));
+ }
+
+ renderButton() {
+ const {
+ props
+ } = this;
+
+ if (!this._shouldRenderButton()) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("a", {
+ href: url
+ }, children);
+ };
+ }
+
+ wrapSnippetContent(children) {
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-header"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(ConditionalWrapper_ConditionalWrapper, {
+ condition: sectionTitleURL,
+ wrap: this.wrapSectionHeader(sectionTitleURL)
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-light-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconLight}")`
+ }
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-dark-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconDark}")`
+ }
+ }), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "snippet-hover-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement(SnippetBase, SimpleSnippet_extends({}, props, {
+ className: className,
+ textStyle: this.props.textStyle
+ }), sectionHeader, /*#__PURE__*/external_React_default().createElement(ConditionalWrapper_ConditionalWrapper, {
+ condition: sectionHeader,
+ wrap: this.wrapSnippetContent
+ }, /*#__PURE__*/external_React_default().createElement("img", {
+ src: safeURI(props.content.icon) || DEFAULT_ICON_PATH,
+ className: "icon icon-light-theme",
+ alt: props.content.icon_alt_text || ICON_ALT_TEXT
+ }), /*#__PURE__*/external_React_default().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
+ }), /*#__PURE__*/external_React_default().createElement("div", null, this.renderTitle(), " ", /*#__PURE__*/external_React_default().createElement("p", {
+ className: "body"
+ }, this.renderText()), this.props.extraContent), /*#__PURE__*/external_React_default().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 EOYSnippetBase extends (external_React_default()).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 /*#__PURE__*/external_React_default().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) => /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, {
+ key: idx
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "radio",
+ name: "amount",
+ value: amount,
+ id: field,
+ defaultChecked: button_name === selected_button
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: field,
+ className: "donation-amount"
+ }, numberFormat.format(amount)));
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "monthly-checkbox-container"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ id: "monthly-checkbox",
+ type: "checkbox"
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: "monthly-checkbox"
+ }, this.props.content.monthly_checkbox_label_text)), /*#__PURE__*/external_React_default().createElement("input", {
+ type: "hidden",
+ name: "frequency",
+ value: "single"
+ }), /*#__PURE__*/external_React_default().createElement("input", {
+ type: "hidden",
+ name: "currency",
+ value: this.props.content.currency_code
+ }), /*#__PURE__*/external_React_default().createElement("input", {
+ type: "hidden",
+ name: "presets",
+ value: fieldNames.map(field => this.props.content[`donation_amount_${field}`])
+ }), /*#__PURE__*/external_React_default().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 = /*#__PURE__*/external_React_default().createElement("em", {
+ style: {
+ backgroundColor: this.props.content.highlight_color
+ }
+ });
+ return /*#__PURE__*/external_React_default().createElement(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 /*#__PURE__*/external_React_default().createElement(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 extends (external_React_default()).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.error(err);
+ }
+
+ 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 {
+ 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) => /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("p", {
+ className: "disclaimerText"
+ }, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("p", {
+ className: "privacyNotice"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "checkbox",
+ id: "id_privacy",
+ name: "privacy",
+ required: "required"
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: "id_privacy"
+ }, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement(SnippetBase, this.props, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "submissionStatus"
+ }, successTitle ? /*#__PURE__*/external_React_default().createElement("h2", {
+ className: "submitStatusTitle"
+ }, successTitle) : null, /*#__PURE__*/external_React_default().createElement("p", null, /*#__PURE__*/external_React_default().createElement(RichText, SubmitFormSnippet_extends({}, bodyText, {
+ localization_id: isSuccess ? "success_text" : "error_text"
+ })), isSuccess ? null : /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("a", {
+ href: url
+ }, children);
+ };
+ }
+
+ renderInput() {
+ const placholder = this.props.content.scene2_email_placeholder_text || this.props.content.scene2_input_placeholder;
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("form", {
+ action: this.props.form_action,
+ method: this.props.form_method,
+ onSubmit: this.handleSubmit,
+ ref: "form"
+ }, this.renderHiddenFormInputs(), /*#__PURE__*/external_React_default().createElement("div", null, this.renderInput(), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "scene2Icon"
+ }, /*#__PURE__*/external_React_default().createElement("img", {
+ src: safeURI(content.scene2_icon),
+ className: "icon-light-theme",
+ alt: content.scene2_icon_alt_text || SubmitFormSnippet_ICON_ALT_TEXT
+ }), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement(SnippetBase, SubmitFormSnippet_extends({}, this.props, {
+ className: containerClass,
+ footerDismiss: true
+ }), this.renderScene2Icon(), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "message"
+ }, /*#__PURE__*/external_React_default().createElement("p", null, content.scene2_title && /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "scene2Title"
+ }, content.scene2_title), " ", content.scene2_text && /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-header"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(ConditionalWrapper_ConditionalWrapper, {
+ wrap: this.wrapSectionHeader(sectionTitleURL),
+ condition: sectionTitleURL
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-light-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconLight}")`
+ }
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-dark-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconDark}")`
+ }
+ }), /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement(SnippetBase, SubmitFormSnippet_extends({}, this.props, {
+ className: containerClass // Don't show bottom dismiss button
+ ,
+ footerDismiss: false
+ }), this.renderSectionHeader(), this.renderScene2Icon(), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "message"
+ }, /*#__PURE__*/external_React_default().createElement("p", null, content.scene2_text && /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement(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 /*#__PURE__*/external_React_default().createElement(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 /*#__PURE__*/external_React_default().createElement(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 /*#__PURE__*/external_React_default().createElement(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 /*#__PURE__*/external_React_default().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 extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onButtonClick = this.onButtonClick.bind(this);
+ }
+
+ renderText() {
+ const {
+ props
+ } = this;
+ return props.content.text ? /*#__PURE__*/external_React_default().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 ? /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "title title-inline"
+ }, title, /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: containerName
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "snippet-hover-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement(SnippetBase, SimpleBelowSearchSnippet_extends({}, props, {
+ className: className,
+ textStyle: this.props.textStyle
+ }), /*#__PURE__*/external_React_default().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
+ }), /*#__PURE__*/external_React_default().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
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "textContainer"
+ }, this.renderTitle(), /*#__PURE__*/external_React_default().createElement("p", {
+ className: "body"
+ }, this.renderText()), this.props.extraContent), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "buttonContainer"
+ }, this.renderButton()))));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/asrouter/templates/template-manifest.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/. */
+
+
+
+
+
+ // Key names matching schema name of templates
+
+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
+};
+;// CONCATENATED MODULE: ./content-src/asrouter/asrouter-content.jsx
+function asrouter_content_extends() { asrouter_content_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 asrouter_content_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 (external_React_default()).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);
+ }
+
+ 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);
+ }
+ } catch (error) {
+ console.error(error);
+ }
+
+ 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: 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) {
+ 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,
+ campaign: this.state.message.campaign
+ });
+ }
+
+ onBlockById(id, options) {
+ return ASRouterUtils.blockById(id, options).then(clearAll => {
+ if (clearAll) {
+ this.setState({
+ message: {}
+ });
+ }
+ });
+ }
+
+ onDismiss() {
+ this.clearMessage(this.state.message.id);
+ } // Blocking a snippet by id blocks the entire campaign
+ // so when clearing we use the two values interchangeably
+
+
+ clearMessage(idOrCampaign) {
+ if (idOrCampaign === this.state.message.id || idOrCampaign === this.state.message.campaign) {
+ 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: actionTypes.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") {
+ __webpack_require__.g.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, prevState) {
+ if (prevProps.adminContent && JSON.stringify(prevProps.adminContent) !== JSON.stringify(this.props.adminContent)) {
+ this.updateContent();
+ }
+
+ if (prevState.message.id !== this.state.message.id) {
+ const main = __webpack_require__.g.window.document.querySelector("main");
+
+ if (main) {
+ if (this.state.message.id) {
+ main.classList.add("has-snippet");
+ } else {
+ main.classList.remove("has-snippet");
+ }
+ }
+ }
+ }
+
+ 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
+ } = message;
+ return /*#__PURE__*/external_React_default().createElement(ImpressionsWrapper, {
+ id: "NEWTAB_FOOTER_BAR",
+ message: this.state.message,
+ sendImpression: this.sendImpression,
+ shouldSendImpressionOnUpdate: shouldSendImpressionOnUpdate // This helps with testing
+ ,
+ document: this.props.document
+ }, /*#__PURE__*/external_React_default().createElement(LocalizationProvider, {
+ l10n: new ReactLocalization(generateBundles(content))
+ }, /*#__PURE__*/external_React_default().createElement(SnippetComponent, asrouter_content_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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "snippets-preview-banner"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), /*#__PURE__*/external_React_default().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 ?
+ /*#__PURE__*/
+ // Render special below search snippets in place;
+ external_React_default().createElement("div", {
+ className: "below-search-snippet-wrapper"
+ }, this.renderSnippets()) :
+ /*#__PURE__*/
+ // For regular snippets etc. we should render everything in our footer
+ // container.
+ external_ReactDOM_default().createPortal( /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, this.renderPreviewBanner(), this.renderSnippets()), this.footerPortal);
+ }
+
+}
+ASRouterUISurface.defaultProps = {
+ document: __webpack_require__.g.document
+};
+;// CONCATENATED MODULE: ./content-src/components/ConfirmDialog/ConfirmDialog.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/. */
+
+
+
+/**
+ * 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 (external_React_default()).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(actionCreators.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 /*#__PURE__*/external_React_default().createElement("span", null, message_body.map(msg => /*#__PURE__*/external_React_default().createElement("p", {
+ key: msg,
+ "data-l10n-id": msg
+ })));
+ }
+
+ render() {
+ if (!this.props.visible) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "confirmation-dialog"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "modal-overlay",
+ onClick: this._handleCancelBtn,
+ role: "presentation"
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "modal"
+ }, /*#__PURE__*/external_React_default().createElement("section", {
+ className: "modal-message"
+ }, this.props.data.icon && /*#__PURE__*/external_React_default().createElement("span", {
+ className: `icon icon-spacer icon-${this.props.data.icon}`
+ }), this._renderModalMessage()), /*#__PURE__*/external_React_default().createElement("section", {
+ className: "actions"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ onClick: this._handleCancelBtn,
+ "data-l10n-id": this.props.data.cancel_button_string_id
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "done",
+ onClick: this._handleConfirmBtn,
+ "data-l10n-id": this.props.data.confirm_button_string_id
+ }))));
+ }
+
+}
+const ConfirmDialog = (0,external_ReactRedux_namespaceObject.connect)(state => state.Dialog)(_ConfirmDialog);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSImage/DSImage.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 PLACEHOLDER_IMAGE_DATA_ARRAY = [{
+ rotation: "0deg",
+ offsetx: "20px",
+ offsety: "8px",
+ scale: "45%"
+}, {
+ rotation: "54deg",
+ offsetx: "-26px",
+ offsety: "62px",
+ scale: "55%"
+}, {
+ rotation: "-30deg",
+ offsetx: "78px",
+ offsety: "30px",
+ scale: "68%"
+}, {
+ rotation: "-22deg",
+ offsetx: "0",
+ offsety: "92px",
+ scale: "60%"
+}, {
+ rotation: "-65deg",
+ offsetx: "66px",
+ offsety: "28px",
+ scale: "60%"
+}, {
+ rotation: "22deg",
+ offsetx: "-35px",
+ offsety: "62px",
+ scale: "52%"
+}, {
+ rotation: "-25deg",
+ offsetx: "86px",
+ offsety: "-15px",
+ scale: "68%"
+}];
+const PLACEHOLDER_IMAGE_COLORS_ARRAY = "#0090ED #FF4F5F #2AC3A2 #FF7139 #A172FF #FFA437 #FF2A8A".split(" ");
+
+function generateIndex({
+ keyCode,
+ max
+}) {
+ if (!keyCode) {
+ // Just grab a random index if we cannot generate an index from a key.
+ return Math.floor(Math.random() * max);
+ }
+
+ const hashStr = str => {
+ let hash = 0;
+
+ for (let i = 0; i < str.length; i++) {
+ let charCode = str.charCodeAt(i);
+ hash += charCode;
+ }
+
+ return hash;
+ };
+
+ const hash = hashStr(keyCode);
+ return hash % max;
+}
+
+function PlaceholderImage({
+ urlKey,
+ titleKey
+}) {
+ const dataIndex = generateIndex({
+ keyCode: urlKey,
+ max: PLACEHOLDER_IMAGE_DATA_ARRAY.length
+ });
+ const colorIndex = generateIndex({
+ keyCode: titleKey,
+ max: PLACEHOLDER_IMAGE_COLORS_ARRAY.length
+ });
+ const {
+ rotation,
+ offsetx,
+ offsety,
+ scale
+ } = PLACEHOLDER_IMAGE_DATA_ARRAY[dataIndex];
+ const color = PLACEHOLDER_IMAGE_COLORS_ARRAY[colorIndex];
+ const style = {
+ "--placeholderBackgroundColor": color,
+ "--placeholderBackgroundRotation": rotation,
+ "--placeholderBackgroundOffsetx": offsetx,
+ "--placeholderBackgroundOffsety": offsety,
+ "--placeholderBackgroundScale": scale
+ };
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ style: style,
+ className: "placeholder-image"
+ });
+}
+class DSImage extends (external_React_default()).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 = /*#__PURE__*/external_React_default().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.props.source && !this.state.nonOptimizedImageFailed) {
+ img = /*#__PURE__*/external_React_default().createElement("img", {
+ loading: "lazy",
+ alt: this.props.alt_text,
+ crossOrigin: "anonymous",
+ onLoad: this.onLoad,
+ onError: this.onNonOptimizedImageError,
+ src: this.props.source
+ });
+ } else {
+ // We consider a failed to load img or source without an image as loaded.
+ classNames = `${classNames} loaded`; // Remove the img element if we have no source. Render a placeholder instead.
+ // This only happens for recent saves without a source.
+
+ if (this.props.isRecentSave && !this.props.rawSource && !this.props.source) {
+ img = /*#__PURE__*/external_React_default().createElement(PlaceholderImage, {
+ urlKey: this.props.url,
+ titleKey: this.props.title
+ });
+ } else {
+ img = /*#__PURE__*/external_React_default().createElement("div", {
+ className: "broken-image"
+ });
+ }
+ }
+ }
+
+ return /*#__PURE__*/external_React_default().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: []
+};
+;// CONCATENATED MODULE: ./content-src/components/ContextMenu/ContextMenu.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 ContextMenu extends (external_React_default()).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(() => {
+ __webpack_require__.g.addEventListener("click", this.hideContext);
+ }, 0);
+ }
+
+ componentWillUnmount() {
+ __webpack_require__.g.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 (
+ /*#__PURE__*/
+ // eslint-disable-next-line jsx-a11y/interactive-supports-focus
+ external_React_default().createElement("span", {
+ className: "context-menu"
+ }, /*#__PURE__*/external_React_default().createElement("ul", {
+ role: "menu",
+ onClick: this.onClick,
+ onKeyDown: this.onClick,
+ className: "context-menu-list"
+ }, this.props.options.map((option, i) => option.type === "separator" ? /*#__PURE__*/external_React_default().createElement("li", {
+ key: i,
+ className: "separator",
+ role: "separator"
+ }) : option.type !== "empty" && /*#__PURE__*/external_React_default().createElement(ContextMenuItem, {
+ key: i,
+ option: option,
+ hideContext: this.hideContext,
+ keyboardAccess: this.props.keyboardAccess
+ }))))
+ );
+ }
+
+}
+class _ContextMenuItem extends (external_React_default()).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;
+ return /*#__PURE__*/external_React_default().createElement("li", {
+ role: "presentation",
+ className: "context-menu-item"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ className: option.disabled ? "disabled" : "",
+ role: "menuitem",
+ onClick: this.onClick,
+ onKeyDown: this.onKeyDown,
+ onKeyUp: this.onKeyUp,
+ ref: option.first ? this.focusFirst : null,
+ "aria-haspopup": option.id === "newtab-menu-edit-topsites" ? "dialog" : null
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": option.string_id || option.id
+ })));
+ }
+
+}
+const ContextMenuItem = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Prefs: state.Prefs
+}))(_ContextMenuItem);
+;// CONCATENATED MODULE: ./content-src/lib/link-menu-options.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/. */
+
+
+const _OpenInPrivateWindow = site => ({
+ id: "newtab-menu-open-new-private-window",
+ icon: "new-window-private",
+ action: actionCreators.OnlyToMain({
+ type: 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: actionTypes.SHOW_PRIVACY_INFO
+ },
+ userEvent: "SHOW_PRIVACY_INFO"
+ }),
+ AboutSponsored: site => ({
+ id: "newtab-menu-show-privacy-info",
+ icon: "info",
+ action: actionCreators.AlsoToMain({
+ type: actionTypes.ABOUT_SPONSORED_TOP_SITES
+ }),
+ userEvent: "TOPSITE_SPONSOR_INFO"
+ }),
+ RemoveBookmark: site => ({
+ id: "newtab-menu-remove-bookmark",
+ icon: "bookmark-added",
+ action: actionCreators.AlsoToMain({
+ type: actionTypes.DELETE_BOOKMARK_BY_ID,
+ data: site.bookmarkGuid
+ }),
+ userEvent: "BOOKMARK_DELETE"
+ }),
+ AddBookmark: site => ({
+ id: "newtab-menu-bookmark",
+ icon: "bookmark-hollow",
+ action: actionCreators.AlsoToMain({
+ type: 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: actionCreators.AlsoToMain({
+ type: actionTypes.OPEN_NEW_WINDOW,
+ data: {
+ referrer: site.referrer,
+ typedBonus: site.typedBonus,
+ url: site.url,
+ sponsored_tile_id: site.sponsored_tile_id
+ }
+ }),
+ 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: actionCreators.AlsoToMain({
+ type: 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,
+ // used by PlacesFeed and TopSitesFeed for sponsored top sites blocking.
+ isSponsoredTopSite: site.sponsored_position,
+ ...(site.flight_id ? {
+ flight_id: site.flight_id
+ } : {})
+ }))
+ }),
+ impression: 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: actionCreators.WebExtEvent(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: actionTypes.DIALOG_OPEN,
+ data: {
+ onConfirm: [actionCreators.AlsoToMain({
+ type: actionTypes.DELETE_HISTORY_URL,
+ data: {
+ url: site.url,
+ pocket_id: site.pocket_id,
+ forceBlock: site.bookmarkGuid
+ }
+ }), 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: actionCreators.OnlyToMain({
+ type: actionTypes.SHOW_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ OpenFile: site => ({
+ id: "newtab-menu-open-file",
+ icon: "open-file",
+ action: actionCreators.OnlyToMain({
+ type: actionTypes.OPEN_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ CopyDownloadLink: site => ({
+ id: "newtab-menu-copy-download-link",
+ icon: "copy",
+ action: actionCreators.OnlyToMain({
+ type: actionTypes.COPY_DOWNLOAD_LINK,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ GoToDownloadPage: site => ({
+ id: "newtab-menu-go-to-download-page",
+ icon: "download",
+ action: actionCreators.OnlyToMain({
+ type: actionTypes.OPEN_LINK,
+ data: {
+ url: site.referrer
+ }
+ }),
+ disabled: !site.referrer
+ }),
+ RemoveDownload: site => ({
+ id: "newtab-menu-remove-download",
+ icon: "delete",
+ action: actionCreators.OnlyToMain({
+ type: actionTypes.REMOVE_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ PinTopSite: (site, index) => ({
+ id: "newtab-menu-pin",
+ icon: "pin",
+ action: actionCreators.AlsoToMain({
+ type: actionTypes.TOP_SITES_PIN,
+ data: {
+ site,
+ index
+ }
+ }),
+ userEvent: "PIN"
+ }),
+ UnpinTopSite: site => ({
+ id: "newtab-menu-unpin",
+ icon: "unpin",
+ action: actionCreators.AlsoToMain({
+ type: actionTypes.TOP_SITES_UNPIN,
+ data: {
+ site: {
+ url: site.url
+ }
+ }
+ }),
+ userEvent: "UNPIN"
+ }),
+ SaveToPocket: (site, index, eventSource = "CARDGRID") => ({
+ id: "newtab-menu-save-to-pocket",
+ icon: "pocket-save",
+ action: actionCreators.AlsoToMain({
+ type: actionTypes.SAVE_TO_POCKET,
+ data: {
+ site: {
+ url: site.url,
+ title: site.title
+ }
+ }
+ }),
+ impression: 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: actionCreators.AlsoToMain({
+ type: 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: actionCreators.AlsoToMain({
+ type: 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: 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, source) => site.pocket_id ? LinkMenuOptions.DeleteFromPocket(site) : LinkMenuOptions.SaveToPocket(site, index, source),
+ CheckBookmarkOrArchive: site => site.pocket_id ? LinkMenuOptions.ArchiveFromPocket(site) : LinkMenuOptions.CheckBookmark(site),
+ CheckArchiveFromPocket: site => site.pocket_id ? LinkMenuOptions.ArchiveFromPocket(site) : LinkMenuOptions.EmptyItem(),
+ CheckDeleteFromPocket: site => site.pocket_id ? LinkMenuOptions.DeleteFromPocket(site) : LinkMenuOptions.EmptyItem(),
+ OpenInPrivateWindow: (site, index, eventSource, isEnabled) => isEnabled ? _OpenInPrivateWindow(site) : LinkMenuOptions.EmptyItem()
+};
+;// CONCATENATED MODULE: ./content-src/components/LinkMenu/LinkMenu.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 DEFAULT_SITE_MENU_OPTIONS = ["CheckPinTopSite", "EditTopSite", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl"];
+class _LinkMenu extends (external_React_default()).PureComponent {
+ getOptions() {
+ const {
+ props
+ } = this;
+ const {
+ site,
+ index,
+ source,
+ isPrivateBrowsingEnabled,
+ siteInfo,
+ platform,
+ userEvent = actionCreators.UserEvent
+ } = 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: eventName
+ } = 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 (eventName) {
+ const userEventData = Object.assign({
+ event: eventName,
+ source,
+ action_position: index,
+ value: {
+ card_type: site.flight_id ? "spoc" : "organic"
+ }
+ }, siteInfo);
+ props.dispatch(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 /*#__PURE__*/external_React_default().createElement(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 = (0,external_ReactRedux_namespaceObject.connect)(getState)(_LinkMenu);
+;// CONCATENATED MODULE: ./content-src/components/ContextMenu/ContextMenuButton.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 ContextMenuButton extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().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 ? /*#__PURE__*/external_React_default().cloneElement(children, {
+ keyboardAccess: contextMenuKeyboard,
+ onUpdate: this.onUpdate
+ }) : null);
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.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 DSLinkMenu extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ index,
+ dispatch
+ } = this.props;
+ let pocketMenuOptions = [];
+ let TOP_STORIES_CONTEXT_MENU_OPTIONS = ["OpenInNewWindow", "OpenInPrivateWindow"];
+
+ if (!this.props.isRecentSave) {
+ if (this.props.pocket_button_enabled) {
+ pocketMenuOptions = this.props.saveToPocketCard ? ["CheckDeleteFromPocket"] : ["CheckSavedToPocket"];
+ }
+
+ TOP_STORIES_CONTEXT_MENU_OPTIONS = ["CheckBookmark", "CheckArchiveFromPocket", ...pocketMenuOptions, "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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "context-menu-position-container"
+ }, /*#__PURE__*/external_React_default().createElement(ContextMenuButton, {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.props.onMenuUpdate
+ }, /*#__PURE__*/external_React_default().createElement(LinkMenu, {
+ dispatch: dispatch,
+ index: index,
+ source: type.toUpperCase(),
+ onShow: this.props.onMenuShow,
+ options: TOP_STORIES_CONTEXT_MENU_OPTIONS,
+ shouldSendImpressionStats: true,
+ userEvent: actionCreators.DiscoveryStreamUserEvent,
+ 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
+ }
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/TopSites/TopSitesConstants.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/. */
+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 = ["OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", "ShowPrivacyInfo"];
+const TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS = ["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
+
+const MIN_SMALL_FAVICON_SIZE = 16;
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.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 ImpressionStats_VISIBLE = "visible";
+const ImpressionStats_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_ImpressionStats extends (external_React_default()).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(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: {
+ flightId: this.props.flightId
+ }
+ })); // Record sponsored topsites impressions if the source is `TOP_SITES_SOURCE`.
+
+ if (this.props.source === TOP_SITES_SOURCE) {
+ for (const card of cards) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "impression",
+ tile_id: card.id,
+ source: "newtab",
+ advertiser: card.advertiser,
+ // Keep the 0-based position, can be adjusted by the telemetry
+ // sender if necessary.
+ position: card.pos
+ }
+ }));
+ }
+ }
+ }
+
+ if (this._needsImpressionStats(cards)) {
+ props.dispatch(actionCreators.DiscoveryStreamImpressionStats({
+ source: props.source.toUpperCase(),
+ window_inner_width: window.innerWidth,
+ window_inner_height: window.innerHeight,
+ tiles: cards.map(link => ({
+ id: link.id,
+ pos: link.pos,
+ type: this.props.flightId ? "spoc" : "organic",
+ ...(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(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 === ImpressionStats_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(ImpressionStats_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === ImpressionStats_VISIBLE) {
+ // Send the loaded content ping once the page is visible.
+ this._dispatchLoadedContent();
+
+ this.setImpressionObserver();
+ props.document.removeEventListener(ImpressionStats_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ props.document.addEventListener(ImpressionStats_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(ImpressionStats_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ ref: "impression",
+ className: "impression-observer"
+ }, this.props.children);
+ }
+
+}
+ImpressionStats_ImpressionStats.defaultProps = {
+ IntersectionObserver: __webpack_require__.g.IntersectionObserver,
+ document: __webpack_require__.g.document,
+ rows: [],
+ source: ""
+};
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.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 SafeAnchor extends (external_React_default()).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(actionCreators.OnlyToMain({
+ type: 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 /*#__PURE__*/external_React_default().createElement("a", {
+ href: this.safeURI(url),
+ className: className,
+ onClick: this.onClick
+ }, this.props.children);
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/Card/types.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/. */
+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"
+ }
+};
+;// CONCATENATED MODULE: external "ReactTransitionGroup"
+const external_ReactTransitionGroup_namespaceObject = ReactTransitionGroup;
+;// CONCATENATED MODULE: ./content-src/components/FluentOrText/FluentOrText.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/. */
+
+/**
+ * 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 (external_React_default()).PureComponent {
+ render() {
+ // Ensure we have a single child to attach attributes
+ const {
+ children,
+ message
+ } = this.props;
+ const child = children ? external_React_default().Children.only(children) : /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().cloneElement(child, extraProps, grandChildren);
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.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/. */
+
+
+
+ // Animation time is mirrored in DSContextFooter.scss
+
+const ANIMATION_DURATION = 3000;
+const DSMessageLabel = props => {
+ const {
+ context,
+ context_type
+ } = props;
+ const {
+ icon,
+ fluentID
+ } = cardContextTypes[context_type] || {};
+
+ if (!context && context_type) {
+ return /*#__PURE__*/external_React_default().createElement(external_ReactTransitionGroup_namespaceObject.TransitionGroup, {
+ component: null
+ }, /*#__PURE__*/external_React_default().createElement(external_ReactTransitionGroup_namespaceObject.CSSTransition, {
+ key: fluentID,
+ timeout: ANIMATION_DURATION,
+ classNames: "story-animate"
+ }, /*#__PURE__*/external_React_default().createElement(StatusMessage, {
+ icon: icon,
+ fluentID: fluentID
+ })));
+ }
+
+ return null;
+};
+const StatusMessage = ({
+ icon,
+ fluentID
+}) => /*#__PURE__*/external_React_default().createElement("div", {
+ className: "status-message"
+}, /*#__PURE__*/external_React_default().createElement("span", {
+ "aria-haspopup": "true",
+ className: `story-badge-icon icon icon-${icon}`
+}), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "story-context-label",
+ "data-l10n-id": fluentID
+}));
+const SponsorLabel = ({
+ sponsored_by_override,
+ sponsor,
+ context,
+ newSponsoredLabel
+}) => {
+ const classList = `story-sponsored-label ${newSponsoredLabel || ""} clamp`; // If override is not false or an empty string.
+
+ if (sponsored_by_override) {
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("p", {
+ className: classList
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: {
+ id: `newtab-label-sponsored-by`,
+ values: {
+ sponsor
+ }
+ }
+ }));
+ } else if (context) {
+ return /*#__PURE__*/external_React_default().createElement("p", {
+ className: classList
+ }, context);
+ }
+
+ return null;
+};
+class DSContextFooter extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ context,
+ context_type,
+ sponsor,
+ sponsored_by_override
+ } = this.props;
+ const sponsorLabel = SponsorLabel({
+ sponsored_by_override,
+ sponsor,
+ context
+ });
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type
+ });
+
+ if (sponsorLabel || dsMessageLabel) {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "story-footer"
+ }, sponsorLabel, dsMessageLabel);
+ }
+
+ return null;
+ }
+
+}
+const DSMessageFooter = props => {
+ const {
+ context,
+ context_type,
+ saveToPocketCard
+ } = props;
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type
+ }); // This case is specific and already displayed to the user elsewhere.
+
+ if (!dsMessageLabel || saveToPocketCard && context_type === "pocket") {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "story-footer"
+ }, dsMessageLabel);
+};
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSCard/DSCard.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 READING_WPM = 220;
+/**
+ * READ TIME FROM WORD COUNT
+ * @param {int} wordCount number of words in an article
+ * @returns {int} number of words per minute in minutes
+ */
+
+function readTimeFromWordCount(wordCount) {
+ if (!wordCount) return false;
+ return Math.ceil(parseInt(wordCount, 10) / READING_WPM);
+}
+const DSSource = ({
+ source,
+ timeToRead,
+ newSponsoredLabel,
+ context,
+ sponsor,
+ sponsored_by_override
+}) => {
+ // First try to display sponsored label or time to read here.
+ if (newSponsoredLabel) {
+ // If we can display something for spocs, do so.
+ if (sponsored_by_override || sponsor || context) {
+ return /*#__PURE__*/external_React_default().createElement(SponsorLabel, {
+ context: context,
+ sponsor: sponsor,
+ sponsored_by_override: sponsored_by_override,
+ newSponsoredLabel: "new-sponsored-label"
+ });
+ }
+ } // If we are not a spoc, and can display a time to read value.
+
+
+ if (source && timeToRead) {
+ return /*#__PURE__*/external_React_default().createElement("p", {
+ className: "source clamp time-to-read"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: {
+ id: `newtab-label-source-read-time`,
+ values: {
+ source,
+ timeToRead
+ }
+ }
+ }));
+ } // Otherwise display a default source.
+
+
+ return /*#__PURE__*/external_React_default().createElement("p", {
+ className: "source clamp"
+ }, source);
+};
+const DefaultMeta = ({
+ source,
+ title,
+ excerpt,
+ timeToRead,
+ newSponsoredLabel,
+ context,
+ context_type,
+ sponsor,
+ sponsored_by_override,
+ saveToPocketCard,
+ isRecentSave
+}) => /*#__PURE__*/external_React_default().createElement("div", {
+ className: "meta"
+}, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "info-wrap"
+}, /*#__PURE__*/external_React_default().createElement(DSSource, {
+ source: source,
+ timeToRead: timeToRead,
+ newSponsoredLabel: newSponsoredLabel,
+ context: context,
+ sponsor: sponsor,
+ sponsored_by_override: sponsored_by_override
+}), /*#__PURE__*/external_React_default().createElement("header", {
+ title: title,
+ className: "title clamp"
+}, title), excerpt && /*#__PURE__*/external_React_default().createElement("p", {
+ className: "excerpt clamp"
+}, excerpt)), !newSponsoredLabel && /*#__PURE__*/external_React_default().createElement(DSContextFooter, {
+ context_type: context_type,
+ context: context,
+ sponsor: sponsor,
+ sponsored_by_override: sponsored_by_override
+}), newSponsoredLabel && /*#__PURE__*/external_React_default().createElement(DSMessageFooter, {
+ context_type: context_type,
+ context: null,
+ saveToPocketCard: saveToPocketCard
+}));
+class _DSCard extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onSaveClick = this.onSaveClick.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+
+ this.setContextMenuButtonHostRef = element => {
+ this.contextMenuButtonHostElement = element;
+ };
+
+ 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(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: this.props.type.toUpperCase(),
+ action_position: this.props.pos,
+ value: {
+ card_type: this.props.flightId ? "spoc" : "organic"
+ }
+ }));
+ this.props.dispatch(actionCreators.ImpressionStats({
+ source: this.props.type.toUpperCase(),
+ click: 0,
+ window_inner_width: this.props.windowObj.innerWidth,
+ window_inner_height: this.props.windowObj.innerHeight,
+ tiles: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click ? {
+ shim: this.props.shim.click
+ } : {}),
+ type: this.props.flightId ? "spoc" : "organic"
+ }]
+ }));
+ }
+ }
+
+ onSaveClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(actionCreators.AlsoToMain({
+ type: actionTypes.SAVE_TO_POCKET,
+ data: {
+ site: {
+ url: this.props.url,
+ title: this.props.title
+ }
+ }
+ }));
+ this.props.dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ source: "CARDGRID_HOVER",
+ action_position: this.props.pos,
+ value: {
+ card_type: this.props.flightId ? "spoc" : "organic"
+ }
+ }));
+ this.props.dispatch(actionCreators.ImpressionStats({
+ source: "CARDGRID_HOVER",
+ pocket: 0,
+ tiles: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.save ? {
+ shim: this.props.shim.save
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ onMenuUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ const dsLinkMenuHostDiv = this.contextMenuButtonHostElement;
+
+ if (dsLinkMenuHostDiv) {
+ dsLinkMenuHostDiv.classList.remove("active", "last-item");
+ }
+ }
+ }
+
+ async onMenuShow() {
+ const dsLinkMenuHostDiv = this.contextMenuButtonHostElement;
+
+ if (dsLinkMenuHostDiv) {
+ // Force translation so we can be sure it's ready before measuring.
+ await this.props.windowObj.document.l10n.translateFragment(dsLinkMenuHostDiv);
+
+ if (this.props.windowObj.scrollMaxX > 0) {
+ dsLinkMenuHostDiv.classList.add("last-item");
+ }
+
+ dsLinkMenuHostDiv.classList.add("active");
+ }
+ }
+
+ 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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-card placeholder",
+ ref: this.setPlaceholderRef
+ });
+ }
+
+ const {
+ isRecentSave,
+ DiscoveryStream,
+ saveToPocketCard
+ } = this.props;
+ let {
+ source
+ } = this.props;
+
+ if (!source) {
+ try {
+ source = new URL(this.props.url).hostname;
+ } catch (e) {}
+ }
+
+ const {
+ pocketButtonEnabled,
+ hideDescriptions,
+ compactImages,
+ imageGradient,
+ newSponsoredLabel,
+ titleLines = 3,
+ descLines = 3,
+ readTime: displayReadTime
+ } = DiscoveryStream;
+ const excerpt = !hideDescriptions ? this.props.excerpt : "";
+ let timeToRead;
+
+ if (displayReadTime) {
+ timeToRead = this.props.time_to_read || readTimeFromWordCount(this.props.word_count);
+ }
+
+ const compactImagesClassName = compactImages ? `ds-card-compact-image` : ``;
+ const imageGradientClassName = imageGradient ? `ds-card-image-gradient` : ``;
+ const titleLinesName = `ds-card-title-lines-${titleLines}`;
+ const descLinesClassName = `ds-card-desc-lines-${descLines}`;
+
+ let stpButton = () => {
+ return /*#__PURE__*/external_React_default().createElement("button", {
+ className: "card-stp-button",
+ onClick: this.onSaveClick
+ }, this.props.context_type === "pocket" ? /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "story-badge-icon icon icon-pocket"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-saved"
+ })) : /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "story-badge-icon icon icon-pocket-save"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-save"
+ })));
+ };
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: `ds-card ${compactImagesClassName} ${imageGradientClassName} ${titleLinesName} ${descLinesClassName}`,
+ ref: this.setContextMenuButtonHostRef
+ }, /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "ds-card-link",
+ dispatch: this.props.dispatch,
+ onLinkClick: !this.props.placeholder ? this.onLinkClick : undefined,
+ url: this.props.url
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "img-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement(DSImage, {
+ extraClassNames: "img",
+ source: this.props.image_src,
+ rawSource: this.props.raw_image_src,
+ sizes: this.dsImageSizes,
+ url: this.props.url,
+ title: this.props.title,
+ isRecentSave: isRecentSave
+ })), /*#__PURE__*/external_React_default().createElement(DefaultMeta, {
+ source: source,
+ title: this.props.title,
+ excerpt: excerpt,
+ newSponsoredLabel: newSponsoredLabel,
+ timeToRead: timeToRead,
+ context: this.props.context,
+ context_type: this.props.context_type,
+ sponsor: this.props.sponsor,
+ sponsored_by_override: this.props.sponsored_by_override,
+ saveToPocketCard: saveToPocketCard
+ }), /*#__PURE__*/external_React_default().createElement(ImpressionStats_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
+ })), saveToPocketCard && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-stp-button-hover-background"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-stp-button-position-wrapper"
+ }, !this.props.flightId && stpButton(), /*#__PURE__*/external_React_default().createElement(DSLinkMenu, {
+ id: this.props.id,
+ index: this.props.pos,
+ dispatch: this.props.dispatch,
+ url: this.props.url,
+ title: this.props.title,
+ source: 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,
+ onMenuUpdate: this.onMenuUpdate,
+ onMenuShow: this.onMenuShow,
+ saveToPocketCard: saveToPocketCard,
+ pocket_button_enabled: pocketButtonEnabled,
+ isRecentSave: isRecentSave
+ }))), !saveToPocketCard && /*#__PURE__*/external_React_default().createElement(DSLinkMenu, {
+ id: this.props.id,
+ index: this.props.pos,
+ dispatch: this.props.dispatch,
+ url: this.props.url,
+ title: this.props.title,
+ source: 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,
+ hostRef: this.contextMenuButtonHostRef,
+ onMenuUpdate: this.onMenuUpdate,
+ onMenuShow: this.onMenuShow,
+ pocket_button_enabled: pocketButtonEnabled,
+ isRecentSave: isRecentSave
+ }));
+ }
+
+}
+_DSCard.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+const DSCard = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ App: state.App,
+ DiscoveryStream: state.DiscoveryStream
+}))(_DSCard);
+const PlaceholderDSCard = props => /*#__PURE__*/external_React_default().createElement(DSCard, {
+ placeholder: true
+});
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.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 DSEmptyState extends (external_React_default()).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: 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(actionCreators.OnlyToMain({
+ type: actionTypes.DISCOVERY_STREAM_RETRY_FEED,
+ data: {
+ feed
+ }
+ }));
+ }
+ }
+
+ renderButton() {
+ if (this.props.status === "waiting" || this.state.waiting) {
+ return /*#__PURE__*/external_React_default().createElement("button", {
+ className: "try-again-button waiting",
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-loading"
+ });
+ }
+
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-timed-out"
+ }), this.renderButton());
+ }
+
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement("h2", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-header"
+ }), /*#__PURE__*/external_React_default().createElement("p", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-content"
+ }));
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-empty-state"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "empty-state-message"
+ }, this.renderState()));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.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 DSDismiss extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: className
+ }, this.props.children, /*#__PURE__*/external_React_default().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
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-dismiss"
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget.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/. */
+
+
+
+
+
+function _TopicsWidget(props) {
+ const {
+ id,
+ source,
+ position,
+ DiscoveryStream,
+ dispatch
+ } = props;
+ const {
+ utmCampaign,
+ utmContent,
+ utmSource
+ } = DiscoveryStream.experimentData;
+ let queryParams = `?utm_source=${utmSource}`;
+
+ if (utmCampaign && utmContent) {
+ queryParams += `&utm_content=${utmContent}&utm_campaign=${utmCampaign}`;
+ }
+
+ const topics = [{
+ label: "Technology",
+ name: "technology"
+ }, {
+ label: "Science",
+ name: "science"
+ }, {
+ label: "Self-Improvement",
+ name: "self-improvement"
+ }, {
+ label: "Travel",
+ name: "travel"
+ }, {
+ label: "Career",
+ name: "career"
+ }, {
+ label: "Entertainment",
+ name: "entertainment"
+ }, {
+ label: "Food",
+ name: "food"
+ }, {
+ label: "Health",
+ name: "health"
+ }, {
+ label: "Must-Reads",
+ name: "must-reads",
+ url: `https://getpocket.com/collections${queryParams}`
+ }];
+
+ function onLinkClick(topic, positionInCard) {
+ if (dispatch) {
+ dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source,
+ action_position: position,
+ value: {
+ card_type: "topics_widget",
+ topic,
+ ...(positionInCard || positionInCard === 0 ? {
+ position_in_card: positionInCard
+ } : {})
+ }
+ }));
+ dispatch(actionCreators.ImpressionStats({
+ source,
+ click: 0,
+ window_inner_width: props.windowObj.innerWidth,
+ window_inner_height: props.windowObj.innerHeight,
+ tiles: [{
+ id,
+ pos: position
+ }]
+ }));
+ }
+ }
+
+ function mapTopicItem(topic, index) {
+ return /*#__PURE__*/external_React_default().createElement("li", {
+ key: topic.name,
+ className: topic.overflow ? "ds-topics-widget-list-overflow-item" : ""
+ }, /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ url: topic.url || `https://getpocket.com/explore/${topic.name}${queryParams}`,
+ dispatch: dispatch,
+ onLinkClick: () => onLinkClick(topic.name, index)
+ }, topic.label));
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-topics-widget"
+ }, /*#__PURE__*/external_React_default().createElement("header", {
+ className: "ds-topics-widget-header"
+ }, "Popular Topics"), /*#__PURE__*/external_React_default().createElement("hr", null), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-topics-widget-list-container"
+ }, /*#__PURE__*/external_React_default().createElement("ul", null, topics.map(mapTopicItem))), /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "ds-topics-widget-button button primary",
+ url: `https://getpocket.com/${queryParams}`,
+ dispatch: dispatch,
+ onLinkClick: () => onLinkClick("more-topics")
+ }, "More Topics"), /*#__PURE__*/external_React_default().createElement(ImpressionStats_ImpressionStats, {
+ dispatch: dispatch,
+ rows: [{
+ id,
+ pos: position
+ }],
+ source: source
+ }));
+}
+_TopicsWidget.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+const TopicsWidget = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ DiscoveryStream: state.DiscoveryStream
+}))(_TopicsWidget);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.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 PREF_ONBOARDING_EXPERIENCE_DISMISSED = "discoverystream.onboardingExperience.dismissed";
+const CardGrid_INTERSECTION_RATIO = 0.5;
+const CardGrid_VISIBLE = "visible";
+const CardGrid_VISIBILITY_CHANGE_EVENT = "visibilitychange";
+const WIDGET_IDS = {
+ TOPICS: 1
+};
+function DSSubHeader({
+ children
+}) {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-top-bar ds-sub-header"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "section-title-container"
+ }, children));
+}
+function OnboardingExperience({
+ children,
+ dispatch,
+ windowObj = __webpack_require__.g
+}) {
+ const [dismissed, setDismissed] = (0,external_React_namespaceObject.useState)(false);
+ const [maxHeight, setMaxHeight] = (0,external_React_namespaceObject.useState)(null);
+ const heightElement = (0,external_React_namespaceObject.useRef)(null);
+ const onDismissClick = (0,external_React_namespaceObject.useCallback)(() => {
+ // We update this as state and redux.
+ // The state update is for this newtab,
+ // and the redux update is for other tabs, offscreen tabs, and future tabs.
+ // We need the state update for this tab to support the transition.
+ setDismissed(true);
+ dispatch(actionCreators.SetPref(PREF_ONBOARDING_EXPERIENCE_DISMISSED, true));
+ dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "BLOCK",
+ source: "POCKET_ONBOARDING"
+ }));
+ }, [dispatch]);
+ (0,external_React_namespaceObject.useEffect)(() => {
+ const resizeObserver = new windowObj.ResizeObserver(() => {
+ if (heightElement.current) {
+ setMaxHeight(heightElement.current.offsetHeight);
+ }
+ });
+ const options = {
+ threshold: CardGrid_INTERSECTION_RATIO
+ };
+ const intersectionObserver = new windowObj.IntersectionObserver(entries => {
+ if (entries.some(entry => entry.isIntersecting && entry.intersectionRatio >= CardGrid_INTERSECTION_RATIO)) {
+ dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "IMPRESSION",
+ source: "POCKET_ONBOARDING"
+ })); // Once we have observed an impression, we can stop for this instance of newtab.
+
+ intersectionObserver.unobserve(heightElement.current);
+ }
+ }, options);
+
+ const onVisibilityChange = () => {
+ intersectionObserver.observe(heightElement.current);
+ windowObj.document.removeEventListener(CardGrid_VISIBILITY_CHANGE_EVENT, onVisibilityChange);
+ };
+
+ if (heightElement.current) {
+ resizeObserver.observe(heightElement.current); // Check visibility or setup a visibility event to make
+ // sure we don't fire this for off screen pre loaded tabs.
+
+ if (windowObj.document.visibilityState === CardGrid_VISIBLE) {
+ intersectionObserver.observe(heightElement.current);
+ } else {
+ windowObj.document.addEventListener(CardGrid_VISIBILITY_CHANGE_EVENT, onVisibilityChange);
+ }
+
+ setMaxHeight(heightElement.current.offsetHeight);
+ } // Return unmount callback to clean up observers.
+
+
+ return () => {
+ resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.disconnect();
+ intersectionObserver === null || intersectionObserver === void 0 ? void 0 : intersectionObserver.disconnect();
+ windowObj.document.removeEventListener(CardGrid_VISIBILITY_CHANGE_EVENT, onVisibilityChange);
+ };
+ }, [dispatch, windowObj]);
+ const style = {};
+
+ if (dismissed) {
+ style.maxHeight = "0";
+ style.opacity = "0";
+ style.transition = "max-height 0.26s ease, opacity 0.26s ease";
+ } else if (maxHeight) {
+ style.maxHeight = `${maxHeight}px`;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ style: style
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-onboarding-ref",
+ ref: heightElement
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-onboarding-container"
+ }, /*#__PURE__*/external_React_default().createElement(DSDismiss, {
+ onDismissClick: onDismissClick,
+ extraClasses: `ds-onboarding`
+ }, /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("header", null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-pocket"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-onboarding-discover"
+ })), /*#__PURE__*/external_React_default().createElement("p", {
+ "data-l10n-id": "newtab-pocket-onboarding-cta"
+ })), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-onboarding-graphic"
+ })))));
+}
+function CardGrid_IntersectionObserver({
+ children,
+ windowObj = window,
+ onIntersecting
+}) {
+ const intersectionElement = (0,external_React_namespaceObject.useRef)(null);
+ (0,external_React_namespaceObject.useEffect)(() => {
+ let observer;
+
+ if (!observer && onIntersecting && intersectionElement.current) {
+ observer = new windowObj.IntersectionObserver(entries => {
+ const entry = entries.find(e => e.isIntersecting);
+
+ if (entry) {
+ // Stop observing since element has been seen
+ if (observer && intersectionElement.current) {
+ observer.unobserve(intersectionElement.current);
+ }
+
+ onIntersecting();
+ }
+ });
+ observer.observe(intersectionElement.current);
+ } // Cleanup
+
+
+ return () => {
+ var _observer;
+
+ return (_observer = observer) === null || _observer === void 0 ? void 0 : _observer.disconnect();
+ };
+ }, [windowObj, onIntersecting]);
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ ref: intersectionElement
+ }, children);
+}
+function RecentSavesContainer({
+ gridClassName = "",
+ dispatch,
+ windowObj = window,
+ items = 3,
+ source = "CARDGRID_RECENT_SAVES"
+}) {
+ const {
+ recentSavesData,
+ isUserLoggedIn,
+ experimentData: {
+ utmCampaign,
+ utmContent,
+ utmSource
+ }
+ } = (0,external_ReactRedux_namespaceObject.useSelector)(state => state.DiscoveryStream);
+ const [visible, setVisible] = (0,external_React_namespaceObject.useState)(false);
+ const onIntersecting = (0,external_React_namespaceObject.useCallback)(() => setVisible(true), []);
+ (0,external_React_namespaceObject.useEffect)(() => {
+ if (visible) {
+ dispatch(actionCreators.AlsoToMain({
+ type: actionTypes.DISCOVERY_STREAM_POCKET_STATE_INIT
+ }));
+ }
+ }, [visible, dispatch]); // The user has not yet scrolled to this section,
+ // so wait before potentially requesting Pocket data.
+
+ if (!visible) {
+ return /*#__PURE__*/external_React_default().createElement(CardGrid_IntersectionObserver, {
+ windowObj: windowObj,
+ onIntersecting: onIntersecting
+ });
+ } // Intersection observer has finished, but we're not yet logged in.
+
+
+ if (visible && !isUserLoggedIn) {
+ return null;
+ }
+
+ let queryParams = `?utm_source=${utmSource}`; // We really only need to add these params to urls we own.
+
+ if (utmCampaign && utmContent) {
+ queryParams += `&utm_content=${utmContent}&utm_campaign=${utmCampaign}`;
+ }
+
+ function renderCard(rec, index) {
+ const url = new URL(rec.url);
+ const urlSearchParams = new URLSearchParams(queryParams);
+
+ if (rec !== null && rec !== void 0 && rec.id && !url.href.match(/getpocket\.com\/read/)) {
+ url.href = `https://getpocket.com/read/${rec.id}`;
+ }
+
+ for (let [key, val] of urlSearchParams.entries()) {
+ url.searchParams.set(key, val);
+ }
+
+ return /*#__PURE__*/external_React_default().createElement(DSCard, {
+ key: `dscard-${(rec === null || rec === void 0 ? void 0 : rec.id) || index}`,
+ id: rec.id,
+ pos: index,
+ type: source,
+ image_src: rec.image_src,
+ raw_image_src: rec.raw_image_src,
+ word_count: rec.word_count,
+ time_to_read: rec.time_to_read,
+ title: rec.title,
+ excerpt: rec.excerpt,
+ url: url.href,
+ source: rec.domain,
+ isRecentSave: true,
+ dispatch: dispatch
+ });
+ }
+
+ function onMyListClicked() {
+ dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: `${source}_VIEW_LIST`
+ }));
+ }
+
+ const recentSavesCards = []; // We fill the cards with a for loop over an inline map because
+ // we want empty placeholders if there are not enough cards.
+
+ for (let index = 0; index < items; index++) {
+ const recentSave = recentSavesData[index];
+
+ if (!recentSave) {
+ recentSavesCards.push( /*#__PURE__*/external_React_default().createElement(PlaceholderDSCard, {
+ key: `dscard-${index}`
+ }));
+ } else {
+ var _recentSave$domain_me;
+
+ recentSavesCards.push(renderCard({
+ id: recentSave.id,
+ image_src: recentSave.top_image_url,
+ raw_image_src: recentSave.top_image_url,
+ word_count: recentSave.word_count,
+ time_to_read: recentSave.time_to_read,
+ title: recentSave.resolved_title || recentSave.given_title,
+ url: recentSave.resolved_url || recentSave.given_url,
+ domain: (_recentSave$domain_me = recentSave.domain_metadata) === null || _recentSave$domain_me === void 0 ? void 0 : _recentSave$domain_me.name,
+ excerpt: recentSave.excerpt
+ }, index));
+ }
+ } // We are visible and logged in.
+
+
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement(DSSubHeader, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: "Recently Saved to your List"
+ })), /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ onLinkClick: onMyListClicked,
+ className: "section-sub-link",
+ url: `https://getpocket.com/a${queryParams}`
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: "View My List"
+ }))), /*#__PURE__*/external_React_default().createElement("div", {
+ className: `ds-card-grid-recent-saves ${gridClassName}`
+ }, recentSavesCards));
+}
+class _CardGrid extends (external_React_default()).PureComponent {
+ renderCards() {
+ var _widgets$positions, _widgets$data, _essentialReadsCards, _editorsPicksCards;
+
+ const prefs = this.props.Prefs.values;
+ const {
+ items,
+ hybridLayout,
+ hideCardBackground,
+ fourCardLayout,
+ compactGrid,
+ essentialReadsHeader,
+ editorsPicksHeader,
+ onboardingExperience,
+ widgets,
+ recentSavesEnabled,
+ hideDescriptions,
+ DiscoveryStream
+ } = this.props;
+ const {
+ saveToPocketCard
+ } = DiscoveryStream;
+ const showRecentSaves = prefs.showRecentSaves && recentSavesEnabled;
+ const isOnboardingExperienceDismissed = prefs[PREF_ONBOARDING_EXPERIENCE_DISMISSED];
+ const recs = this.props.data.recommendations.slice(0, items);
+ const cards = [];
+ let essentialReadsCards = [];
+ let editorsPicksCards = [];
+
+ for (let index = 0; index < items; index++) {
+ const rec = recs[index];
+ cards.push(!rec || rec.placeholder ? /*#__PURE__*/external_React_default().createElement(PlaceholderDSCard, {
+ key: `dscard-${index}`
+ }) : /*#__PURE__*/external_React_default().createElement(DSCard, {
+ key: `dscard-${rec.id}`,
+ pos: rec.pos,
+ flightId: rec.flight_id,
+ image_src: rec.image_src,
+ raw_image_src: rec.raw_image_src,
+ word_count: rec.word_count,
+ time_to_read: rec.time_to_read,
+ 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,
+ is_collection: this.props.is_collection,
+ saveToPocketCard: saveToPocketCard
+ }));
+ }
+
+ if (widgets !== null && widgets !== void 0 && (_widgets$positions = widgets.positions) !== null && _widgets$positions !== void 0 && _widgets$positions.length && widgets !== null && widgets !== void 0 && (_widgets$data = widgets.data) !== null && _widgets$data !== void 0 && _widgets$data.length) {
+ let positionIndex = 0;
+ const source = "CARDGRID_WIDGET";
+
+ for (const widget of widgets.data) {
+ let widgetComponent = null;
+ const position = widgets.positions[positionIndex]; // Stop if we run out of positions to place widgets.
+
+ if (!position) {
+ break;
+ }
+
+ switch (widget === null || widget === void 0 ? void 0 : widget.type) {
+ case "TopicsWidget":
+ widgetComponent = /*#__PURE__*/external_React_default().createElement(TopicsWidget, {
+ position: position.index,
+ dispatch: this.props.dispatch,
+ source: source,
+ id: WIDGET_IDS.TOPICS
+ });
+ break;
+ }
+
+ if (widgetComponent) {
+ // We found a widget, so up the position for next try.
+ positionIndex++; // We replace an existing card with the widget.
+
+ cards.splice(position.index, 1, widgetComponent);
+ }
+ }
+ }
+
+ let moreRecsHeader = ""; // For now this is English only.
+
+ if (showRecentSaves || essentialReadsHeader && editorsPicksHeader) {
+ let spliceAt = 6; // For 4 card row layouts, second row is 8 cards, and regular it is 6 cards.
+
+ if (fourCardLayout) {
+ spliceAt = 8;
+ } // If we have a custom header, ensure the more recs section also has a header.
+
+
+ moreRecsHeader = "More Recommendations"; // Put the first 2 rows into essentialReadsCards.
+
+ essentialReadsCards = [...cards.splice(0, spliceAt)]; // Put the rest into editorsPicksCards.
+
+ if (essentialReadsHeader && editorsPicksHeader) {
+ editorsPicksCards = [...cards.splice(0, cards.length)];
+ }
+ }
+
+ const hideCardBackgroundClass = hideCardBackground ? `ds-card-grid-hide-background` : ``;
+ const fourCardLayoutClass = fourCardLayout ? `ds-card-grid-four-card-variant` : ``;
+ const hideDescriptionsClassName = !hideDescriptions ? `ds-card-grid-include-descriptions` : ``;
+ const compactGridClassName = compactGrid ? `ds-card-grid-compact` : ``;
+ const hybridLayoutClassName = hybridLayout ? `ds-card-grid-hybrid-layout` : ``;
+ const gridClassName = `ds-card-grid ${hybridLayoutClassName} ${hideCardBackgroundClass} ${fourCardLayoutClass} ${hideDescriptionsClassName} ${compactGridClassName}`;
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, !isOnboardingExperienceDismissed && onboardingExperience && /*#__PURE__*/external_React_default().createElement(OnboardingExperience, {
+ dispatch: this.props.dispatch
+ }), ((_essentialReadsCards = essentialReadsCards) === null || _essentialReadsCards === void 0 ? void 0 : _essentialReadsCards.length) > 0 && /*#__PURE__*/external_React_default().createElement("div", {
+ className: gridClassName
+ }, essentialReadsCards), showRecentSaves && /*#__PURE__*/external_React_default().createElement(RecentSavesContainer, {
+ gridClassName: gridClassName,
+ dispatch: this.props.dispatch
+ }), ((_editorsPicksCards = editorsPicksCards) === null || _editorsPicksCards === void 0 ? void 0 : _editorsPicksCards.length) > 0 && /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement(DSSubHeader, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: "Editor\u2019s Picks"
+ }))), /*#__PURE__*/external_React_default().createElement("div", {
+ className: gridClassName
+ }, editorsPicksCards)), (cards === null || cards === void 0 ? void 0 : cards.length) > 0 && /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, moreRecsHeader && /*#__PURE__*/external_React_default().createElement(DSSubHeader, null, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: moreRecsHeader
+ }))), /*#__PURE__*/external_React_default().createElement("div", {
+ className: gridClassName
+ }, 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 /*#__PURE__*/external_React_default().createElement("div", null, this.props.title && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-header"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "title"
+ }, this.props.title), this.props.context && /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: this.props.context
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-context"
+ }))), isEmpty ? /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-card-grid empty"
+ }, /*#__PURE__*/external_React_default().createElement(DSEmptyState, {
+ status: data.status,
+ dispatch: this.props.dispatch,
+ feed: this.props.feed
+ })) : this.renderCards());
+ }
+
+}
+_CardGrid.defaultProps = {
+ items: 4 // Number of stories to display
+
+};
+const CardGrid = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Prefs: state.Prefs,
+ DiscoveryStream: state.DiscoveryStream
+}))(_CardGrid);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid.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 CollectionCardGrid extends (external_React_default()).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(actionCreators.DiscoveryStreamUserEvent({
+ event: userEvent,
+ source,
+ action_position: pos
+ }));
+
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const {
+ data,
+ dismissible,
+ pocket_button_enabled
+ } = 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 = /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-collection-card-grid"
+ }, /*#__PURE__*/external_React_default().createElement(CardGrid, {
+ pocket_button_enabled: pocket_button_enabled,
+ title: title,
+ context: sponsoredByMessage,
+ data: recsData,
+ feed: feed,
+ type: type,
+ is_collection: true,
+ dispatch: this.props.dispatch,
+ items: this.props.items
+ }));
+
+ if (dismissible) {
+ return /*#__PURE__*/external_React_default().createElement(DSDismiss, {
+ onDismissClick: this.onDismissClick,
+ extraClasses: `ds-dismiss-ds-collection`
+ }, collectionGrid);
+ }
+
+ return collectionGrid;
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/A11yLinkButton/A11yLinkButton.jsx
+function A11yLinkButton_extends() { A11yLinkButton_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 A11yLinkButton_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 /*#__PURE__*/external_React_default().createElement("button", A11yLinkButton_extends({
+ type: "button"
+ }, props, {
+ className: className
+ }), props.children);
+}
+;// CONCATENATED MODULE: ./content-src/components/ErrorBoundary/ErrorBoundary.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 ErrorBoundaryFallback extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: className
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ "data-l10n-id": "newtab-error-fallback-info"
+ }), /*#__PURE__*/external_React_default().createElement("span", null, /*#__PURE__*/external_React_default().createElement(A11yLinkButton, {
+ className: "reload-button",
+ onClick: this.onClick,
+ "data-l10n-id": "newtab-error-fallback-refresh-link"
+ })));
+ }
+
+}
+ErrorBoundaryFallback.defaultProps = {
+ className: "as-error-fallback"
+};
+class ErrorBoundary extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement(this.props.FallbackComponent, {
+ className: this.props.className
+ });
+ }
+
+}
+ErrorBoundary.defaultProps = {
+ FallbackComponent: ErrorBoundaryFallback
+};
+;// CONCATENATED MODULE: ./content-src/components/CollapsibleSection/CollapsibleSection.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/. */
+
+
+
+
+/**
+ * A section that can collapse. As of bug 1710937, it can no longer collapse.
+ * See bug 1727365 for follow-up work to simplify this component.
+ */
+
+class _CollapsibleSection extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBodyMount = this.onBodyMount.bind(this);
+ this.onMenuButtonMouseEnter = this.onMenuButtonMouseEnter.bind(this);
+ this.onMenuButtonMouseLeave = this.onMenuButtonMouseLeave.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.state = {
+ menuButtonHover: false,
+ showContextMenu: false
+ };
+ this.setContextMenuButtonRef = this.setContextMenuButtonRef.bind(this);
+ }
+
+ setContextMenuButtonRef(element) {
+ this.contextMenuButtonRef = element;
+ }
+
+ onBodyMount(node) {
+ this.sectionBody = node;
+ }
+
+ onMenuButtonMouseEnter() {
+ this.setState({
+ menuButtonHover: true
+ });
+ }
+
+ onMenuButtonMouseLeave() {
+ this.setState({
+ menuButtonHover: false
+ });
+ }
+
+ onMenuUpdate(showContextMenu) {
+ this.setState({
+ showContextMenu
+ });
+ }
+
+ render() {
+ const {
+ isAnimating,
+ maxHeight,
+ menuButtonHover,
+ showContextMenu
+ } = this.state;
+ const {
+ id,
+ collapsed,
+ learnMore,
+ title,
+ subTitle
+ } = 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"
+ };
+ }
+
+ const hasSubtitleClassName = subTitle ? `has-subtitle` : ``;
+ return /*#__PURE__*/external_React_default().createElement("section", {
+ className: `collapsible-section ${this.props.className}${active ? " active" : ""}` // Note: data-section-id is used for web extension api tests in mozilla central
+ ,
+ "data-section-id": id
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-top-bar"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: `section-title-container ${hasSubtitleClassName}`,
+ style: titleStyle
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "section-title"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: title
+ })), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "learn-more-link-wrapper"
+ }, learnMore && /*#__PURE__*/external_React_default().createElement("span", {
+ className: "learn-more-link"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: learnMore.link.message
+ }, /*#__PURE__*/external_React_default().createElement("a", {
+ href: learnMore.link.href
+ })))), subTitle && /*#__PURE__*/external_React_default().createElement("span", {
+ className: "section-sub-title"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: subTitle
+ })))), /*#__PURE__*/external_React_default().createElement(ErrorBoundary, {
+ className: "section-body-fallback"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ ref: this.onBodyMount,
+ style: bodyStyle
+ }, this.props.children)));
+ }
+
+}
+_CollapsibleSection.defaultProps = {
+ document: __webpack_require__.g.document || {
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ visibilityState: "hidden"
+ }
+};
+const CollapsibleSection = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Prefs: state.Prefs
+}))(_CollapsibleSection);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage.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 DSMessage extends (external_React_default()).PureComponent {
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-message"
+ }, /*#__PURE__*/external_React_default().createElement("header", {
+ className: "title"
+ }, this.props.icon && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "glyph",
+ style: {
+ backgroundImage: `url(${this.props.icon})`
+ }
+ }), this.props.title && /*#__PURE__*/external_React_default().createElement("span", {
+ className: "title-text"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: this.props.title
+ })), this.props.link_text && this.props.link_url && /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "link",
+ url: this.props.link_url
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: this.props.link_text
+ }))));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/asrouter/components/ModalOverlay/ModalOverlay.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 ModalOverlayWrapper extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "modalOverlayOuter active",
+ onKeyDown: this.onKeyDown,
+ role: "presentation"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: className,
+ "aria-labelledby": props.headerId,
+ id: props.id,
+ role: "dialog"
+ }, props.children));
+ }
+
+}
+ModalOverlayWrapper.defaultProps = {
+ document: __webpack_require__.g.document
+};
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.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 DSPrivacyModal extends (external_React_default()).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(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK_PRIVACY_INFO",
+ source: "DS_PRIVACY_MODAL"
+ }));
+ }
+
+ onManageLinkClick(event) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.SETTINGS_OPEN
+ }));
+ }
+
+ closeModal() {
+ this.props.dispatch({
+ type: `HIDE_PRIVACY_INFO`,
+ data: {}
+ });
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement(ModalOverlayWrapper, {
+ onClose: this.closeModal,
+ innerClassName: "ds-privacy-modal"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "privacy-notice"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ "data-l10n-id": "newtab-privacy-modal-header"
+ }), /*#__PURE__*/external_React_default().createElement("p", {
+ "data-l10n-id": "newtab-privacy-modal-paragraph-2"
+ }), /*#__PURE__*/external_React_default().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"
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "modal-link modal-link-manage",
+ "data-l10n-id": "newtab-privacy-modal-button-manage",
+ onClick: this.onManageLinkClick
+ })), /*#__PURE__*/external_React_default().createElement("section", {
+ className: "actions"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "done",
+ type: "submit",
+ onClick: this.closeModal,
+ "data-l10n-id": "newtab-privacy-modal-button-done"
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.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 DSSignup extends (external_React_default()).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(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0
+ }));
+ this.props.dispatch(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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: outerClassName
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-signup-content"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon icon-small-spacer icon-mail"
+ }), /*#__PURE__*/external_React_default().createElement("span", null, title, " ", /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "ds-chevron-link",
+ dispatch: dispatch,
+ onLinkClick: this.onLinkClick,
+ url: url
+ }, excerpt)), /*#__PURE__*/external_React_default().createElement(ImpressionStats_ImpressionStats, {
+ flightId: flight_id,
+ rows: [{
+ id,
+ pos: 0,
+ shim: shim && shim.impression
+ }],
+ dispatch: dispatch,
+ source: type
+ })), /*#__PURE__*/external_React_default().createElement(ContextMenuButton, {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuButtonUpdate
+ }, /*#__PURE__*/external_React_default().createElement(LinkMenu, {
+ dispatch: dispatch,
+ index: 0,
+ source: type.toUpperCase(),
+ onShow: this.onMenuShow,
+ options: SIGNUP_CONTEXT_MENU_OPTIONS,
+ shouldSendImpressionStats: true,
+ userEvent: actionCreators.DiscoveryStreamUserEvent,
+ site: {
+ referrer: "https://getpocket.com/recommendations",
+ title,
+ type,
+ url,
+ guid: id,
+ shim,
+ flight_id
+ }
+ })));
+ }
+
+}
+DSSignup.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo.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 DSTextPromo extends (external_React_default()).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(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0
+ }));
+ this.props.dispatch(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 = LinkMenuOptions.BlockUrl(spocData, index, source);
+ const {
+ action,
+ impression,
+ userEvent
+ } = blockUrlOption;
+ this.props.dispatch(action);
+ this.props.dispatch(actionCreators.DiscoveryStreamUserEvent({
+ 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 /*#__PURE__*/external_React_default().createElement(DSDismiss, {
+ onDismissClick: this.onDismissClick,
+ extraClasses: `ds-dismiss-ds-text-promo`
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-text-promo"
+ }, /*#__PURE__*/external_React_default().createElement(DSImage, {
+ alt_text: alt_text,
+ source: image_src,
+ rawSource: raw_image_src
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "text"
+ }, /*#__PURE__*/external_React_default().createElement("h3", null, `${title}\u2003`, /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "ds-chevron-link",
+ dispatch: this.props.dispatch,
+ onLinkClick: this.onLinkClick,
+ url: url
+ }, cta)), /*#__PURE__*/external_React_default().createElement("p", {
+ className: "subtitle"
+ }, context)), /*#__PURE__*/external_React_default().createElement(ImpressionStats_ImpressionStats, {
+ flightId: flight_id,
+ rows: [{
+ id,
+ pos: 0,
+ shim: shim && shim.impression
+ }],
+ dispatch: this.props.dispatch,
+ source: this.props.type
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/lib/screenshot-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/. */
+
+/**
+ * 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: __webpack_require__.g.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)) {
+ __webpack_require__.g.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;
+ }
+
+};
+;// CONCATENATED MODULE: ./content-src/components/Card/Card.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/. */
+
+
+
+
+
+
+ // 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 (external_React_default()).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
+
+
+ try {
+ await gImageLoading.get(imageUrl);
+ } catch (ex) {
+ // Ignore the failed image without changing state
+ return;
+ } // 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(actionCreators.OnlyToMain({
+ type: actionTypes.OPEN_DOWNLOAD_FILE,
+ data: Object.assign(this.props.link, {
+ event: {
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ }));
+ } else {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ }));
+ }
+
+ if (this.props.isWebExtension) {
+ this.props.dispatch(actionCreators.WebExtEvent(actionTypes.WEBEXT_CLICK, {
+ source: this.props.eventSource,
+ url: this.props.link.url,
+ action_position: this.props.index
+ }));
+ } else {
+ this.props.dispatch(actionCreators.UserEvent(Object.assign({
+ event: "CLICK",
+ source: this.props.eventSource,
+ action_position: this.props.index
+ }, this._getTelemetryInfo())));
+
+ if (this.props.shouldSendImpressionStats) {
+ this.props.dispatch(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() {
+ 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 /*#__PURE__*/external_React_default().createElement("li", {
+ className: outerClassName
+ }, /*#__PURE__*/external_React_default().createElement("a", {
+ href: link.type === "pocket" ? link.open_url : link.url,
+ onClick: !props.placeholder ? this.onLinkClick : undefined
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-preview-image-outer"
+ }, hasImage && /*#__PURE__*/external_React_default().createElement("div", {
+ className: `card-preview-image${this.state.imageLoaded ? " loaded" : ""}`,
+ style: imageStyle
+ })), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-details"
+ }, link.type === "download" && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-host-name alternate",
+ "data-l10n-id": "newtab-menu-open-file"
+ }), link.hostname && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-host-name"
+ }, link.hostname.slice(0, 100), link.type === "download" && ` \u2014 ${link.description}`), /*#__PURE__*/external_React_default().createElement("div", {
+ className: ["card-text", icon ? "" : "no-context", link.description ? "" : "no-description", link.hostname ? "" : "no-host-name"].join(" ")
+ }, /*#__PURE__*/external_React_default().createElement("h4", {
+ className: "card-title",
+ dir: "auto"
+ }, link.title), /*#__PURE__*/external_React_default().createElement("p", {
+ className: "card-description",
+ dir: "auto"
+ }, link.description)), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-context"
+ }, icon && !link.context && /*#__PURE__*/external_React_default().createElement("span", {
+ "aria-haspopup": "true",
+ className: `card-context-icon icon icon-${icon}`
+ }), link.icon && link.context && /*#__PURE__*/external_React_default().createElement("span", {
+ "aria-haspopup": "true",
+ className: "card-context-icon icon",
+ style: {
+ backgroundImage: `url('${link.icon}')`
+ }
+ }), fluentID && !link.context && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-context-label",
+ "data-l10n-id": fluentID
+ }), link.context && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "card-context-label"
+ }, link.context))))), !props.placeholder && /*#__PURE__*/external_React_default().createElement(ContextMenuButton, {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuButtonUpdate
+ }, /*#__PURE__*/external_React_default().createElement(LinkMenu, {
+ dispatch: dispatch,
+ index: index,
+ source: eventSource,
+ options: link.contextMenuOptions || contextMenuOptions,
+ site: link,
+ siteInfo: this._getTelemetryInfo(),
+ shouldSendImpressionStats: shouldSendImpressionStats
+ })));
+ }
+
+}
+_Card.defaultProps = {
+ link: {}
+};
+const Card = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ platform: state.Prefs.values.platform
+}))(_Card);
+const PlaceholderCard = props => /*#__PURE__*/external_React_default().createElement(Card, {
+ placeholder: true,
+ className: props.className
+});
+;// CONCATENATED MODULE: ./content-src/lib/perf-service.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/. */
+
+
+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();
+;// CONCATENATED MODULE: ./content-src/components/ComponentPerfTimer/ComponentPerfTimer.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/. */
+
+
+ // 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 (external_React_default()).Component {
+ constructor(props) {
+ super(props); // Just for test dependency injection:
+
+ this.perfSvc = this.props.perfSvc || 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(actionCreators.OnlyToMain({
+ type: 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(actionCreators.OnlyToMain({
+ type: 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;
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/MoreRecommendations/MoreRecommendations.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 MoreRecommendations extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ read_more_endpoint
+ } = this.props;
+
+ if (read_more_endpoint) {
+ return /*#__PURE__*/external_React_default().createElement("a", {
+ className: "more-recommendations",
+ href: read_more_endpoint,
+ "data-l10n-id": "newtab-pocket-more-recommendations"
+ });
+ }
+
+ return null;
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/PocketLoggedInCta/PocketLoggedInCta.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 _PocketLoggedInCta extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ pocketCta
+ } = this.props.Pocket;
+ return /*#__PURE__*/external_React_default().createElement("span", {
+ className: "pocket-logged-in-cta"
+ }, /*#__PURE__*/external_React_default().createElement("a", {
+ className: "pocket-cta-button",
+ href: pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"
+ }, pocketCta.ctaButton ? pocketCta.ctaButton : /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-cta-button"
+ })), /*#__PURE__*/external_React_default().createElement("a", {
+ href: pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "cta-text"
+ }, pocketCta.ctaText ? pocketCta.ctaText : /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-cta-text"
+ }))));
+ }
+
+}
+const PocketLoggedInCta = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Pocket: state.Pocket
+}))(_PocketLoggedInCta);
+;// CONCATENATED MODULE: ./content-src/components/Topics/Topics.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 Topic extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ url,
+ name
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement("li", null, /*#__PURE__*/external_React_default().createElement("a", {
+ key: name,
+ href: url
+ }, name));
+ }
+
+}
+class Topics extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ topics
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement("span", {
+ className: "topics"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": "newtab-pocket-read-more"
+ }), /*#__PURE__*/external_React_default().createElement("ul", null, topics && topics.map(t => /*#__PURE__*/external_React_default().createElement(Topic, {
+ key: t.name,
+ url: t.url,
+ name: t.name
+ }))));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/TopSites/SearchShortcutsForm.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 SelectableSearchShortcut extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ shortcut,
+ selected
+ } = this.props;
+ const imageStyle = {
+ backgroundImage: `url("${shortcut.tippyTopIcon}")`
+ };
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-outer search-shortcut"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ type: "checkbox",
+ id: shortcut.keyword,
+ name: shortcut.keyword,
+ checked: selected,
+ onChange: this.props.onChange
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: shortcut.keyword
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-inner"
+ }, /*#__PURE__*/external_React_default().createElement("span", null, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "tile"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-icon rich-icon",
+ style: imageStyle,
+ "data-fallback": "@"
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-icon search-topsite"
+ })), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "title"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ dir: "auto"
+ }, shortcut.keyword))))));
+ }
+
+}
+class SearchShortcutsForm extends (external_React_default()).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(actionCreators.OnlyToMain({
+ type: actionTypes.UPDATE_PINNED_SEARCH_SHORTCUTS,
+ data: {
+ addedShortcuts: pinQueue,
+ deletedShortcuts: unpinQueue
+ }
+ })); // Send the Telemetry pings.
+
+ pinQueue.forEach(shortcut => {
+ this.props.dispatch(actionCreators.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "SEARCH_EDIT_ADD",
+ value: {
+ search_vendor: shortcut.searchVendor
+ }
+ }));
+ });
+ unpinQueue.forEach(shortcut => {
+ this.props.dispatch(actionCreators.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 /*#__PURE__*/external_React_default().createElement("form", {
+ className: "topsite-form"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "search-shortcuts-container"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "section-title grey-title",
+ "data-l10n-id": "newtab-topsites-add-search-engine-header"
+ }), /*#__PURE__*/external_React_default().createElement("div", null, this.state.shortcuts.map(shortcut => /*#__PURE__*/external_React_default().createElement(SelectableSearchShortcut, {
+ key: shortcut.keyword,
+ shortcut: shortcut,
+ selected: shortcut.isSelected,
+ onChange: this.handleChange
+ })))), /*#__PURE__*/external_React_default().createElement("section", {
+ className: "actions"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "cancel",
+ type: "button",
+ onClick: this.onCancelButtonClick,
+ "data-l10n-id": "newtab-topsites-cancel-button"
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ className: "done",
+ type: "submit",
+ onClick: this.onSaveButtonClick,
+ "data-l10n-id": "newtab-topsites-save-button"
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./common/Dedupe.sys.mjs
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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_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: "",
+ isForStartupCache: false,
+ customizeMenuVisible: false,
+ },
+ 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: { featureConfig: {} },
+ },
+ 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: [],
+ },
+ experimentData: {
+ utmSource: "pocket-newtab",
+ utmCampaign: undefined,
+ utmContent: undefined,
+ },
+ recentSavesData: [],
+ isUserLoggedIn: false,
+ recentSavesEnabled: false,
+ },
+ Personalization: {
+ 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 actionTypes.INIT:
+ return Object.assign({}, prevState, action.data || {}, {
+ initialized: true,
+ });
+ case actionTypes.TOP_SITES_UPDATED:
+ // Toggle `isForStartupCache` when receiving the `TOP_SITES_UPDATE` action
+ // so that sponsored tiles can be rendered as usual. See Bug 1826360.
+ return Object.assign({}, prevState, action.data || {}, {
+ isForStartupCache: false,
+ });
+ case actionTypes.SHOW_PERSONALIZE:
+ return Object.assign({}, prevState, {
+ customizeMenuVisible: true,
+ });
+ case actionTypes.HIDE_PERSONALIZE:
+ return Object.assign({}, prevState, {
+ customizeMenuVisible: false,
+ });
+ default:
+ return prevState;
+ }
+}
+
+function ASRouter(prevState = INITIAL_STATE.ASRouter, action) {
+ switch (action.type) {
+ case 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 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 actionTypes.TOP_SITES_PREFS_UPDATED:
+ return Object.assign({}, prevState, { pref: action.data.pref });
+ case actionTypes.TOP_SITES_EDIT:
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: action.data.index,
+ previewResponse: null,
+ },
+ });
+ case actionTypes.TOP_SITES_CANCEL_EDIT:
+ return Object.assign({}, prevState, { editForm: null });
+ case actionTypes.TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, { showSearchShortcutsForm: true });
+ case actionTypes.TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, { showSearchShortcutsForm: false });
+ case 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 actionTypes.PREVIEW_REQUEST:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null,
+ previewUrl: action.data.url,
+ },
+ });
+ case actionTypes.PREVIEW_REQUEST_CANCEL:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null,
+ },
+ });
+ case 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 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 actionTypes.PLACES_BOOKMARKS_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.map(site => {
+ if (site && action.data.urls.includes(site.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 actionTypes.PLACES_LINKS_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.filter(
+ site => !action.data.urls.includes(site.url)
+ );
+ return Object.assign({}, prevState, { rows: newRows });
+ case actionTypes.UPDATE_SEARCH_SHORTCUTS:
+ return { ...prevState, searchShortcuts: action.data.searchShortcuts };
+ case actionTypes.SNIPPETS_PREVIEW_MODE:
+ return { ...prevState, rows: [] };
+ default:
+ return prevState;
+ }
+}
+
+function Dialog(prevState = INITIAL_STATE.Dialog, action) {
+ switch (action.type) {
+ case actionTypes.DIALOG_OPEN:
+ return Object.assign({}, prevState, { visible: true, data: action.data });
+ case actionTypes.DIALOG_CANCEL:
+ return Object.assign({}, prevState, { visible: false });
+ case 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 actionTypes.PREFS_INITIAL_VALUES:
+ return Object.assign({}, prevState, {
+ initialized: true,
+ values: action.data,
+ });
+ case 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 actionTypes.SECTION_DEREGISTER:
+ return prevState.filter(section => section.id !== action.data);
+ case 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 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 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 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 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 actionTypes.PLACES_BOOKMARKS_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 (action.data.urls.includes(item.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 actionTypes.PLACES_LINKS_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.filter(
+ site => !action.data.urls.includes(site.url)
+ ),
+ })
+ );
+ case 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 actionTypes.DELETE_FROM_POCKET:
+ case actionTypes.ARCHIVE_FROM_POCKET:
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.filter(
+ site => site.pocket_id !== action.data.pocket_id
+ ),
+ })
+ );
+ case actionTypes.SNIPPETS_PREVIEW_MODE:
+ return prevState.map(section => ({ ...section, rows: [] }));
+ default:
+ return prevState;
+ }
+}
+
+function Snippets(prevState = INITIAL_STATE.Snippets, action) {
+ switch (action.type) {
+ case actionTypes.SNIPPETS_DATA:
+ return Object.assign({}, prevState, { initialized: true }, action.data);
+ case actionTypes.SNIPPET_BLOCKED:
+ return Object.assign({}, prevState, {
+ blockList: prevState.blockList.concat(action.data),
+ });
+ case actionTypes.SNIPPETS_BLOCKLIST_CLEARED:
+ return Object.assign({}, prevState, { blockList: [] });
+ case actionTypes.SNIPPETS_RESET:
+ return INITIAL_STATE.Snippets;
+ default:
+ return prevState;
+ }
+}
+
+function Pocket(prevState = INITIAL_STATE.Pocket, action) {
+ switch (action.type) {
+ case actionTypes.POCKET_WAITING_FOR_SPOC:
+ return { ...prevState, waitingForSpoc: action.data };
+ case actionTypes.POCKET_LOGGED_IN:
+ return { ...prevState, isUserLoggedIn: !!action.data };
+ case 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 Reducers_sys_Personalization(prevState = INITIAL_STATE.Personalization, action) {
+ switch (action.type) {
+ case actionTypes.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED:
+ return {
+ ...prevState,
+ lastUpdated: action.data.lastUpdated,
+ };
+ case actionTypes.DISCOVERY_STREAM_PERSONALIZATION_INIT:
+ return {
+ ...prevState,
+ initialized: true,
+ };
+ 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 actionTypes.DISCOVERY_STREAM_CONFIG_CHANGE:
+ // Fall through to a separate action is so it doesn't trigger a listener update on init
+ case actionTypes.DISCOVERY_STREAM_CONFIG_SETUP:
+ return { ...prevState, config: action.data || {} };
+ case actionTypes.DISCOVERY_STREAM_EXPERIMENT_DATA:
+ return { ...prevState, experimentData: action.data || {} };
+ case actionTypes.DISCOVERY_STREAM_LAYOUT_UPDATE:
+ return {
+ ...prevState,
+ lastUpdated: action.data.lastUpdated || null,
+ layout: action.data.layout || [],
+ };
+ case actionTypes.DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE:
+ return {
+ ...prevState,
+ isCollectionDismissible: action.data.value,
+ };
+ case actionTypes.DISCOVERY_STREAM_PREFS_SETUP:
+ return {
+ ...prevState,
+ recentSavesEnabled: action.data.recentSavesEnabled,
+ pocketButtonEnabled: action.data.pocketButtonEnabled,
+ saveToPocketCard: action.data.saveToPocketCard,
+ hideDescriptions: action.data.hideDescriptions,
+ compactImages: action.data.compactImages,
+ imageGradient: action.data.imageGradient,
+ newSponsoredLabel: action.data.newSponsoredLabel,
+ titleLines: action.data.titleLines,
+ descLines: action.data.descLines,
+ readTime: action.data.readTime,
+ };
+ case actionTypes.DISCOVERY_STREAM_RECENT_SAVES:
+ return {
+ ...prevState,
+ recentSavesData: action.data.recentSaves,
+ };
+ case actionTypes.DISCOVERY_STREAM_POCKET_STATE_SET:
+ return {
+ ...prevState,
+ isUserLoggedIn: action.data.isUserLoggedIn,
+ };
+ case actionTypes.HIDE_PRIVACY_INFO:
+ return {
+ ...prevState,
+ isPrivacyInfoModalVisible: false,
+ };
+ case actionTypes.SHOW_PRIVACY_INFO:
+ return {
+ ...prevState,
+ isPrivacyInfoModalVisible: true,
+ };
+ case actionTypes.DISCOVERY_STREAM_LAYOUT_RESET:
+ return { ...INITIAL_STATE.DiscoveryStream, config: prevState.config };
+ case actionTypes.DISCOVERY_STREAM_FEEDS_UPDATE:
+ return {
+ ...prevState,
+ feeds: {
+ ...prevState.feeds,
+ loaded: true,
+ },
+ };
+ case 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 actionTypes.DISCOVERY_STREAM_SPOCS_CAPS:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ frequency_caps: [...prevState.spocs.frequency_caps, ...action.data],
+ },
+ };
+ case actionTypes.DISCOVERY_STREAM_SPOCS_ENDPOINT:
+ return {
+ ...prevState,
+ spocs: {
+ ...INITIAL_STATE.DiscoveryStream.spocs,
+ spocs_endpoint:
+ action.data.url ||
+ INITIAL_STATE.DiscoveryStream.spocs.spocs_endpoint,
+ },
+ };
+ case actionTypes.DISCOVERY_STREAM_SPOCS_PLACEMENTS:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ placements:
+ action.data.placements ||
+ INITIAL_STATE.DiscoveryStream.spocs.placements,
+ },
+ };
+ case 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 actionTypes.DISCOVERY_STREAM_SPOC_BLOCKED:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ blocked: [...prevState.spocs.blocked, action.data.url],
+ },
+ };
+ case actionTypes.DISCOVERY_STREAM_LINK_BLOCKED:
+ return isNotReady()
+ ? prevState
+ : nextState(items =>
+ items.filter(item => item.url !== action.data.url)
+ );
+
+ case 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 actionTypes.DELETE_FROM_POCKET:
+ case actionTypes.ARCHIVE_FROM_POCKET:
+ return isNotReady()
+ ? prevState
+ : nextState(items =>
+ items.filter(item => item.pocket_id !== action.data.pocket_id)
+ );
+
+ case 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 actionTypes.PLACES_BOOKMARKS_REMOVED:
+ const removeBookmarkInfo = item => {
+ if (action.data.urls.includes(item.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 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 actionTypes.DISABLE_SEARCH:
+ return Object.assign({ ...prevState, disable: true });
+ case actionTypes.FAKE_FOCUS_SEARCH:
+ return Object.assign({ ...prevState, fakeFocus: true });
+ case actionTypes.SHOW_SEARCH:
+ return Object.assign({ ...prevState, disable: false, fakeFocus: false });
+ default:
+ return prevState;
+ }
+}
+
+const reducers = {
+ TopSites,
+ App,
+ ASRouter,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization: Reducers_sys_Personalization,
+ DiscoveryStream,
+ Search,
+};
+
+;// 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 extends (external_React_default()).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 /*#__PURE__*/external_React_default().createElement("div", {
+ className: "loading-container"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "loading-animation"
+ }));
+ } else if (showClearButton) {
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("label", null, /*#__PURE__*/external_React_default().createElement("span", {
+ "data-l10n-id": this.props.titleId
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: `field ${typeUrl ? "url" : ""}${validationError ? " invalid" : ""}`
+ }, /*#__PURE__*/external_React_default().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.autoFocusOnOpen,
+ disabled: this.props.loading
+ }), this.renderLoadingOrCloseButton(), validationError && /*#__PURE__*/external_React_default().createElement("aside", {
+ className: "error-tooltip",
+ "data-l10n-id": this.props.errorMessageId
+ })));
+ }
+
+}
+TopSiteFormInput.defaultProps = {
+ showClearButton: false,
+ value: "",
+ validationError: false
+};
+;// CONCATENATED MODULE: ./content-src/components/TopSites/TopSiteImpressionWrapper.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 TopSiteImpressionWrapper_VISIBLE = "visible";
+const TopSiteImpressionWrapper_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 TopSiteImpressionWrapper_INTERSECTION_RATIO = 0.5;
+/**
+ * Impression wrapper for a TopSite tile.
+ *
+ * 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.
+ */
+
+class TopSiteImpressionWrapper extends (external_React_default()).PureComponent {
+ _dispatchImpressionStats() {
+ const {
+ actionType,
+ tile
+ } = this.props;
+
+ if (!actionType) {
+ return;
+ }
+
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionType,
+ data: {
+ type: "impression",
+ ...tile
+ }
+ }));
+ }
+
+ setImpressionObserverOrAddListener() {
+ const {
+ props
+ } = this;
+
+ if (!props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === TopSiteImpressionWrapper_VISIBLE) {
+ this.setImpressionObserver();
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ props.document.removeEventListener(TopSiteImpressionWrapper_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === TopSiteImpressionWrapper_VISIBLE) {
+ this.setImpressionObserver();
+ props.document.removeEventListener(TopSiteImpressionWrapper_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ props.document.addEventListener(TopSiteImpressionWrapper_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.tile) {
+ return;
+ }
+
+ this._handleIntersect = entries => {
+ if (entries.some(entry => entry.isIntersecting && entry.intersectionRatio >= TopSiteImpressionWrapper_INTERSECTION_RATIO)) {
+ this._dispatchImpressionStats();
+
+ this.impressionObserver.unobserve(this.refs.topsite_impression_wrapper);
+ }
+ };
+
+ const options = {
+ threshold: TopSiteImpressionWrapper_INTERSECTION_RATIO
+ };
+ this.impressionObserver = new props.IntersectionObserver(this._handleIntersect, options);
+ this.impressionObserver.observe(this.refs.topsite_impression_wrapper);
+ }
+
+ componentDidMount() {
+ if (this.props.tile) {
+ this.setImpressionObserverOrAddListener();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._handleIntersect && this.impressionObserver) {
+ this.impressionObserver.unobserve(this.refs.topsite_impression_wrapper);
+ }
+
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(TopSiteImpressionWrapper_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ ref: "topsite_impression_wrapper",
+ className: "topsite-impression-observer"
+ }, this.props.children);
+ }
+
+}
+TopSiteImpressionWrapper.defaultProps = {
+ IntersectionObserver: __webpack_require__.g.IntersectionObserver,
+ document: __webpack_require__.g.document,
+ actionType: null,
+ tile: null
+};
+;// CONCATENATED MODULE: ./content-src/components/TopSites/TopSite.jsx
+function TopSite_extends() { TopSite_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 TopSite_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";
+const NEWTAB_SOURCE = "newtab"; // For cases if we want to know if this is sponsored by either sponsored_position or type.
+// We have two sources for sponsored topsites, and
+// sponsored_position is set by one sponsored source, and type is set by another.
+// This is not called in all cases, sometimes we want to know if it's one source
+// or the other. This function is only applicable in cases where we only care if it's either.
+
+function isSponsored(link) {
+ return (link === null || link === void 0 ? void 0 : link.sponsored_position) || (link === null || link === void 0 ? void 0 : link.type) === SPOC_TYPE;
+}
+
+class TopSiteLink extends (external_React_default()).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 || !isSponsored(this.props.link)) && 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":
+ event.target.blur();
+
+ if (isSponsored(this.props.link)) {
+ event.preventDefault();
+ break;
+ }
+
+ this.dragged = true;
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/topsite-index", this.props.index);
+ 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
+ } = this.props;
+ const {
+ tippyTopIcon,
+ faviconSize
+ } = link;
+ let imageClassName;
+ let imageStyle;
+ let showSmallFavicon = false;
+ let smallFaviconStyle;
+ let hasScreenshotImage = this.state.screenshotImage && this.state.screenshotImage.url;
+ let selectedColor;
+
+ if (defaultStyle) {
+ // force no styles (letter fallback) even if the link has imagery
+ 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
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: hasScreenshotImage ? `url(${this.state.screenshotImage.url})` : ""
+ };
+ } else if (tippyTopIcon || link.type === SPOC_TYPE || 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 if (faviconSize >= MIN_SMALL_FAVICON_SIZE) {
+ showSmallFavicon = true;
+ smallFaviconStyle = {
+ backgroundImage: `url(${link.favicon})`
+ };
+ } else {
+ selectedColor = this.generateColor();
+ imageClassName = "";
+ }
+
+ return {
+ showSmallFavicon,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor
+ };
+ }
+
+ render() {
+ const {
+ children,
+ className,
+ isDraggable,
+ link,
+ onClick,
+ title
+ } = this.props;
+ const topSiteOuterClassName = `top-site-outer${className ? ` ${className}` : ""}${link.isDragged ? " dragged" : ""}${link.searchTopSite ? " search-shortcut" : ""}`;
+ const [letterFallback] = title;
+ const {
+ showSmallFavicon,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor
+ } = this.calculateStyle();
+ let draggableProps = {};
+
+ if (isDraggable) {
+ draggableProps = {
+ onClick: this.onDragEvent,
+ onDragEnd: this.onDragEvent,
+ onDragStart: this.onDragEvent,
+ onMouseDown: this.onDragEvent
+ };
+ }
+
+ let impressionStats = null;
+
+ if (link.type === SPOC_TYPE) {
+ // Record impressions for Pocket tiles.
+ impressionStats = /*#__PURE__*/external_React_default().createElement(ImpressionStats_ImpressionStats, {
+ flightId: link.flightId,
+ rows: [{
+ id: link.id,
+ pos: link.pos,
+ shim: link.shim && link.shim.impression,
+ advertiser: title.toLocaleLowerCase()
+ }],
+ dispatch: this.props.dispatch,
+ source: TOP_SITES_SOURCE
+ });
+ } else if (isSponsored(link)) {
+ // Record impressions for non-Pocket sponsored tiles.
+ impressionStats = /*#__PURE__*/external_React_default().createElement(TopSiteImpressionWrapper, {
+ actionType: actionTypes.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ tile: {
+ position: this.props.index,
+ tile_id: link.sponsored_tile_id || -1,
+ reporting_url: link.sponsored_impression_url,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE
+ } // For testing.
+ ,
+ IntersectionObserver: this.props.IntersectionObserver,
+ document: this.props.document,
+ dispatch: this.props.dispatch
+ });
+ } else {
+ // Record impressions for organic tiles.
+ impressionStats = /*#__PURE__*/external_React_default().createElement(TopSiteImpressionWrapper, {
+ actionType: actionTypes.TOP_SITES_ORGANIC_IMPRESSION_STATS,
+ tile: {
+ position: this.props.index,
+ source: NEWTAB_SOURCE
+ } // For testing.
+ ,
+ IntersectionObserver: this.props.IntersectionObserver,
+ document: this.props.document,
+ dispatch: this.props.dispatch
+ });
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("li", TopSite_extends({
+ className: topSiteOuterClassName,
+ onDrop: this.onDragEvent,
+ onDragOver: this.onDragEvent,
+ onDragEnter: this.onDragEvent,
+ onDragLeave: this.onDragEvent
+ }, draggableProps), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-inner"
+ }, /*#__PURE__*/external_React_default().createElement("a", {
+ className: "top-site-button",
+ href: link.searchTopSite ? undefined : link.url,
+ tabIndex: "0",
+ onKeyPress: this.onKeyPress,
+ onClick: onClick,
+ draggable: true,
+ "data-is-sponsored-link": !!link.sponsored_tile_id
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "tile",
+ "aria-hidden": true
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: selectedColor ? "icon-wrapper letter-fallback" : "icon-wrapper",
+ "data-fallback": letterFallback,
+ style: selectedColor ? {
+ backgroundColor: selectedColor
+ } : {}
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: imageClassName,
+ style: imageStyle
+ }), showSmallFavicon && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-icon default-icon",
+ "data-fallback": smallFaviconStyle ? "" : letterFallback,
+ style: smallFaviconStyle
+ })), link.searchTopSite && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-site-icon search-topsite"
+ })), /*#__PURE__*/external_React_default().createElement("div", {
+ className: `title${link.isPinned ? " has-icon pinned" : ""}${link.type === SPOC_TYPE || link.show_sponsored_label ? " sponsored" : ""}`
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ dir: "auto"
+ }, link.isPinned && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "icon icon-pin-small"
+ }), title || /*#__PURE__*/external_React_default().createElement("br", null), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "sponsored-label",
+ "data-l10n-id": "newtab-topsite-sponsored"
+ })))), children, impressionStats));
+ }
+
+}
+TopSiteLink.defaultProps = {
+ title: "",
+ link: {},
+ isDraggable: true
+};
+class TopSite extends (external_React_default()).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 (isSponsored(this.props.link)) {
+ value.card_type = "spoc";
+ }
+
+ return {
+ value
+ };
+ }
+
+ userEvent(event) {
+ this.props.dispatch(actionCreators.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(actionCreators.OnlyToMain({
+ type: actionTypes.OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ }));
+
+ if (this.props.link.type === SPOC_TYPE) {
+ // Record a Pocket-specific click.
+ this.props.dispatch(actionCreators.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
+ }]
+ })); // Record a click for a Pocket sponsored tile.
+
+ const title = this.props.link.label || this.props.link.hostname;
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.link.pos,
+ tile_id: this.props.link.id,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE
+ }
+ }));
+ } else if (isSponsored(this.props.link)) {
+ // Record a click for a non-Pocket sponsored tile.
+ const title = this.props.link.label || this.props.link.hostname;
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.index,
+ tile_id: this.props.link.sponsored_tile_id || -1,
+ reporting_url: this.props.link.sponsored_click_url,
+ advertiser: title.toLocaleLowerCase(),
+ source: NEWTAB_SOURCE
+ }
+ }));
+ } else {
+ // Record a click for an organic tile.
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.TOP_SITES_ORGANIC_IMPRESSION_STATS,
+ data: {
+ type: "click",
+ position: this.props.index,
+ source: NEWTAB_SOURCE
+ }
+ }));
+ }
+
+ if (this.props.link.sendAttributionRequest) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.PARTNER_LINK_ATTRIBUTION,
+ data: {
+ targetURL: this.props.link.url,
+ source: "newtab"
+ }
+ }));
+ }
+ } else {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: 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 = 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 /*#__PURE__*/external_React_default().createElement(TopSiteLink, TopSite_extends({}, props, {
+ onClick: this.onLinkClick,
+ onDragEvent: this.props.onDragEvent,
+ className: `${props.className || ""}${isContextMenuOpen ? " active" : ""}`,
+ title: title
+ }), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement(ContextMenuButton, {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuUpdate
+ }, /*#__PURE__*/external_React_default().createElement(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
+ }))));
+ }
+
+}
+TopSite.defaultProps = {
+ link: {},
+
+ onActivate() {}
+
+};
+class TopSitePlaceholder extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEditButtonClick = this.onEditButtonClick.bind(this);
+ }
+
+ onEditButtonClick() {
+ this.props.dispatch({
+ type: actionTypes.TOP_SITES_EDIT,
+ data: {
+ index: this.props.index
+ }
+ });
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement(TopSiteLink, TopSite_extends({}, this.props, {
+ className: `placeholder ${this.props.className || ""}`,
+ isDraggable: false
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ "aria-haspopup": "dialog",
+ className: "context-menu-button edit-button icon",
+ "data-l10n-id": "newtab-menu-topsites-placeholder-tooltip",
+ onClick: this.onEditButtonClick
+ }));
+ }
+
+}
+class _TopSiteList extends (external_React_default()).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(actionCreators.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(actionCreators.AlsoToMain({
+ type: 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 * 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 || isSponsored(site)) ? site : null);
+ const unpinned = topSites.filter(site => site && !site.isPinned && !isSponsored(site));
+ 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 (isSponsored(preview[nextIndex])) {
+ 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
+ }; // 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";
+ }
+
+ let topSiteLink; // Use a placeholder if the link is empty or it's rendering a sponsored
+ // tile for the about:home startup cache.
+
+ if (!link || props.App.isForStartupCache && isSponsored(link)) {
+ topSiteLink = /*#__PURE__*/external_React_default().createElement(TopSitePlaceholder, TopSite_extends({}, slotProps, commonProps));
+ } else {
+ topSiteLink = /*#__PURE__*/external_React_default().createElement(TopSite, TopSite_extends({
+ link: link,
+ activeIndex: this.state.activeIndex,
+ onActivate: this.onActivate
+ }, slotProps, commonProps, {
+ colors: props.colors
+ }));
+ }
+
+ topSitesUI.push(topSiteLink);
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("ul", {
+ className: `top-sites-list${this.state.draggedSite ? " dnd-active" : ""}`
+ }, topSitesUI);
+ }
+
+}
+const TopSiteList = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ App: state.App
+}))(_TopSiteList);
+;// CONCATENATED MODULE: ./content-src/components/TopSites/TopSiteForm.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 TopSiteForm extends (external_React_default()).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: 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(actionCreators.AlsoToMain({
+ type: actionTypes.TOP_SITES_PIN,
+ data: {
+ site,
+ index
+ }
+ }));
+ this.props.dispatch(actionCreators.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(actionCreators.AlsoToMain({
+ type: actionTypes.PREVIEW_REQUEST,
+ data: {
+ url: this.cleanUrl(this.state.customScreenshotUrl)
+ }
+ }));
+ this.props.dispatch(actionCreators.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 /*#__PURE__*/external_React_default().createElement(A11yLinkButton, {
+ onClick: this.onEnableScreenshotUrlForm,
+ className: "enable-custom-image-input",
+ "data-l10n-id": "newtab-topsites-use-image-link"
+ });
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "custom-image-input-container"
+ }, /*#__PURE__*/external_React_default().createElement(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;
+ const addTopsitesHeaderL10nId = "newtab-topsites-add-shortcut-header";
+ const editTopsitesHeaderL10nId = "newtab-topsites-edit-shortcut-header";
+ return /*#__PURE__*/external_React_default().createElement("form", {
+ className: "topsite-form",
+ onSubmit: onSubmit
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "form-input-container"
+ }, /*#__PURE__*/external_React_default().createElement("h3", {
+ className: "section-title grey-title",
+ "data-l10n-id": showAsAdd ? addTopsitesHeaderL10nId : editTopsitesHeaderL10nId
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "fields-and-preview"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "form-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement(TopSiteFormInput, {
+ onChange: this.onLabelChange,
+ value: this.state.label,
+ titleId: "newtab-topsites-title-label",
+ placeholderId: "newtab-topsites-title-input",
+ autoFocusOnOpen: true
+ }), /*#__PURE__*/external_React_default().createElement(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()), /*#__PURE__*/external_React_default().createElement(TopSiteLink, {
+ link: previewLink,
+ defaultStyle: requestFailed,
+ title: this.state.label
+ }))), /*#__PURE__*/external_React_default().createElement("section", {
+ className: "actions"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "cancel",
+ type: "button",
+ onClick: this.onCancelButtonClick,
+ "data-l10n-id": "newtab-topsites-cancel-button"
+ }), previewMode ? /*#__PURE__*/external_React_default().createElement("button", {
+ className: "done preview",
+ type: "submit",
+ "data-l10n-id": "newtab-topsites-preview-button"
+ }) : /*#__PURE__*/external_React_default().createElement("button", {
+ className: "done",
+ type: "submit",
+ "data-l10n-id": showAsAdd ? "newtab-topsites-add-button" : "newtab-topsites-save-button"
+ })));
+ }
+
+}
+TopSiteForm.defaultProps = {
+ site: null,
+ index: -1
+};
+;// CONCATENATED MODULE: ./content-src/components/TopSites/TopSites.jsx
+function TopSites_extends() { TopSites_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 TopSites_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 >= MIN_RICH_FAVICON_SIZE) {
+ return "rich_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: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0
+ });
+}
+
+class _TopSites extends (external_React_default()).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(actionCreators.AlsoToMain({
+ type: 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 = TOP_SITES_MAX_SITES_PER_ROW; // $break-point-widest = 1072px (from _variables.scss)
+
+ if (!__webpack_require__.g.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(actionCreators.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "TOP_SITES_EDIT_CLOSE"
+ }));
+ this.props.dispatch({
+ type: actionTypes.TOP_SITES_CANCEL_EDIT
+ });
+ }
+
+ onSearchShortcutsFormClose() {
+ this.props.dispatch(actionCreators.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "SEARCH_EDIT_CLOSE"
+ }));
+ this.props.dispatch({
+ type: actionTypes.TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL
+ });
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ editForm,
+ showSearchShortcutsForm
+ } = props.TopSites;
+ const extraMenuOptions = ["AddTopSite"];
+ const colors = props.Prefs.values["newNewtabExperience.colors"];
+
+ if (props.Prefs.values["improvesearch.topSiteSearchShortcuts"]) {
+ extraMenuOptions.push("AddSearchShortcut");
+ }
+
+ return /*#__PURE__*/external_React_default().createElement(ComponentPerfTimer, {
+ id: "topsites",
+ initialized: props.TopSites.initialized,
+ dispatch: props.dispatch
+ }, /*#__PURE__*/external_React_default().createElement(CollapsibleSection, {
+ className: "top-sites",
+ id: "topsites",
+ title: props.title || {
+ id: "newtab-section-header-topsites"
+ },
+ hideTitle: true,
+ extraMenuOptions: extraMenuOptions,
+ showPrefName: "feeds.topsites",
+ eventSource: TOP_SITES_SOURCE,
+ collapsed: false,
+ isFixed: props.isFixed,
+ isFirst: props.isFirst,
+ isLast: props.isLast,
+ dispatch: props.dispatch
+ }, /*#__PURE__*/external_React_default().createElement(TopSiteList, {
+ TopSites: props.TopSites,
+ TopSitesRows: props.TopSitesRows,
+ dispatch: props.dispatch,
+ topSiteIconType: topSiteIconType,
+ colors: colors
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "edit-topsites-wrapper"
+ }, editForm && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "edit-topsites"
+ }, /*#__PURE__*/external_React_default().createElement(ModalOverlayWrapper, {
+ unstyled: true,
+ onClose: this.onEditFormClose,
+ innerClassName: "modal"
+ }, /*#__PURE__*/external_React_default().createElement(TopSiteForm, TopSites_extends({
+ site: props.TopSites.rows[editForm.index],
+ onClose: this.onEditFormClose,
+ dispatch: this.props.dispatch
+ }, editForm)))), showSearchShortcutsForm && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "edit-search-shortcuts"
+ }, /*#__PURE__*/external_React_default().createElement(ModalOverlayWrapper, {
+ unstyled: true,
+ onClose: this.onSearchShortcutsFormClose,
+ innerClassName: "modal"
+ }, /*#__PURE__*/external_React_default().createElement(SearchShortcutsForm, {
+ TopSites: props.TopSites,
+ onClose: this.onSearchShortcutsFormClose,
+ dispatch: this.props.dispatch
+ }))))));
+ }
+
+}
+const TopSites_TopSites = (0,external_ReactRedux_namespaceObject.connect)((state, props) => ({
+ TopSites: state.TopSites,
+ Prefs: state.Prefs,
+ TopSitesRows: state.Prefs.values.topSitesRows
+}))(_TopSites);
+;// CONCATENATED MODULE: ./content-src/components/Sections/Sections.jsx
+function Sections_extends() { Sections_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 Sections_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 Sections_VISIBLE = "visible";
+const Sections_VISIBILITY_CHANGE_EVENT = "visibilitychange";
+const CARDS_PER_ROW_DEFAULT = 3;
+const CARDS_PER_ROW_COMPACT_WIDE = 4;
+class Section extends (external_React_default()).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 && __webpack_require__.g.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(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 === Sections_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(Sections_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 === Sections_VISIBLE) {
+ if (!this.props.pref.collapsed) {
+ this._dispatchImpressionStats();
+ }
+
+ props.document.removeEventListener(Sections_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ props.document.addEventListener(Sections_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(Sections_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(actionCreators.AlsoToMain({
+ type: actionTypes.NEW_TAB_REHYDRATED,
+ data: {}
+ }));
+ this.renderNotified = true;
+ }
+ }
+
+ render() {
+ const {
+ id,
+ eventSource,
+ title,
+ 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 ? /*#__PURE__*/external_React_default().createElement(Card, {
+ key: i,
+ index: i,
+ className: className,
+ dispatch: dispatch,
+ link: link,
+ contextMenuOptions: contextMenuOptions,
+ eventSource: eventSource,
+ shouldSendImpressionStats: this.props.shouldSendImpressionStats,
+ isWebExtension: this.props.isWebExtension
+ }) : /*#__PURE__*/external_React_default().createElement(PlaceholderCard, {
+ key: i,
+ className: className
+ }));
+ }
+ }
+
+ const sectionClassName = ["section", compactCards ? "compact-cards" : "normal-cards"].join(" "); // <Section> <-- React component
+ // <section> <-- HTML5 element
+
+ return /*#__PURE__*/external_React_default().createElement(ComponentPerfTimer, this.props, /*#__PURE__*/external_React_default().createElement(CollapsibleSection, {
+ className: sectionClassName,
+ 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 && /*#__PURE__*/external_React_default().createElement("ul", {
+ className: "section-list",
+ style: {
+ padding: 0
+ }
+ }, cards), shouldShowEmptyState && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "section-empty-state"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "empty-state"
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: emptyState.message
+ }, /*#__PURE__*/external_React_default().createElement("p", {
+ className: "empty-state-message"
+ })))), id === "topstories" && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "top-stories-bottom-container"
+ }, shouldShowTopics && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "wrapper-topics"
+ }, /*#__PURE__*/external_React_default().createElement(Topics, {
+ topics: this.props.topics
+ })), shouldShowPocketCta && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "wrapper-cta"
+ }, /*#__PURE__*/external_React_default().createElement(PocketLoggedInCta, null)), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "wrapper-more-recommendations"
+ }, shouldShowReadMore && /*#__PURE__*/external_React_default().createElement(MoreRecommendations, {
+ read_more_endpoint: read_more_endpoint
+ })))));
+ }
+
+}
+Section.defaultProps = {
+ document: __webpack_require__.g.document,
+ rows: [],
+ emptyState: {},
+ pref: {},
+ title: ""
+};
+const SectionIntl = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Prefs: state.Prefs,
+ Pocket: state.Pocket
+}))(Section);
+class _Sections extends (external_React_default()).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( /*#__PURE__*/external_React_default().createElement(TopSites_TopSites, commonProps));
+ } else {
+ const section = enabledSections.find(s => s.id === sectionId);
+
+ if (section) {
+ sections.push( /*#__PURE__*/external_React_default().createElement(SectionIntl, Sections_extends({}, section, commonProps)));
+ }
+ }
+ }
+
+ return sections;
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "sections-list"
+ }, this.renderSections());
+ }
+
+}
+const Sections_Sections = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Sections: state.Sections,
+ Prefs: state.Prefs
+}))(_Sections);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/Highlights/Highlights.jsx
+function Highlights_extends() { Highlights_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 Highlights_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 (external_React_default()).PureComponent {
+ render() {
+ const section = this.props.Sections.find(s => s.id === "highlights");
+
+ if (!section || !section.enabled) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-highlights sections-list"
+ }, /*#__PURE__*/external_React_default().createElement(SectionIntl, Highlights_extends({}, section, {
+ isFixed: true
+ })));
+ }
+
+}
+const Highlights = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Sections: state.Sections
+}))(_Highlights);
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule.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 HorizontalRule extends (external_React_default()).PureComponent {
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("hr", {
+ className: "ds-hr"
+ });
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/Navigation/Navigation.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 Navigation_Topic extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ action_position: 0,
+ value: {
+ topic: event.target.text.toLowerCase().replace(` `, `-`)
+ }
+ }));
+ }
+ }
+
+ render() {
+ const {
+ url,
+ name
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ onLinkClick: this.onLinkClick,
+ className: this.props.className,
+ url: url
+ }, name);
+ }
+
+}
+class Navigation extends (external_React_default()).PureComponent {
+ render() {
+ let links = this.props.links || [];
+ const alignment = this.props.alignment || "centered";
+ const header = this.props.header || {};
+ const english = this.props.locale.startsWith("en-");
+ const privacyNotice = this.props.privacyNoticeURL || {};
+ const {
+ newFooterSection
+ } = this.props;
+ const className = `ds-navigation ds-navigation-${alignment} ${newFooterSection ? `ds-navigation-new-topics` : ``}`;
+ let {
+ title
+ } = header;
+
+ if (newFooterSection) {
+ title = {
+ id: "newtab-pocket-new-topics-title"
+ };
+
+ if (this.props.extraLinks) {
+ links = [...links.slice(0, links.length - 1), ...this.props.extraLinks, links[links.length - 1]];
+ }
+ }
+
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: className
+ }, title && english ? /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: title
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "ds-navigation-header"
+ })) : null, english ? /*#__PURE__*/external_React_default().createElement("ul", null, links && links.map(t => /*#__PURE__*/external_React_default().createElement("li", {
+ key: t.name
+ }, /*#__PURE__*/external_React_default().createElement(Navigation_Topic, {
+ url: t.url,
+ name: t.name,
+ dispatch: this.props.dispatch
+ })))) : null, !newFooterSection ? /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ className: "ds-navigation-privacy",
+ url: privacyNotice.url
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: privacyNotice.title
+ })) : null, newFooterSection ? /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-navigation-family"
+ }, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon firefox-logo"
+ }), /*#__PURE__*/external_React_default().createElement("span", null, "|"), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "icon pocket-logo"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "ds-navigation-family-message",
+ "data-l10n-id": "newtab-pocket-pocket-firefox-family"
+ })) : null);
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink.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 PrivacyLink extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ properties
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-privacy-link"
+ }, /*#__PURE__*/external_React_default().createElement(SafeAnchor, {
+ url: properties.url
+ }, /*#__PURE__*/external_React_default().createElement(FluentOrText, {
+ message: properties.title
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle.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 SectionTitle extends (external_React_default()).PureComponent {
+ render() {
+ const {
+ header: {
+ title,
+ subtitle
+ }
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-section-title"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "title"
+ }, title), subtitle ? /*#__PURE__*/external_React_default().createElement("div", {
+ className: "subtitle"
+ }, subtitle) : null);
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/lib/selectLayoutRender.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/. */
+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", "HorizontalRule", "PrivacyLink"];
+ const filterArray = [];
+
+ if (!prefs["feeds.topsites"]) {
+ filterArray.push("TopSites");
+ }
+
+ 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
+ };
+};
+;// CONCATENATED MODULE: ./content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.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_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 (external_React_default()).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}`);
+ 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}`);
+ }
+ });
+ });
+ });
+ }
+
+ renderComponent(component, embedWidth) {
+ var _component$header;
+
+ switch (component.type) {
+ case "Highlights":
+ return /*#__PURE__*/external_React_default().createElement(Highlights, null);
+
+ case "TopSites":
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-top-sites"
+ }, /*#__PURE__*/external_React_default().createElement(TopSites_TopSites, {
+ isFixed: true,
+ title: (_component$header = component.header) === null || _component$header === void 0 ? void 0 : _component$header.title
+ }));
+
+ case "TextPromo":
+ return /*#__PURE__*/external_React_default().createElement(DSTextPromo, {
+ dispatch: this.props.dispatch,
+ type: component.type,
+ data: component.data
+ });
+
+ case "Signup":
+ return /*#__PURE__*/external_React_default().createElement(DSSignup, {
+ dispatch: this.props.dispatch,
+ type: component.type,
+ data: component.data
+ });
+
+ case "Message":
+ return /*#__PURE__*/external_React_default().createElement(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,
+ essentialReadsHeader: component.essentialReadsHeader,
+ editorsPicksHeader: component.editorsPicksHeader
+ });
+
+ case "SectionTitle":
+ return /*#__PURE__*/external_React_default().createElement(SectionTitle, {
+ header: component.header
+ });
+
+ case "Navigation":
+ return /*#__PURE__*/external_React_default().createElement(Navigation, {
+ dispatch: this.props.dispatch,
+ links: component.properties.links,
+ extraLinks: component.properties.extraLinks,
+ alignment: component.properties.alignment,
+ explore_topics: component.properties.explore_topics,
+ header: component.header,
+ locale: this.props.App.locale,
+ newFooterSection: component.newFooterSection,
+ privacyNoticeURL: component.properties.privacyNoticeURL
+ });
+
+ case "CollectionCardGrid":
+ const {
+ DiscoveryStream
+ } = this.props;
+ return /*#__PURE__*/external_React_default().createElement(CollectionCardGrid, {
+ data: component.data,
+ feed: component.feed,
+ spocs: DiscoveryStream.spocs,
+ placement: component.placement,
+ type: component.type,
+ items: component.properties.items,
+ dismissible: this.props.DiscoveryStream.isCollectionDismissible,
+ dispatch: this.props.dispatch
+ });
+
+ case "CardGrid":
+ return /*#__PURE__*/external_React_default().createElement(CardGrid, {
+ title: component.header && component.header.title,
+ data: component.data,
+ feed: component.feed,
+ widgets: component.widgets,
+ type: component.type,
+ dispatch: this.props.dispatch,
+ items: component.properties.items,
+ hybridLayout: component.properties.hybridLayout,
+ hideCardBackground: component.properties.hideCardBackground,
+ fourCardLayout: component.properties.fourCardLayout,
+ compactGrid: component.properties.compactGrid,
+ essentialReadsHeader: component.properties.essentialReadsHeader,
+ onboardingExperience: component.properties.onboardingExperience,
+ editorsPicksHeader: component.properties.editorsPicksHeader,
+ recentSavesEnabled: this.props.DiscoveryStream.recentSavesEnabled,
+ hideDescriptions: this.props.DiscoveryStream.hideDescriptions
+ });
+
+ case "HorizontalRule":
+ return /*#__PURE__*/external_React_default().createElement(HorizontalRule, null);
+
+ case "PrivacyLink":
+ return /*#__PURE__*/external_React_default().createElement(PrivacyLink, {
+ properties: component.properties
+ });
+
+ default:
+ return /*#__PURE__*/external_React_default().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 /*#__PURE__*/external_React_default().createElement("style", {
+ key: json,
+ "data-styles": json,
+ ref: this.onStyleMount
+ });
+ }
+
+ render() {
+ const {
+ locale
+ } = this.props; // Select layout render data by adding spocs and position to recommendations
+
+ const {
+ layoutRender
+ } = selectLayoutRender({
+ state: this.props.DiscoveryStream,
+ prefs: this.props.Prefs.values,
+ 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
+ }
+ };
+ const privacyLinkComponent = extractComponent("PrivacyLink");
+ let learnMore = {
+ link: {
+ href: message.header.link_url,
+ message: message.header.link_text
+ }
+ };
+ let sectionTitle = message.header.title;
+ let subTitle = ""; // If we're in one of these experiments, override the default message.
+ // For now this is English only.
+
+ if (message.essentialReadsHeader || message.editorsPicksHeader) {
+ learnMore = null;
+ subTitle = "Recommended By Pocket";
+
+ if (message.essentialReadsHeader) {
+ sectionTitle = "Today’s Essential Reads";
+ } else if (message.editorsPicksHeader) {
+ sectionTitle = "Editor’s Picks";
+ }
+ } // Render a DS-style TopSites then the rest if any in a collapsible section
+
+
+ return /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, this.props.DiscoveryStream.isPrivacyInfoModalVisible && /*#__PURE__*/external_React_default().createElement(DSPrivacyModal, {
+ dispatch: this.props.dispatch
+ }), topSites && this.renderLayout([{
+ width: 12,
+ components: [topSites]
+ }]), sponsoredCollection && this.renderLayout([{
+ width: 12,
+ components: [sponsoredCollection]
+ }]), !!layoutRender.length && /*#__PURE__*/external_React_default().createElement(CollapsibleSection, {
+ className: "ds-layout",
+ collapsed: topStories.pref.collapsed,
+ dispatch: this.props.dispatch,
+ id: topStories.id,
+ isFixed: true,
+ learnMore: learnMore,
+ privacyNoticeURL: topStories.privacyNoticeURL,
+ showPrefName: topStories.pref.feed,
+ title: sectionTitle,
+ subTitle: subTitle,
+ eventSource: "CARDGRID"
+ }, this.renderLayout(layoutRender)), this.renderLayout([{
+ width: 12,
+ components: [{
+ type: "Highlights"
+ }]
+ }]), privacyLinkComponent && this.renderLayout([{
+ width: 12,
+ components: [privacyLinkComponent]
+ }]));
+ }
+
+ renderLayout(layoutRender) {
+ const styles = [];
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "discovery-stream ds-layout"
+ }, layoutRender.map((row, rowIndex) => /*#__PURE__*/external_React_default().createElement("div", {
+ key: `row-${rowIndex}`,
+ className: `ds-column ds-column-${row.width}`
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "ds-column-grid"
+ }, row.components.map((component, componentIndex) => {
+ if (!component) {
+ return null;
+ }
+
+ styles[rowIndex] = [...(styles[rowIndex] || []), component.styles];
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ key: `component-${componentIndex}`
+ }, this.renderComponent(component, row.width));
+ })))), this.renderStyles(styles));
+ }
+
+}
+const DiscoveryStreamBase = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ document: __webpack_require__.g.document,
+ App: state.App
+}))(_DiscoveryStreamBase);
+;// 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 extends (external_React_default()).PureComponent {
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", null);
+ }
+
+}
+;// 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 extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onPreferenceSelect = this.onPreferenceSelect.bind(this); // Refs are necessary for dynamically measuring drawer heights for slide animations
+
+ this.topSitesDrawerRef = /*#__PURE__*/external_React_default().createRef();
+ this.pocketDrawerRef = /*#__PURE__*/external_React_default().createRef();
+ }
+
+ inputUserEvent(eventSource, status) {
+ this.props.dispatch(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"); // TOP_SITES, TOP_STORIES, HIGHLIGHTS
+
+ 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);
+ }
+
+ componentDidMount() {
+ this.setDrawerMargins();
+ }
+
+ componentDidUpdate() {
+ this.setDrawerMargins();
+ }
+
+ setDrawerMargins() {
+ this.setDrawerMargin(`TOP_SITES`, this.props.enabledSections.topSitesEnabled);
+ this.setDrawerMargin(`TOP_STORIES`, this.props.enabledSections.pocketEnabled);
+ }
+
+ setDrawerMargin(drawerID, isOpen) {
+ let drawerRef;
+
+ if (drawerID === `TOP_SITES`) {
+ drawerRef = this.topSitesDrawerRef.current;
+ } else if (drawerID === `TOP_STORIES`) {
+ drawerRef = this.pocketDrawerRef.current;
+ } else {
+ return;
+ }
+
+ let drawerHeight;
+
+ if (drawerRef) {
+ var _window$getComputedSt;
+
+ drawerHeight = parseFloat((_window$getComputedSt = window.getComputedStyle(drawerRef)) === null || _window$getComputedSt === void 0 ? void 0 : _window$getComputedSt.height);
+
+ if (isOpen) {
+ drawerRef.style.marginTop = `0`;
+ } else {
+ drawerRef.style.marginTop = `-${drawerHeight}px`;
+ }
+ }
+ }
+
+ render() {
+ const {
+ enabledSections,
+ mayHaveSponsoredTopSites,
+ pocketRegion,
+ mayHaveSponsoredStories,
+ mayHaveRecentSaves,
+ openPreferences
+ } = this.props;
+ const {
+ topSitesEnabled,
+ pocketEnabled,
+ highlightsEnabled,
+ showSponsoredTopSitesEnabled,
+ showSponsoredPocketEnabled,
+ showRecentSavesEnabled,
+ topSitesRowsCount
+ } = enabledSections;
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "home-section"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ id: "shortcuts-section",
+ className: "section"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ className: "switch"
+ }, /*#__PURE__*/external_React_default().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"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("h2", {
+ id: "custom-shortcuts-title",
+ className: "title"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: "shortcuts-toggle",
+ "data-l10n-id": "newtab-custom-shortcuts-title"
+ })), /*#__PURE__*/external_React_default().createElement("p", {
+ id: "custom-shortcuts-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-shortcuts-subtitle"
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "more-info-top-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "more-information",
+ ref: this.topSitesDrawerRef
+ }, /*#__PURE__*/external_React_default().createElement("select", {
+ id: "row-selector",
+ className: "selector",
+ name: "row-count",
+ preference: "topSitesRows",
+ value: topSitesRowsCount,
+ onChange: this.onPreferenceSelect,
+ disabled: !topSitesEnabled,
+ "aria-labelledby": "custom-shortcuts-title"
+ }, /*#__PURE__*/external_React_default().createElement("option", {
+ value: "1",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 1}"
+ }), /*#__PURE__*/external_React_default().createElement("option", {
+ value: "2",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 2}"
+ }), /*#__PURE__*/external_React_default().createElement("option", {
+ value: "3",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 3}"
+ }), /*#__PURE__*/external_React_default().createElement("option", {
+ value: "4",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 4}"
+ })), mayHaveSponsoredTopSites && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "check-wrapper",
+ role: "presentation"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ id: "sponsored-shortcuts",
+ className: "sponsored-checkbox",
+ disabled: !topSitesEnabled,
+ checked: showSponsoredTopSitesEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "showSponsoredTopSites",
+ eventSource: "SPONSORED_TOP_SITES"
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ className: "sponsored",
+ htmlFor: "sponsored-shortcuts",
+ "data-l10n-id": "newtab-custom-sponsored-sites"
+ })))))), pocketRegion && /*#__PURE__*/external_React_default().createElement("div", {
+ id: "pocket-section",
+ className: "section"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ className: "switch"
+ }, /*#__PURE__*/external_React_default().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"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("h2", {
+ id: "custom-pocket-title",
+ className: "title"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: "pocket-toggle",
+ "data-l10n-id": "newtab-custom-pocket-title"
+ })), /*#__PURE__*/external_React_default().createElement("p", {
+ id: "custom-pocket-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-pocket-subtitle"
+ }), (mayHaveSponsoredStories || mayHaveRecentSaves) && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "more-info-pocket-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "more-information",
+ ref: this.pocketDrawerRef
+ }, mayHaveSponsoredStories && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "check-wrapper",
+ role: "presentation"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ id: "sponsored-pocket",
+ className: "sponsored-checkbox",
+ disabled: !pocketEnabled,
+ checked: showSponsoredPocketEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "showSponsored",
+ eventSource: "POCKET_SPOCS"
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ className: "sponsored",
+ htmlFor: "sponsored-pocket",
+ "data-l10n-id": "newtab-custom-pocket-sponsored"
+ })), mayHaveRecentSaves && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "check-wrapper",
+ role: "presentation"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ id: "recent-saves-pocket",
+ className: "sponsored-checkbox",
+ disabled: !pocketEnabled,
+ checked: showRecentSavesEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "showRecentSaves",
+ eventSource: "POCKET_RECENT_SAVES"
+ }), /*#__PURE__*/external_React_default().createElement("label", {
+ className: "sponsored",
+ htmlFor: "recent-saves-pocket",
+ "data-l10n-id": "newtab-custom-pocket-show-recent-saves"
+ })))))), /*#__PURE__*/external_React_default().createElement("div", {
+ id: "recent-section",
+ className: "section"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ className: "switch"
+ }, /*#__PURE__*/external_React_default().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"
+ }), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("h2", {
+ id: "custom-recent-title",
+ className: "title"
+ }, /*#__PURE__*/external_React_default().createElement("label", {
+ htmlFor: "highlights-toggle",
+ "data-l10n-id": "newtab-custom-recent-title"
+ })), /*#__PURE__*/external_React_default().createElement("p", {
+ id: "custom-recent-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-recent-subtitle"
+ }))), /*#__PURE__*/external_React_default().createElement("span", {
+ className: "divider",
+ role: "separator"
+ }), /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement("button", {
+ id: "settings-link",
+ className: "external-link",
+ onClick: openPreferences,
+ "data-l10n-id": "newtab-custom-settings"
+ })));
+ }
+
+}
+;// CONCATENATED MODULE: ./content-src/components/CustomizeMenu/CustomizeMenu.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 _CustomizeMenu extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEntered = this.onEntered.bind(this);
+ this.onExited = this.onExited.bind(this);
+ }
+
+ onEntered() {
+ if (this.closeButton) {
+ this.closeButton.focus();
+ }
+ }
+
+ onExited() {
+ if (this.openButton) {
+ this.openButton.focus();
+ }
+ }
+
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("span", null, /*#__PURE__*/external_React_default().createElement(external_ReactTransitionGroup_namespaceObject.CSSTransition, {
+ timeout: 300,
+ classNames: "personalize-animate",
+ in: !this.props.showing,
+ appear: true
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ className: "icon icon-settings personalize-button",
+ onClick: () => this.props.onOpen(),
+ "data-l10n-id": "newtab-personalize-icon-label",
+ ref: c => this.openButton = c
+ })), /*#__PURE__*/external_React_default().createElement(external_ReactTransitionGroup_namespaceObject.CSSTransition, {
+ timeout: 250,
+ classNames: "customize-animate",
+ in: this.props.showing,
+ onEntered: this.onEntered,
+ onExited: this.onExited,
+ appear: true
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "customize-menu",
+ role: "dialog",
+ "data-l10n-id": "newtab-personalize-dialog-label"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ onClick: () => this.props.onClose(),
+ className: "close-button",
+ "data-l10n-id": "newtab-custom-close-button",
+ ref: c => this.closeButton = c
+ }), /*#__PURE__*/external_React_default().createElement(BackgroundsSection, null), /*#__PURE__*/external_React_default().createElement(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,
+ mayHaveRecentSaves: this.props.DiscoveryStream.recentSavesEnabled,
+ dispatch: this.props.dispatch
+ }))));
+ }
+
+}
+const CustomizeMenu = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ DiscoveryStream: state.DiscoveryStream
+}))(_CustomizeMenu);
+;// CONCATENATED MODULE: ./content-src/components/Search/Search.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/. */
+
+/* globals ContentSearchUIController, ContentSearchHandoffUIController */
+
+
+function Search_extends() { Search_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 Search_extends.apply(this, arguments); }
+
+
+
+
+
+class _Search extends (external_React_default()).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(actionCreators.UserEvent({
+ event: "SEARCH"
+ }));
+ }
+ }
+
+ onSearchClick(event) {
+ window.gContentSearchController.search(event);
+ }
+
+ doSearchHandoff(text) {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.HANDOFF_SEARCH_TO_AWESOMEBAR,
+ data: {
+ text
+ }
+ }));
+ this.props.dispatch({
+ type: actionTypes.FAKE_FOCUS_SEARCH
+ });
+ this.props.dispatch(actionCreators.UserEvent({
+ event: "SEARCH_HANDOFF"
+ }));
+
+ if (text) {
+ this.props.dispatch({
+ type: actionTypes.DISABLE_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 us set the search icon and reacts to
+ // changes to default engine to keep everything in sync.
+ this._handoffSearchController = new ContentSearchHandoffUIController();
+ }
+ }
+
+ getDefaultEngineName() {
+ // _handoffSearchController will manage engine names once it is initialized.
+ return this.props.Prefs.values["urlbar.placeholderName"];
+ }
+
+ getHandoffInputL10nAttributes() {
+ let defaultEngineName = this.getDefaultEngineName();
+ return defaultEngineName ? {
+ "data-l10n-id": "newtab-search-box-handoff-input",
+ "data-l10n-args": `{"engine": "${defaultEngineName}"}`
+ } : {
+ "data-l10n-id": "newtab-search-box-handoff-input-no-engine"
+ };
+ }
+
+ getHandoffTextL10nAttributes() {
+ let defaultEngineName = this.getDefaultEngineName();
+ return defaultEngineName ? {
+ "data-l10n-id": "newtab-search-box-handoff-text",
+ "data-l10n-args": `{"engine": "${defaultEngineName}"}`
+ } : {
+ "data-l10n-id": "newtab-search-box-handoff-text-no-engine"
+ };
+ }
+
+ 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.disable && "search-disabled", this.props.fakeFocus && "fake-focus"].filter(v => v).join(" ");
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: wrapperClassName
+ }, this.props.showLogo && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "logo-and-wordmark"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "logo"
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "wordmark"
+ })), !this.props.handoffEnabled && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "search-inner-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement("input", {
+ id: "newtab-search-text",
+ "data-l10n-id": "newtab-search-box-input",
+ maxLength: "256",
+ ref: this.onInputMount,
+ type: "search"
+ }), /*#__PURE__*/external_React_default().createElement("button", {
+ id: "searchSubmit",
+ className: "search-button",
+ "data-l10n-id": "newtab-search-box-search-button",
+ onClick: this.onSearchClick
+ })), this.props.handoffEnabled && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "search-inner-wrapper"
+ }, /*#__PURE__*/external_React_default().createElement("button", Search_extends({
+ className: "search-handoff-button"
+ }, this.getHandoffInputL10nAttributes(), {
+ ref: this.onSearchHandoffButtonMount,
+ onClick: this.onSearchHandoffClick,
+ tabIndex: "-1"
+ }), /*#__PURE__*/external_React_default().createElement("div", Search_extends({
+ className: "fake-textbox"
+ }, this.getHandoffTextL10nAttributes())), /*#__PURE__*/external_React_default().createElement("input", {
+ type: "search",
+ className: "fake-editable",
+ tabIndex: "-1",
+ "aria-hidden": "true",
+ onDrop: this.onSearchHandoffDrop,
+ onPaste: this.onSearchHandoffPaste,
+ ref: this.onInputMountHandoff
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: "fake-caret"
+ }))));
+ }
+
+}
+const Search_Search = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Prefs: state.Prefs
+}))(_Search);
+;// CONCATENATED MODULE: ./content-src/components/Base/Base.jsx
+function Base_extends() { Base_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 Base_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
+}) => /*#__PURE__*/external_React_default().createElement("div", {
+ className: "prefs-button"
+}, /*#__PURE__*/external_React_default().createElement("button", {
+ className: `icon ${icon || "icon-settings"}`,
+ onClick: onClick,
+ "data-l10n-id": "newtab-settings-button"
+})); // 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 (external_React_default()).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(" ");
+ __webpack_require__.g.document.body.className = bodyClassName;
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ App
+ } = props;
+ const isDevtoolsEnabled = props.Prefs.values["asrouter.devtoolsEnabled"];
+
+ if (!App.initialized) {
+ return null;
+ }
+
+ return /*#__PURE__*/external_React_default().createElement(ErrorBoundary, {
+ className: "base-content-fallback"
+ }, /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement(BaseContent, Base_extends({}, this.props, {
+ adminContent: this.state
+ })), isDevtoolsEnabled ? /*#__PURE__*/external_React_default().createElement(ASRouterAdmin, {
+ notifyContent: this.notifyContent
+ }) : null));
+ }
+
+}
+class BaseContent extends (external_React_default()).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
+ };
+ }
+
+ componentDidMount() {
+ __webpack_require__.g.addEventListener("scroll", this.onWindowScroll);
+ __webpack_require__.g.addEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ componentWillUnmount() {
+ __webpack_require__.g.removeEventListener("scroll", this.onWindowScroll);
+ __webpack_require__.g.removeEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ onWindowScroll() {
+ const prefs = this.props.Prefs.values;
+ const SCROLL_THRESHOLD = prefs["logowordmark.alwaysVisible"] ? 179 : 34;
+
+ if (__webpack_require__.g.scrollY > SCROLL_THRESHOLD && !this.state.fixedSearch) {
+ this.setState({
+ fixedSearch: true
+ });
+ } else if (__webpack_require__.g.scrollY <= SCROLL_THRESHOLD && this.state.fixedSearch) {
+ this.setState({
+ fixedSearch: false
+ });
+ }
+ }
+
+ openPreferences() {
+ this.props.dispatch(actionCreators.OnlyToMain({
+ type: actionTypes.SETTINGS_OPEN
+ }));
+ this.props.dispatch(actionCreators.UserEvent({
+ event: "OPEN_NEWTAB_PREFS"
+ }));
+ }
+
+ openCustomizationMenu() {
+ this.props.dispatch({
+ type: actionTypes.SHOW_PERSONALIZE
+ });
+ this.props.dispatch(actionCreators.UserEvent({
+ event: "SHOW_PERSONALIZE"
+ }));
+ }
+
+ closeCustomizationMenu() {
+ if (this.props.App.customizeMenuVisible) {
+ this.props.dispatch({
+ type: actionTypes.HIDE_PERSONALIZE
+ });
+ this.props.dispatch(actionCreators.UserEvent({
+ event: "HIDE_PERSONALIZE"
+ }));
+ }
+ }
+
+ handleOnKeyDown(e) {
+ if (e.key === "Escape") {
+ this.closeCustomizationMenu();
+ }
+ }
+
+ setPref(pref, value) {
+ this.props.dispatch(actionCreators.SetPref(pref, value));
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ App
+ } = props;
+ const {
+ initialized,
+ customizeMenuVisible
+ } = App;
+ const prefs = props.Prefs.values;
+ 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 enabledSections = {
+ topSitesEnabled: prefs["feeds.topsites"],
+ pocketEnabled: prefs["feeds.section.topstories"],
+ highlightsEnabled: prefs["feeds.section.highlights"],
+ showSponsoredTopSitesEnabled: prefs.showSponsoredTopSites,
+ showSponsoredPocketEnabled: prefs.showSponsored,
+ showRecentSavesEnabled: prefs.showRecentSaves,
+ 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"].filter(v => v).join(" ");
+ const hasSnippet = prefs["feeds.snippets"] && this.props.adminContent && this.props.adminContent.message && this.props.adminContent.message.id;
+ return /*#__PURE__*/external_React_default().createElement("div", null, /*#__PURE__*/external_React_default().createElement(CustomizeMenu, {
+ onClose: this.closeCustomizationMenu,
+ onOpen: this.openCustomizationMenu,
+ openPreferences: this.openPreferences,
+ setPref: this.setPref,
+ enabledSections: enabledSections,
+ pocketRegion: pocketRegion,
+ mayHaveSponsoredTopSites: mayHaveSponsoredTopSites,
+ showing: customizeMenuVisible
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: outerClassName,
+ onClick: this.closeCustomizationMenu
+ }, /*#__PURE__*/external_React_default().createElement("main", {
+ className: hasSnippet ? "has-snippet" : ""
+ }, prefs.showSearch && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "non-collapsible-section"
+ }, /*#__PURE__*/external_React_default().createElement(ErrorBoundary, null, /*#__PURE__*/external_React_default().createElement(Search_Search, Base_extends({
+ showLogo: noSectionsEnabled || prefs["logowordmark.alwaysVisible"],
+ handoffEnabled: searchHandoffEnabled
+ }, props.Search)))), /*#__PURE__*/external_React_default().createElement(ASRouterUISurface, {
+ adminContent: this.props.adminContent,
+ appUpdateChannel: this.props.Prefs.values.appUpdateChannel,
+ fxaEndpoint: this.props.Prefs.values.fxa_endpoint,
+ dispatch: this.props.dispatch
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: `body-wrapper${initialized ? " on" : ""}`
+ }, isDiscoveryStream ? /*#__PURE__*/external_React_default().createElement(ErrorBoundary, {
+ className: "borderless-error"
+ }, /*#__PURE__*/external_React_default().createElement(DiscoveryStreamBase, {
+ locale: props.App.locale
+ })) : /*#__PURE__*/external_React_default().createElement(Sections_Sections, null)), /*#__PURE__*/external_React_default().createElement(ConfirmDialog, null))));
+ }
+
+}
+const Base = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ App: state.App,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Search: state.Search
+}))(_Base);
+;// CONCATENATED MODULE: ./content-src/lib/detect-user-session-start.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/. */
+
+
+const detect_user_session_start_VISIBLE = "visible";
+const detect_user_session_start_VISIBILITY_CHANGE_EVENT = "visibilitychange";
+class DetectUserSessionStart {
+ constructor(store, options = {}) {
+ this._store = store; // Overrides for testing
+
+ this.document = options.document || __webpack_require__.g.document;
+ this._perfService = options.perfService || 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 === detect_user_session_start_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(detect_user_session_start_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(actionCreators.AlsoToMain({
+ type: 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 === detect_user_session_start_VISIBLE) {
+ this._sendEvent();
+
+ this.document.removeEventListener(detect_user_session_start_VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+}
+;// CONCATENATED MODULE: external "Redux"
+const external_Redux_namespaceObject = Redux;
+;// CONCATENATED MODULE: ./content-src/lib/init-store.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/. */
+
+/* eslint-env mozilla/remote-page */
+
+
+const MERGE_STORE_ACTION = "NEW_TAB_INITIAL_STATE";
+const OUTGOING_MESSAGE_NAME = "ActivityStream:ContentToMain";
+const INCOMING_MESSAGE_NAME = "ActivityStream:MainToContent";
+const EARLY_QUEUED_ACTIONS = [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 (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 === 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 === actionTypes.INIT) {
+ return next(actionCreators.AlsoToMain({
+ type: actionTypes.NEW_TAB_STATE_REQUEST
+ }));
+ }
+
+ if (actionUtils.isBroadcastToContent(action) || actionUtils.isSendToOneContent(action) || 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 (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 = (0,external_Redux_namespaceObject.createStore)(mergeStateReducer((0,external_Redux_namespaceObject.combineReducers)(reducers)), initialState, __webpack_require__.g.RPMAddMessageListener && (0,external_Redux_namespaceObject.applyMiddleware)(queueEarlyMessageMiddleware, rehydrationMiddleware, messageMiddleware));
+
+ if (__webpack_require__.g.RPMAddMessageListener) {
+ __webpack_require__.g.RPMAddMessageListener(INCOMING_MESSAGE_NAME, msg => {
+ try {
+ store.dispatch(msg.data);
+ } catch (ex) {
+ console.error("Content msg:", msg, "Dispatch error: ", ex);
+ dump(`Content msg: ${JSON.stringify(msg)}\nDispatch error: ${ex}\n${ex.stack}`);
+ }
+ });
+ }
+
+ return store;
+}
+;// CONCATENATED MODULE: ./content-src/activity-stream.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 NewTab = ({
+ store
+}) => /*#__PURE__*/external_React_default().createElement(external_ReactRedux_namespaceObject.Provider, {
+ store: store
+}, /*#__PURE__*/external_React_default().createElement(Base, null));
+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(actionCreators.AlsoToMain({
+ type: actionTypes.NEW_TAB_STATE_REQUEST
+ }));
+ }
+ }
+
+ if (document.hidden) {
+ requestIdleCallbackId = requestIdleCallback(doRequest);
+ addEventListener("visibilitychange", doRequest, {
+ once: true
+ });
+ } else {
+ doRequest();
+ }
+
+ external_ReactDOM_default().hydrate( /*#__PURE__*/external_React_default().createElement(NewTab, {
+ store: store
+ }), document.getElementById("root"));
+}
+function renderCache(initialState) {
+ const store = initStore(reducers, initialState);
+ new DetectUserSessionStart(store).sendEventOrAddListener();
+ external_ReactDOM_default().hydrate( /*#__PURE__*/external_React_default().createElement(NewTab, {
+ store: store
+ }), document.getElementById("root"));
+}
+NewtabRenderUtils = __webpack_exports__;
+/******/ })()
+; \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/confetti.svg b/browser/components/newtab/data/content/assets/confetti.svg
new file mode 100644
index 0000000000..e00cd95120
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/confetti.svg
@@ -0,0 +1,55 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.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="574" height="210" xmlns="http://www.w3.org/2000/svg">
+<path d="M569.854 103.202C564.294 103.202 559.781 98.6802 559.781 93.1295C559.781 87.5788 564.303 83.0566 569.854 83.0566C575.413 83.0566 579.926 87.5788 579.926 93.1295C579.926 98.6802 575.404 103.202 569.854 103.202ZM569.854 83.9345C564.791 83.9345 560.668 88.0576 560.668 93.1206C560.668 98.1837 564.791 102.307 569.854 102.307C574.917 102.307 579.039 98.1837 579.039 93.1206C579.039 88.0576 574.917 83.9345 569.854 83.9345Z" fill="#FFF4DE"/>
+<path d="M577.231 23.4883C574.642 23.4883 572.531 21.378 572.531 18.7888C572.531 16.1997 574.642 14.0894 577.231 14.0894C579.82 14.0894 581.93 16.1997 581.93 18.7888C581.93 21.378 579.82 23.4883 577.231 23.4883ZM577.231 14.9761C575.129 14.9761 573.418 16.6874 573.418 18.7888C573.418 20.8903 575.129 22.6016 577.231 22.6016C579.332 22.6016 581.043 20.8903 581.043 18.7888C581.043 16.6874 579.332 14.9761 577.231 14.9761Z" fill="#F68FFF"/>
+<path d="M561.395 60.6054C558.806 60.6054 556.695 58.4951 556.695 55.9059C556.695 53.3168 558.806 51.2064 561.395 51.2064C563.984 51.2064 566.094 53.3168 566.094 55.9059C566.094 58.4951 563.984 60.6054 561.395 60.6054Z" fill="#F770FF"/>
+<path d="M498.691 109.897C496.102 109.897 493.992 107.787 493.992 105.197C493.992 102.608 496.102 100.498 498.691 100.498C501.281 100.498 503.391 102.608 503.391 105.197C503.391 107.787 501.281 109.897 498.691 109.897ZM498.691 101.385C496.59 101.385 494.879 103.096 494.879 105.197C494.879 107.299 496.59 109.01 498.691 109.01C500.793 109.01 502.504 107.299 502.504 105.197C502.504 103.096 500.793 101.385 498.691 101.385Z" fill="#073072"/>
+<path d="M499.471 57.8478C499.205 57.8478 498.939 57.8301 498.673 57.7946C495.569 57.3601 493.37 54.4872 493.769 51.3749L495.782 35.6538C495.977 34.1109 496.766 32.7543 498.008 31.8232C499.24 30.8922 500.774 30.5109 502.308 30.7415L517.975 33.1533C521.07 33.6321 523.224 36.5405 522.79 39.635C522.577 41.1602 521.779 42.4991 520.547 43.4124C519.314 44.3257 517.798 44.6981 516.282 44.4675L506.395 42.9513L505.128 52.8734C504.932 54.3985 504.152 55.7463 502.937 56.6773C501.918 57.4488 500.712 57.8478 499.471 57.8478ZM501.412 31.5661C500.375 31.5661 499.373 31.903 498.531 32.5326C497.485 33.3218 496.82 34.4656 496.651 35.769L494.638 51.4902C494.301 54.1148 496.163 56.5532 498.788 56.9168C500.074 57.0941 501.35 56.766 502.379 55.9769C503.407 55.1877 504.064 54.0527 504.232 52.7581L505.615 41.9316L516.397 43.5897C517.674 43.7848 518.959 43.4744 519.997 42.703C521.034 41.9316 521.708 40.7966 521.894 39.5109C522.267 36.8863 520.44 34.4301 517.824 34.0311L502.157 31.6193C501.909 31.5838 501.661 31.5661 501.412 31.5661Z" fill="#FF4AA2"/>
+<path d="M530.708 98.0773C529.316 98.0773 527.915 97.9 526.541 97.5364C522.285 96.428 518.712 93.7325 516.486 89.9374C511.893 82.1079 514.518 71.9996 522.347 67.4065C525.096 65.7927 528.687 66.6882 530.345 69.4104L530.442 69.5789C532.012 72.3542 531.107 75.8301 528.385 77.4882L528.234 77.5769C526.053 78.9069 525.335 81.7798 526.63 83.9788C527.924 86.1778 530.779 86.9493 533.005 85.6902L533.155 85.6015C535.931 84.032 539.504 84.9897 541.118 87.7384C542.758 90.5315 541.818 94.1404 539.025 95.7808C536.454 97.3059 533.599 98.0773 530.708 98.0773ZM525.309 67.4952C524.448 67.4952 523.588 67.7168 522.799 68.1779C515.396 72.5316 512.904 82.0902 517.258 89.4941C519.368 93.0852 522.737 95.63 526.771 96.6852C530.797 97.7315 534.991 97.1463 538.582 95.0448C540.958 93.6527 541.747 90.5847 540.355 88.2172C538.981 85.8852 535.957 85.0695 533.599 86.3995L533.448 86.4882C530.806 87.9867 527.401 87.0734 525.867 84.4488C524.333 81.833 525.184 78.4192 527.782 76.8409L527.933 76.7523C530.238 75.3424 531.01 72.3986 529.68 70.04L529.591 69.8892C528.651 68.3464 526.993 67.4952 525.309 67.4952Z" fill="#FFFF98"/>
+<path d="M543.095 28.5248C542.075 28.5248 541.037 28.2588 540.098 27.7002L524.838 18.6027C522.107 16.9712 521.167 13.4067 522.755 10.649L522.852 10.4806C524.528 7.77613 528.11 6.90717 530.841 8.52982L546.1 17.6273C547.448 18.4254 548.397 19.7111 548.778 21.2273C549.159 22.7436 548.929 24.3219 548.131 25.6697C547.04 27.5051 545.09 28.5248 543.095 28.5248ZM523.615 10.9416L523.526 11.0835C522.178 13.4244 522.976 16.448 525.29 17.8313L540.55 26.9288C542.908 28.3298 545.967 27.5583 547.368 25.2086C548.051 24.0648 548.246 22.7258 547.918 21.4401C547.59 20.1544 546.783 19.0638 545.639 18.3899L530.38 9.29238C528.074 7.90914 525.033 8.65396 523.615 10.9416Z" fill="#2AC3A2"/>
+<path d="M551.004 128.163C548.415 128.163 546.305 126.053 546.305 123.463C546.305 120.874 548.415 118.764 551.004 118.764C553.593 118.764 555.703 120.874 555.703 123.463C555.703 126.053 553.593 128.163 551.004 128.163ZM551.004 119.651C548.903 119.651 547.191 121.362 547.191 123.463C547.191 125.565 548.903 127.276 551.004 127.276C553.105 127.276 554.817 125.565 554.817 123.463C554.817 121.362 553.105 119.651 551.004 119.651Z" fill="#FF8A50"/>
+<path d="M575.12 176.08C574.517 176.08 573.897 175.982 573.294 175.778L558.282 170.698C556.811 170.201 555.631 169.155 554.966 167.763C554.301 166.371 554.221 164.792 554.753 163.338L560.206 148.459C561.288 145.515 564.56 143.981 567.513 145.019C568.958 145.533 570.119 146.579 570.767 147.963C571.423 149.355 571.485 150.907 570.962 152.352L567.521 161.742L576.991 164.943C578.445 165.431 579.615 166.468 580.289 167.842C580.963 169.217 581.052 170.777 580.546 172.232C579.731 174.599 577.488 176.08 575.12 176.08Z" fill="#FFD567"/>
+<path d="M525.033 151.625C523.57 151.625 522.107 151.093 520.981 150.011L520.839 149.878C518.605 147.599 518.578 144.008 520.777 141.703L520.901 141.579C522.666 139.734 522.612 136.773 520.795 134.982C518.977 133.182 516.016 133.182 514.189 134.973L514.065 135.097C511.786 137.331 508.089 137.331 505.819 135.088C503.514 132.809 503.487 129.085 505.757 126.78C508.843 123.65 512.966 121.903 517.363 121.876C521.744 121.867 525.902 123.525 529.041 126.611C535.505 132.986 535.575 143.432 529.209 149.896C528.074 151.048 526.549 151.625 525.033 151.625ZM521.469 149.257L521.593 149.373C523.544 151.235 526.682 151.19 528.589 149.257C534.618 143.139 534.547 133.261 528.429 127.232C525.494 124.341 521.619 122.745 517.496 122.745C517.461 122.745 517.417 122.745 517.381 122.745C513.223 122.772 509.321 124.421 506.404 127.383C504.471 129.342 504.498 132.508 506.458 134.441C508.382 136.338 511.52 136.347 513.453 134.45L513.577 134.325C515.741 132.197 519.261 132.206 521.424 134.334C523.588 136.462 523.641 139.982 521.548 142.182L521.424 142.306C519.554 144.274 519.571 147.324 521.469 149.257Z" fill="#FFA436"/>
+<path d="M479.211 22.7346C473.652 22.7346 469.139 18.2125 469.139 12.6617C469.139 7.11102 473.661 2.58887 479.211 2.58887C484.762 2.58887 489.284 7.11102 489.284 12.6617C489.284 18.2125 484.77 22.7346 479.211 22.7346ZM479.211 3.46669C474.148 3.46669 470.025 7.58983 470.025 12.6529C470.025 17.7159 474.148 21.839 479.211 21.839C484.274 21.839 488.397 17.7159 488.397 12.6529C488.397 7.58983 484.274 3.46669 479.211 3.46669Z" fill="#D1FFEE"/>
+<path d="M383.354 103.202C377.794 103.202 373.281 98.6802 373.281 93.1295C373.281 87.5788 377.803 83.0566 383.354 83.0566C388.913 83.0566 393.426 87.5788 393.426 93.1295C393.426 98.6802 388.904 103.202 383.354 103.202ZM383.354 83.9345C378.291 83.9345 374.168 88.0576 374.168 93.1206C374.168 98.1837 378.291 102.307 383.354 102.307C388.417 102.307 392.539 98.1837 392.539 93.1206C392.539 88.0576 388.417 83.9345 383.354 83.9345Z" fill="#CB9EFF"/>
+<path d="M390.731 23.4883C388.141 23.4883 386.031 21.378 386.031 18.7888C386.031 16.1997 388.141 14.0894 390.731 14.0894C393.32 14.0894 395.43 16.1997 395.43 18.7888C395.43 21.378 393.32 23.4883 390.731 23.4883Z" fill="#0090ED"/>
+<path d="M451.6 39.3248C449.011 39.3248 446.9 37.2144 446.9 34.6253C446.9 32.0361 449.011 29.9258 451.6 29.9258C454.189 29.9258 456.299 32.0361 456.299 34.6253C456.299 37.2144 454.189 39.3248 451.6 39.3248ZM451.6 30.8125C449.498 30.8125 447.787 32.5238 447.787 34.6253C447.787 36.7267 449.498 38.4381 451.6 38.4381C453.701 38.4381 455.412 36.7267 455.412 34.6253C455.412 32.5238 453.701 30.8125 451.6 30.8125Z" fill="#E3FFF3"/>
+<path d="M374.895 60.6054C372.306 60.6054 370.195 58.4951 370.195 55.9059C370.195 53.3168 372.306 51.2064 374.895 51.2064C377.484 51.2064 379.594 53.3168 379.594 55.9059C379.594 58.4951 377.484 60.6054 374.895 60.6054ZM374.895 52.0931C372.793 52.0931 371.082 53.8044 371.082 55.9059C371.082 58.0074 372.793 59.7187 374.895 59.7187C376.996 59.7187 378.707 58.0074 378.707 55.9059C378.707 53.8044 376.996 52.0931 374.895 52.0931Z" fill="#241F20"/>
+<path d="M435.268 95.2487C432.679 95.2487 430.568 93.1384 430.568 90.5492C430.568 87.9601 432.679 85.8497 435.268 85.8497C437.857 85.8497 439.967 87.9601 439.967 90.5492C439.967 93.1384 437.857 95.2487 435.268 95.2487Z" fill="#FF298A"/>
+<path d="M421.826 7.33274C420.478 7.33274 419.121 6.87166 418.022 5.94063L417.88 5.81649C415.53 3.67068 415.335 -0.00910568 417.437 -2.39432L429.185 -15.7214C430.222 -16.8918 431.65 -17.6012 433.219 -17.6898C434.78 -17.7874 436.287 -17.2731 437.466 -16.2356C439.887 -14.0987 440.117 -10.3835 437.98 -7.96277L426.223 5.36427C425.071 6.66772 423.448 7.33274 421.826 7.33274ZM418.474 5.16033L418.598 5.2756C420.646 7.03126 423.767 6.80959 425.558 4.77905L437.307 -8.54799C439.124 -10.6051 438.92 -13.7529 436.872 -15.5706C435.879 -16.4485 434.593 -16.8918 433.272 -16.8031C431.942 -16.7233 430.728 -16.1292 429.85 -15.1273L418.102 -1.80023C416.319 0.212566 416.488 3.3426 418.474 5.16033Z" fill="#FF298A"/>
+<path d="M312.971 57.8478C312.705 57.8478 312.439 57.8301 312.173 57.7946C309.069 57.3601 306.87 54.4872 307.269 51.3749L309.282 35.6538C309.477 34.1109 310.266 32.7543 311.508 31.8232C312.749 30.8922 314.274 30.5109 315.808 30.7415L331.475 33.1533C334.57 33.6321 336.724 36.5405 336.29 39.635C336.077 41.1602 335.279 42.4991 334.047 43.4124C332.814 44.3257 331.298 44.6981 329.782 44.4675L319.895 42.9513L318.628 52.8734C318.432 54.3985 317.652 55.7463 316.437 56.6773C315.418 57.4488 314.212 57.8478 312.971 57.8478ZM314.912 31.5661C313.875 31.5661 312.873 31.903 312.031 32.5326C310.985 33.3218 310.32 34.4656 310.151 35.769L308.138 51.4902C307.801 54.1148 309.663 56.5532 312.288 56.9168C313.574 57.0941 314.85 56.766 315.879 55.9769C316.907 55.1877 317.564 54.0527 317.732 52.7581L319.115 41.9316L329.897 43.5897C331.183 43.7848 332.459 43.4744 333.497 42.703C334.534 41.9316 335.208 40.7966 335.394 39.5109C335.767 36.8863 333.94 34.4301 331.324 34.0311L315.657 31.6193C315.409 31.5838 315.161 31.5661 314.912 31.5661Z" fill="#E7DFFF"/>
+<path d="M414.654 74.3758C413.678 74.3758 412.685 74.1276 411.772 73.6221C407.942 71.4586 405.184 67.9384 404.005 63.7C402.826 59.4616 403.366 55.0193 405.53 51.1976C409.99 43.2971 420.053 40.4952 427.962 44.9464C430.738 46.5158 431.757 50.0626 430.241 52.8646L430.144 53.033C428.53 55.7818 425.072 56.7483 422.27 55.2232L422.119 55.1345C419.876 53.9198 417.03 54.7355 415.771 56.9611C414.512 59.1867 415.283 62.0508 417.491 63.3365L417.642 63.4251C420.39 65.0389 421.357 68.6034 419.787 71.3877C418.697 73.3029 416.702 74.3758 414.654 74.3758ZM419.894 43.7139C414.45 43.7139 409.156 46.569 406.301 51.6321C404.253 55.2587 403.748 59.4616 404.865 63.4606C405.982 67.4596 408.589 70.8025 412.215 72.8419C414.609 74.1985 417.659 73.3473 419.016 70.9443C420.346 68.5857 419.53 65.5532 417.198 64.1877L417.048 64.099C414.423 62.565 413.51 59.1601 414.999 56.5178C416.489 53.8754 419.876 52.9001 422.545 54.3454L422.696 54.434C425.072 55.7286 428.007 54.9129 429.381 52.572L429.47 52.4212C430.755 50.0449 429.895 47.0301 427.537 45.7001C425.107 44.3523 422.483 43.7139 419.894 43.7139Z" fill="#E7DFFF"/>
+<path d="M356.595 28.5247C355.575 28.5247 354.537 28.2587 353.598 27.7001L338.338 18.6026C335.607 16.9711 334.667 13.4066 336.255 10.6489L336.352 10.4805C338.028 7.78491 341.61 6.90709 344.341 8.52974L359.6 17.6272C360.948 18.4253 361.897 19.711 362.278 21.2272C362.659 22.7435 362.429 24.3218 361.631 25.6696C360.54 27.505 358.59 28.5247 356.595 28.5247ZM337.115 10.9416L337.026 11.0834C335.678 13.4243 336.476 16.4479 338.79 17.8312L354.05 26.9287C356.408 28.3297 359.467 27.5582 360.868 25.2085C361.551 24.0647 361.746 22.7257 361.418 21.44C361.09 20.1543 360.283 19.0637 359.139 18.3898L343.88 9.2923C341.575 7.90905 338.542 8.65388 337.115 10.9416Z" fill="#D74CF0"/>
+<path d="M467.729 91.8792C465.965 91.8792 464.209 91.09 463.065 89.5915L452.248 75.5019C451.29 74.2605 450.882 72.7177 451.086 71.1659C451.29 69.6142 452.088 68.231 453.33 67.2822C455.892 65.3137 459.581 65.8014 461.549 68.364L472.366 82.4536C474.308 84.9807 473.856 88.6427 471.364 90.6201L471.214 90.7353C470.167 91.5068 468.944 91.8792 467.729 91.8792Z" fill="#3FE1B0"/>
+<path d="M417.25 142.421C411.691 142.421 407.178 137.899 407.178 132.348C407.178 126.797 411.7 122.275 417.25 122.275C422.801 122.275 427.323 126.797 427.323 132.348C427.323 137.899 422.81 142.421 417.25 142.421ZM417.25 123.162C412.187 123.162 408.064 127.285 408.064 132.348C408.064 137.411 412.187 141.534 417.25 141.534C422.313 141.534 426.436 137.411 426.436 132.348C426.436 127.285 422.313 123.162 417.25 123.162Z" fill="#FFDEF0"/>
+<path d="M364.504 128.163C361.915 128.163 359.805 126.053 359.805 123.463C359.805 120.874 361.915 118.764 364.504 118.764C367.093 118.764 369.203 120.874 369.203 123.463C369.203 126.053 367.093 128.163 364.504 128.163ZM364.504 119.651C362.403 119.651 360.691 121.362 360.691 123.463C360.691 125.565 362.403 127.276 364.504 127.276C366.605 127.276 368.317 125.565 368.317 123.463C368.317 121.362 366.605 119.651 364.504 119.651Z" fill="#FFB587"/>
+<path d="M469.387 157.805C467.969 157.805 466.541 157.282 465.433 156.236L453.942 145.32C452.816 144.256 452.186 142.811 452.168 141.259C452.151 139.708 452.745 138.253 453.835 137.154L465.034 125.937C467.25 123.72 470.868 123.703 473.111 125.884C474.211 126.957 474.823 128.393 474.831 129.927C474.84 131.461 474.246 132.907 473.165 133.988L466.098 141.064L473.351 147.954C474.468 149.009 475.097 150.437 475.124 151.971C475.151 153.505 474.583 154.959 473.51 156.058C472.384 157.22 470.886 157.805 469.387 157.805ZM469.095 125.157C467.845 125.157 466.603 125.627 465.655 126.576L454.456 137.792C453.534 138.723 453.028 139.947 453.046 141.259C453.064 142.572 453.596 143.786 454.545 144.691L466.036 155.606C467.96 157.433 471.019 157.371 472.863 155.464C473.767 154.533 474.246 153.31 474.229 152.015C474.211 150.72 473.67 149.514 472.73 148.619L464.821 141.109L472.535 133.385C473.448 132.472 473.954 131.249 473.945 129.954C473.936 128.659 473.422 127.445 472.491 126.54C471.551 125.609 470.327 125.157 469.095 125.157Z" fill="#FFBD4F"/>
+<path d="M292.711 22.7346C287.152 22.7346 282.639 18.2125 282.639 12.6617C282.639 7.11102 287.161 2.58887 292.711 2.58887C298.262 2.58887 302.784 7.11102 302.784 12.6617C302.784 18.2125 298.262 22.7346 292.711 22.7346ZM292.711 3.46669C287.648 3.46669 283.525 7.58983 283.525 12.6529C283.525 17.7159 287.648 21.839 292.711 21.839C297.774 21.839 301.897 17.7159 301.897 12.6529C301.897 7.58983 297.774 3.46669 292.711 3.46669Z" fill="#80EBFF"/>
+<path d="M196.854 103.202C191.294 103.202 186.781 98.6802 186.781 93.1295C186.781 87.5788 191.303 83.0566 196.854 83.0566C202.404 83.0566 206.926 87.5788 206.926 93.1295C206.926 98.6802 202.404 103.202 196.854 103.202ZM196.854 83.9345C191.791 83.9345 187.668 88.0576 187.668 93.1206C187.668 98.1837 191.791 102.307 196.854 102.307C201.917 102.307 206.04 98.1837 206.04 93.1206C206.04 88.0576 201.917 83.9345 196.854 83.9345Z" fill="#E7DFFF"/>
+<path d="M204.231 23.4883C201.641 23.4883 199.531 21.378 199.531 18.7888C199.531 16.1997 201.641 14.0894 204.231 14.0894C206.82 14.0894 208.93 16.1997 208.93 18.7888C208.93 21.378 206.82 23.4883 204.231 23.4883ZM204.231 14.9761C202.129 14.9761 200.418 16.6874 200.418 18.7888C200.418 20.8903 202.129 22.6016 204.231 22.6016C206.332 22.6016 208.043 20.8903 208.043 18.7888C208.043 16.6874 206.332 14.9761 204.231 14.9761Z" fill="#F7E2FF"/>
+<path d="M265.1 39.3248C262.511 39.3248 260.4 37.2144 260.4 34.6253C260.4 32.0361 262.511 29.9258 265.1 29.9258C267.689 29.9258 269.799 32.0361 269.799 34.6253C269.799 37.2144 267.689 39.3248 265.1 39.3248ZM265.1 30.8125C262.998 30.8125 261.287 32.5238 261.287 34.6253C261.287 36.7267 262.998 38.4381 265.1 38.4381C267.201 38.4381 268.912 36.7267 268.912 34.6253C268.912 32.5238 267.201 30.8125 265.1 30.8125Z" fill="#FFD567"/>
+<path d="M188.395 60.6054C185.806 60.6054 183.695 58.4951 183.695 55.9059C183.695 53.3168 185.806 51.2064 188.395 51.2064C190.984 51.2064 193.094 53.3168 193.094 55.9059C193.094 58.4951 190.984 60.6054 188.395 60.6054ZM188.395 52.0931C186.293 52.0931 184.582 53.8044 184.582 55.9059C184.582 58.0074 186.293 59.7187 188.395 59.7187C190.496 59.7187 192.207 58.0074 192.207 55.9059C192.207 53.8044 190.496 52.0931 188.395 52.0931Z" fill="#FFB587"/>
+<path d="M125.691 109.897C123.102 109.897 120.992 107.787 120.992 105.197C120.992 102.608 123.102 100.498 125.691 100.498C128.281 100.498 130.391 102.608 130.391 105.197C130.391 107.787 128.281 109.897 125.691 109.897ZM125.691 101.385C123.59 101.385 121.879 103.096 121.879 105.197C121.879 107.299 123.59 109.01 125.691 109.01C127.793 109.01 129.504 107.299 129.504 105.197C129.504 103.096 127.793 101.385 125.691 101.385Z" fill="#45278D"/>
+<path d="M235.325 7.33274C233.978 7.33274 232.621 6.87166 231.522 5.94063L231.38 5.81649C229.03 3.67068 228.835 -0.00910568 230.937 -2.39432L242.685 -15.7214C243.722 -16.8918 245.15 -17.6012 246.719 -17.6898C248.288 -17.7874 249.787 -17.2731 250.966 -16.2356C253.387 -14.0987 253.617 -10.3835 251.48 -7.96277L239.732 5.36427C238.571 6.66772 236.948 7.33274 235.325 7.33274Z" fill="#FF6A75"/>
+<path d="M126.471 57.8478C126.205 57.8478 125.939 57.8301 125.673 57.7946C122.569 57.3601 120.37 54.4872 120.769 51.3749L122.782 35.6538C122.977 34.1109 123.766 32.7543 125.008 31.8232C126.249 30.8922 127.774 30.5109 129.308 30.7415L144.975 33.1533C148.07 33.6321 150.233 36.5405 149.79 39.635C149.577 41.1602 148.779 42.4991 147.547 43.4124C146.314 44.3257 144.798 44.6981 143.282 44.4675L133.395 42.9513L132.128 52.8734C131.932 54.3985 131.152 55.7463 129.937 56.6773C128.909 57.4488 127.712 57.8478 126.471 57.8478ZM128.412 31.5661C127.375 31.5661 126.373 31.903 125.531 32.5326C124.485 33.3218 123.82 34.4656 123.651 35.769L121.638 51.4902C121.301 54.1148 123.163 56.5532 125.788 56.9168C127.074 57.0941 128.35 56.766 129.379 55.9769C130.407 55.1877 131.064 54.0527 131.232 52.7581L132.615 41.9316L143.397 43.5897C144.683 43.7848 145.959 43.4656 146.997 42.703C148.034 41.9316 148.708 40.7966 148.894 39.5109C149.267 36.8863 147.44 34.4301 144.824 34.0311L129.157 31.6193C128.909 31.5838 128.661 31.5661 128.412 31.5661Z" fill="#54FFBD"/>
+<path d="M225.262 73.6222C226.176 74.1276 227.169 74.3759 228.144 74.3759C230.201 74.3759 232.196 73.303 233.278 71.3878C234.847 68.6035 233.881 65.039 231.132 63.4252L230.981 63.3365C228.773 62.0508 228.002 59.1868 229.261 56.9612C230.52 54.7356 233.366 53.9198 235.61 55.1346L235.76 55.2233C238.562 56.7484 242.02 55.7819 243.634 53.0331L243.731 52.8647C245.248 50.0627 244.228 46.5159 241.453 44.9465C233.544 40.4864 223.48 43.2883 219.02 51.1977C216.857 55.0193 216.316 59.4617 217.495 63.7001C218.674 67.9385 221.432 71.4587 225.262 73.6222Z" fill="#592ACB"/>
+<path d="M157.708 98.0773C156.316 98.0773 154.915 97.9 153.541 97.5364C149.285 96.428 145.712 93.7325 143.486 89.9374C138.893 82.1079 141.518 71.9996 149.347 67.4065C152.096 65.7927 155.678 66.6882 157.336 69.4104L157.433 69.5789C159.003 72.3542 158.098 75.8301 155.376 77.4882L155.226 77.5769C153.044 78.9069 152.326 81.7798 153.621 83.9788C154.915 86.1778 157.779 86.9493 159.996 85.6902L160.147 85.6015C162.922 84.032 166.495 84.9897 168.109 87.7384C169.749 90.5315 168.809 94.1404 166.016 95.7808C163.454 97.3059 160.599 98.0773 157.708 98.0773ZM152.309 67.4952C151.448 67.4952 150.588 67.7168 149.799 68.1779C142.396 72.5316 139.904 82.0902 144.258 89.4941C146.368 93.0852 149.737 95.63 153.771 96.6852C157.797 97.7315 161.991 97.1463 165.582 95.0448C167.958 93.6527 168.747 90.5847 167.355 88.2172C165.981 85.8852 162.957 85.0695 160.599 86.3995L160.448 86.4882C157.806 87.9867 154.401 87.0734 152.867 84.4488C151.333 81.833 152.184 78.4192 154.782 76.8409L154.933 76.7523C157.238 75.3424 158.01 72.3986 156.68 70.04L156.591 69.8892C155.642 68.3464 153.993 67.4952 152.309 67.4952Z" fill="#FF6BBA"/>
+<path d="M170.095 28.5247C169.075 28.5247 168.037 28.2587 167.098 27.7001L151.838 18.6026C149.107 16.9711 148.167 13.4066 149.755 10.6489L149.852 10.4805C151.528 7.78491 155.11 6.90709 157.841 8.52974L173.1 17.6272C174.448 18.4253 175.397 19.711 175.778 21.2272C176.159 22.7435 175.929 24.3218 175.131 25.6696C174.04 27.505 172.089 28.5247 170.095 28.5247ZM150.615 10.9416L150.526 11.0834C149.178 13.4243 149.976 16.4479 152.29 17.8312L167.55 26.9287C169.908 28.3297 172.967 27.5582 174.368 25.2085C175.051 24.0647 175.246 22.7257 174.918 21.44C174.59 20.1543 173.783 19.0637 172.639 18.3898L157.38 9.2923C155.075 7.90905 152.033 8.65388 150.615 10.9416Z" fill="#FFFFCC"/>
+<path d="M178.004 128.163C175.415 128.163 173.305 126.053 173.305 123.463C173.305 120.874 175.415 118.764 178.004 118.764C180.593 118.764 182.703 120.874 182.703 123.463C182.703 126.053 180.593 128.163 178.004 128.163ZM178.004 119.651C175.903 119.651 174.191 121.362 174.191 123.463C174.191 125.565 175.903 127.276 178.004 127.276C180.105 127.276 181.817 125.565 181.817 123.463C181.817 121.362 180.105 119.651 178.004 119.651Z" fill="#241F20"/>
+<path d="M152.025 151.625C150.562 151.625 149.099 151.093 147.973 150.011L147.831 149.878C145.597 147.599 145.57 144.008 147.769 141.703L147.893 141.578C149.658 139.734 149.605 136.773 147.787 134.981C145.969 133.181 143.008 133.181 141.181 134.973L141.057 135.097C138.779 137.331 135.081 137.331 132.811 135.088C130.506 132.818 130.479 129.085 132.749 126.78C135.835 123.649 139.958 121.903 144.356 121.876C144.4 121.876 144.435 121.876 144.48 121.876C148.833 121.876 152.93 123.552 156.033 126.611C162.497 132.986 162.568 143.432 156.201 149.896C155.075 151.048 153.55 151.625 152.025 151.625ZM148.47 149.257L148.594 149.373C150.553 151.243 153.692 151.19 155.59 149.266C161.619 143.148 161.548 133.27 155.43 127.241C152.495 124.35 148.62 122.754 144.498 122.754C144.462 122.754 144.418 122.754 144.382 122.754C140.224 122.781 136.323 124.43 133.405 127.391C131.472 129.351 131.499 132.516 133.459 134.449C135.383 136.356 138.521 136.356 140.454 134.458L140.578 134.334C142.742 132.206 146.262 132.206 148.425 134.343C150.589 136.471 150.642 140 148.55 142.19L148.425 142.314C146.555 144.274 146.572 147.324 148.47 149.257Z" fill="#C689FF"/>
+<path d="M106.211 22.7346C100.652 22.7346 96.1387 18.2125 96.1387 12.6617C96.1387 7.11102 100.661 2.58887 106.211 2.58887C111.762 2.58887 116.284 7.11102 116.284 12.6617C116.284 18.2125 111.762 22.7346 106.211 22.7346ZM106.211 3.46669C101.148 3.46669 97.0253 7.58983 97.0253 12.6529C97.0253 17.7159 101.148 21.839 106.211 21.839C111.274 21.839 115.397 17.7159 115.397 12.6529C115.397 7.58983 111.274 3.46669 106.211 3.46669Z" fill="#FF6BBA"/>
+<path d="M10.3459 103.202C4.78654 103.202 0.273438 98.6802 0.273438 93.1295C0.273438 87.5788 4.7954 83.0566 10.3459 83.0566C15.8964 83.0566 20.4184 87.5788 20.4184 93.1295C20.4184 98.6802 15.9053 103.202 10.3459 103.202ZM10.3459 83.9345C5.28307 83.9345 1.1601 88.0576 1.1601 93.1206C1.1601 98.1837 5.28307 102.307 10.3459 102.307C15.4087 102.307 19.5317 98.1837 19.5317 93.1206C19.5317 88.0576 15.4176 83.9345 10.3459 83.9345Z" fill="#87FFD1"/>
+<path d="M17.7305 23.4883C15.1415 23.4883 13.0312 21.378 13.0312 18.7888C13.0312 16.1997 15.1415 14.0894 17.7305 14.0894C20.3196 14.0894 22.4298 16.1997 22.4298 18.7888C22.4298 21.378 20.3196 23.4883 17.7305 23.4883ZM17.7305 14.9761C15.6292 14.9761 13.9179 16.6874 13.9179 18.7888C13.9179 20.8903 15.6292 22.6016 17.7305 22.6016C19.8319 22.6016 21.5432 20.8903 21.5432 18.7888C21.5432 16.6874 19.8319 14.9761 17.7305 14.9761Z" fill="#C45A27"/>
+<path d="M78.5997 39.3248C76.0106 39.3248 73.9004 37.2144 73.9004 34.6253C73.9004 32.0361 76.0106 29.9258 78.5997 29.9258C81.1887 29.9258 83.299 32.0361 83.299 34.6253C83.299 37.2144 81.1887 39.3248 78.5997 39.3248ZM78.5997 30.8125C76.4983 30.8125 74.7871 32.5238 74.7871 34.6253C74.7871 36.7267 76.4983 38.4381 78.5997 38.4381C80.7011 38.4381 82.4123 36.7267 82.4123 34.6253C82.4123 32.5238 80.7011 30.8125 78.5997 30.8125Z" fill="#45278D"/>
+<path d="M62.2677 95.2487C59.6786 95.2487 57.5684 93.1384 57.5684 90.5492C57.5684 87.9601 59.6786 85.8497 62.2677 85.8497C64.8567 85.8497 66.967 87.9601 66.967 90.5492C66.967 93.1384 64.8567 95.2487 62.2677 95.2487ZM62.2677 86.7364C60.1663 86.7364 58.455 88.4478 58.455 90.5492C58.455 92.6507 60.1663 94.362 62.2677 94.362C64.369 94.362 66.0803 92.6507 66.0803 90.5492C66.0803 88.4478 64.369 86.7364 62.2677 86.7364Z" fill="#241F20"/>
+<path d="M48.8166 7.33274C47.4689 7.33274 46.1123 6.87166 45.0217 5.94063L44.8798 5.81649C42.5302 3.67068 42.3351 -0.00910568 44.4365 -2.39432L56.1848 -15.7214C57.2221 -16.8918 58.6497 -17.6012 60.2191 -17.6898C61.7796 -17.7874 63.2869 -17.2731 64.4662 -16.2356C66.8867 -14.0987 67.1173 -10.3835 64.9804 -7.96277L53.2322 5.36427C52.0707 6.66772 50.4481 7.33274 48.8166 7.33274Z" fill="#87FFD1"/>
+<path d="M41.6439 74.3759C40.6686 74.3759 39.6755 74.1276 38.7622 73.6222C34.9319 71.4587 32.1744 67.9385 30.9951 63.7001C29.8158 59.4617 30.3567 55.0193 32.5202 51.1977C36.9801 43.2883 47.0436 40.4864 54.9526 44.9465C57.7279 46.5159 58.7476 50.0627 57.2314 52.8647L57.1338 53.0331C55.5201 55.7819 52.0621 56.7484 49.2603 55.2233L49.1096 55.1346C46.8663 53.9198 44.0201 54.7356 42.7611 56.9612C41.502 59.1868 42.2734 62.0508 44.4812 63.3365L44.6319 63.4252C47.3806 65.039 48.347 68.6035 46.7776 71.3878C45.6959 73.303 43.7009 74.3759 41.6439 74.3759ZM46.884 43.714C41.44 43.714 36.1466 46.5691 33.2915 51.6321C31.2434 55.2587 30.738 59.4617 31.8552 63.4607C32.9723 67.4686 35.5791 70.8025 39.2056 72.8419C41.5995 74.1986 44.6497 73.3474 46.0062 70.9444C47.3362 68.5858 46.5205 65.5533 44.1886 64.1878L44.0379 64.0991C41.4133 62.5651 40.5001 59.1602 41.9897 56.5179C43.4793 53.8755 46.8663 52.9001 49.5351 54.3454L49.6859 54.4341C52.0621 55.7287 54.997 54.9129 56.3713 52.5721L56.46 52.4213C57.7456 50.045 56.8856 47.0302 54.527 45.7002C52.1065 44.3524 49.482 43.714 46.884 43.714Z" fill="#FFA266"/>
+<path d="M94.729 91.8792C92.9646 91.8792 91.209 91.09 90.0652 89.5915L79.248 75.5019C78.2904 74.2605 77.8825 72.7177 78.0864 71.1659C78.2904 69.6142 79.0884 68.231 80.3297 67.2822C82.8921 65.3137 86.5806 65.8014 88.549 68.364L99.3662 82.4536C101.308 84.9807 100.856 88.6427 98.3643 90.6201L98.2136 90.7353C97.1585 91.5068 95.9437 91.8792 94.729 91.8792ZM83.8852 66.963C82.8301 66.963 81.7661 67.2999 80.8617 67.9916C79.8066 68.7985 79.1327 69.9689 78.9554 71.2901C78.778 72.6113 79.1327 73.9147 79.9396 74.9699L90.7568 89.0595C92.3971 91.1964 95.5004 91.6309 97.6639 90.026L97.7969 89.9196C99.9071 88.2437 100.288 85.1403 98.6481 82.9945L87.8308 68.9049C86.8644 67.6369 85.3836 66.963 83.8852 66.963Z" fill="#FF6A75"/>
+<path d="M44.2502 142.421C38.6908 142.421 34.1777 137.899 34.1777 132.348C34.1777 126.797 38.6997 122.275 44.2502 122.275C49.8007 122.275 54.3226 126.797 54.3226 132.348C54.3226 137.899 49.8007 142.421 44.2502 142.421ZM44.2502 123.162C39.1874 123.162 35.0644 127.285 35.0644 132.348C35.0644 137.411 39.1874 141.534 44.2502 141.534C49.313 141.534 53.436 137.411 53.436 132.348C53.436 127.285 49.313 123.162 44.2502 123.162Z" fill="#FF4AA2"/>
+<path d="M17.7305 209.828C15.1415 209.828 13.0312 207.717 13.0312 205.128C13.0312 202.539 15.1415 200.429 17.7305 200.429C20.3196 200.429 22.4298 202.539 22.4298 205.128C22.4298 207.717 20.3196 209.828 17.7305 209.828ZM17.7305 201.306C15.6292 201.306 13.9179 203.018 13.9179 205.119C13.9179 207.221 15.6292 208.932 17.7305 208.932C19.8319 208.932 21.5432 207.221 21.5432 205.119C21.5432 203.018 19.8319 201.306 17.7305 201.306Z" fill="#AB71FF"/>
+<path d="M48.8166 193.672C47.4689 193.672 46.1123 193.211 45.0217 192.28L44.8798 192.156C42.5302 190.01 42.3351 186.33 44.4365 183.945L56.1848 170.618C57.2221 169.447 58.6497 168.738 60.2191 168.649C61.7796 168.552 63.2869 169.066 64.4662 170.104C66.8867 172.241 67.1173 175.956 64.9804 178.376L53.2322 191.704C52.0707 192.998 50.4481 193.672 48.8166 193.672ZM45.4739 191.491L45.598 191.606C47.6462 193.353 50.7673 193.14 52.5583 191.109L64.3066 177.782C66.1242 175.725 65.9203 172.577 63.8721 170.76C62.879 169.882 61.5934 169.43 60.2723 169.518C58.9423 169.598 57.7275 170.192 56.8497 171.194L45.1015 184.521C43.3105 186.543 43.4789 189.673 45.4739 191.491Z" fill="#AB71FF"/>
+<path d="M15.6289 176.089C15.0171 176.089 14.3965 175.991 13.7935 175.787L-1.21762 170.707C-2.68948 170.21 -3.86874 169.164 -4.53373 167.772C-5.19873 166.371 -5.27853 164.801 -4.74653 163.347L0.706426 148.468C1.78815 145.524 5.05993 143.99 8.01251 145.028C9.45776 145.542 10.6193 146.588 11.2665 147.972C11.9138 149.355 11.9847 150.915 11.4616 152.361L8.02137 161.751L17.4909 164.952C18.945 165.44 20.1154 166.477 20.7893 167.851C21.4631 169.226 21.5518 170.786 21.0464 172.241C20.8868 172.684 20.6829 173.101 20.4257 173.491C19.344 175.149 17.5264 176.089 15.6289 176.089ZM6.11505 145.586C4.12893 145.586 2.25808 146.81 1.53989 148.77L-3.91307 163.648C-4.36527 164.881 -4.3032 166.202 -3.73574 167.381C-3.16827 168.561 -2.17522 169.439 -0.933894 169.864L14.0773 174.945C16.1698 175.654 18.4751 174.856 19.6898 173.012C19.9026 172.684 20.0799 172.329 20.2129 171.948C20.6385 170.724 20.5676 169.412 20.0001 168.241C19.4327 167.071 18.4396 166.211 17.216 165.794L6.87758 162.301L10.637 152.059C11.0803 150.836 11.0271 149.523 10.4774 148.353C9.92769 147.182 8.95237 146.296 7.72878 145.861C7.18791 145.675 6.64704 145.586 6.11505 145.586Z" fill="#F770FF"/>
+<path d="M96.3873 157.805C94.9686 157.805 93.5411 157.282 92.4328 156.236L80.9417 145.32C79.8156 144.247 79.1861 142.811 79.1684 141.259C79.1506 139.708 79.7447 138.253 80.8353 137.154L92.0338 125.937C94.2416 123.72 97.868 123.703 100.111 125.884C101.211 126.957 101.823 128.393 101.831 129.927C101.84 131.461 101.246 132.907 100.164 133.988L93.0978 141.064L100.351 147.954C101.468 149.009 102.097 150.437 102.124 151.971C102.151 153.505 101.583 154.959 100.51 156.058C99.3842 157.22 97.8857 157.805 96.3873 157.805ZM96.0947 125.157C94.8445 125.157 93.6032 125.627 92.6545 126.576L81.4559 137.792C80.5338 138.723 80.0284 139.947 80.0462 141.259C80.0639 142.572 80.5959 143.786 81.5446 144.691L93.0357 155.606C94.9598 157.424 98.0187 157.362 99.863 155.464C100.767 154.533 101.246 153.31 101.228 152.015C101.202 150.72 100.67 149.514 99.73 148.619L91.821 141.109L99.5349 133.385C100.448 132.463 100.954 131.249 100.945 129.954C100.936 128.659 100.422 127.445 99.4906 126.54C98.5507 125.609 97.3183 125.157 96.0947 125.157Z" fill="#F6B8FF"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/default.svg b/browser/components/newtab/data/content/assets/default.svg
new file mode 100644
index 0000000000..48a6baa6c3
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/default.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="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M19.0334 4.89145C20.8652 6.70398 22 9.21946 22 12C22 17.5228 17.5228 22 12 22C9.91269 22 7.97474 21.3605 6.37141 20.2667L19.0334 4.89145ZM17.4788 3.63307L4.83963 18.9806C3.08254 17.1786 2 14.7157 2 12C2 6.47715 6.47715 2 12 2C14.0227 2 15.9052 2.60055 17.4788 3.63307ZM12 0C18.6274 0 24 5.37258 24 12C24 18.6274 18.6274 24 12 24C5.37258 24 0 18.6274 0 12C0 5.37258 5.37258 0 12 0Z" fill="#5B5B66"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/device-migration.svg b/browser/components/newtab/data/content/assets/device-migration.svg
new file mode 100644
index 0000000000..d4beba87d9
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/device-migration.svg
@@ -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/. -->
+<svg fill="none" xmlns="http://www.w3.org/2000/svg" width="341" height="400" viewBox="0 0 341 215">
+ <g clip-path="url(#a)">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="m68 23.5 3.5 65 6.5 40 3.5 8v5.5l45 54 17.5 17.5h6l108-51 18-12.5 2-13.5v-8l-44.5-30v-55l-2-30-2-10.5L182 6l-76.5 7.5L73 19l-5 4.5Zm18 1L84 30v20l3.5 40.5 2 20 6 4 24-2 48.5-10 45-12 12.5-5.5 2-13-2-36.5-3-23L213 11l-64 5.5-49 4.5-14 3.5Z" fill="url(#b)"/>
+ <path d="M195.462 93.1709c-1.298.4447-2.726.6375-4.02 1.1121-1.865.6857-3.946.6082-5.686 1.6711-.03.0197-.058.0464-.087.0506-2.241.1511-4.472.9891-6.723.1476-1.412-.5314-1.683-1.9152-2.119-3.1264-.579-1.5954-.821-3.3083-1.647-4.8297-.368-.6797-.097-1.461-.283-2.1819-.494-1.9163-.938-3.8461-1.417-5.7663-.082-.3343-.148-.6535-.07-.9961-1.351-1.6748-1.376-2.9231-.2-4.8221 1.158-1.8789 1.829-3.9835 2.639-6.0207.105-.2721.175-.5619.339-.8151.514-.7999.864-1.6487.733-2.6283-1.221.1141-2.043 1.0043-3.018 1.5715-1.424.8272-2.834 1.6658-4.308 2.4093-1.17.5886-2.258 1.3991-3.25 2.2652-1.049.9124-2.075 1.9115-2.855 3.0463-.869 1.2668-1.984 2.3245-2.807 3.6178-.518.8126-1.334 1.3646-1.891 2.1916-.861 1.2803-1.408 2.6351-1.768 4.1102-.148.605-.543 1.1371-.624 1.7747.688 1.4111.78 3.071.278 4.3326-.442 1.1135-1.818 1.9471-3.169 2.3827-1.186.3839-2.469.6422-3.431 1.4578-.503.4215-.898.783-1.587.7854-.881.0077-1.581-.2074-2.149-.9655-.342-.4543-.719-.9805-1.357-1.135-.782-.4331-1.468.0873-2.172.249-.875.2035-1.733.0347-2.582.0762-1.53.0693-3.083.071-4.591.5719-.824.2753-1.778.1434-2.649.315-1.341.2587-2.667.5986-3.988.9294-1.794.4457-3.584 1.0068-5.278 1.7359-1.458.6306-2.86 1.4092-4.256 2.1978-1.461.8212-2.591 2.0805-4.089 2.8075-.284.138-.411.331-.442.618.424.471.963.183 1.453.207 2.726.114 5.478.007 8.135.759.545.156.986-.121 1.537-.032 1.023.163 2.006.868 3.059.52.826-.271 1.519-.055 2.254.202.517.179 1.169.043 1.429-.248.709-.778.981.094 1.379.277.507.229.315.671.171 1.128-.319 1.007-.443 2.063-.822 3.063-.624 1.646-.986 3.37-1.277 5.106-.005.024-.007.044-.013.065l67.243-18.02c.057-1.2624.265-2.5071.74-3.7147-1.594.4969-3.185 1.0082-4.764 1.5476Zm-43.856 7.6401c-1.077.447-2.196.782-3.385.737-2.244-.022-3.012-.576-3.505-2.3568-.159-.5653-.009-.9853.35-1.2943.377-.3295.866-.2824 1.331-.0353.433.2287.801.5637 1.328.6355.848.1136 1.625.1686 2.443-.3062 1.316-.7552 1.988-.5017 2.597.7603.339.6993-.051 1.3998-1.159 1.8598Z" fill="#fff"/>
+ <path d="M152.764 98.9514c.339.6994-.051 1.4006-1.159 1.8596-1.077.448-2.195.782-3.385.737-2.244-.022-3.012-.576-3.505-2.3566-.159-.5653-.008-.9852.35-1.2943.377-.3295.866-.2824 1.331-.0353.433.2287.801.5637 1.328.6355.848.1137 1.625.1687 2.443-.3061 1.316-.7552 1.988-.5017 2.597.7602Z" fill="#F69322"/>
+ <path d="M202.439 78.2929c.18 2.2755.359 4.5783.627 6.8612.2 1.7589.17 3.5134-.057 5.3094-.175 1.3713-.387 2.7331-.6 4.0915l-2.923.7834c.057-1.2623.265-2.5071.74-3.7147-1.594.497-3.185 1.0082-4.764 1.5476-1.298.4448-2.726.6375-4.02 1.1122-1.865.6856-3.946.6082-5.686 1.671-.03.0197-.058.0464-.087.0506-2.241.1512-4.472.9891-6.723.1476-1.412-.5313-1.683-1.9152-2.119-3.1264-.579-1.5954-.821-3.3082-1.647-4.8297-.368-.6797-.097-1.461-.283-2.1819-.494-1.9162-.938-3.8461-1.417-5.7662-.082-.3344-.148-.6536-.07-.9961-1.351-1.6749-1.376-2.9232-.2-4.8222 1.158-1.8789 1.829-3.9834 2.639-6.0207.105-.2721.175-.5619.339-.8151.514-.7999.864-1.6487.733-2.6283-1.221.1141-2.043 1.0043-3.018 1.5716-1.424.8272-2.834 1.6657-4.308 2.4092-1.17.5887-2.258 1.3991-3.25 2.2653-1.049.9123-2.075 1.9114-2.855 3.0462-.869 1.2668-1.984 2.3246-2.807 3.6179-.518.8126-1.334 1.3645-1.891 2.1915-.861 1.2803-1.408 2.6351-1.768 4.1103-.148.605-.543 1.137-.624 1.7746.688 1.4111.78 3.071.278 4.3326-.442 1.1136-1.818 1.9471-3.169 2.3827-1.186.3839-2.469.6423-3.431 1.4579-.503.4214-.898.7829-1.587.7854-.881.0076-1.581-.2074-2.149-.9656-.342-.4543-.719-.9804-1.357-1.135-.782-.4331-1.468.0874-2.172.249-.875.2035-1.733.0347-2.582.0763-1.53.0692-3.083.0709-4.591.5718-.824.2753-1.778.1435-2.649.3151-1.341.2586-2.667.5985-3.988.9293-1.794.4457-3.584 1.0069-5.278 1.7359-1.458.6306-2.86 1.4092-4.256 2.1978-1.461.8213-2.591 2.0811-4.089 2.8071-.284.139-.411.331-.442.618.424.471.963.184 1.453.207 2.726.114 5.478.008 8.135.76.545.156.986-.121 1.537-.033 1.023.164 2.006.869 3.059.521.826-.272 1.519-.055 2.254.201.517.179 1.169.043 1.429-.247.709-.779.981.093 1.379.277.507.228.315.671.171 1.128-.319 1.007-.443 2.062-.822 3.062-.624 1.647-.986 3.371-1.277 5.106-.005.025-.007.045-.013.066l-1.431.383c-.214-.063-.375-.201-.402-.531-.024-.292-.059-.569.005-.877.355-1.71.656-3.436 1.014-5.147.129-.62-.077-.897-.68-.934-2.512-.14-5.021-.311-7.537-.408-1.46-.058-2.832-.554-4.269-.699-1.402-.144-2.869-.777-4.182-.328-2.117.726-3.917-.267-5.854-.546-.455-.064-.575-.295-.63-.613-.231-1.34-.517-2.681-.619-4.0324-.119-1.6295-.395-3.2518-.224-4.9087.203-1.9326.376-3.8729.537-5.802.115-1.3785.361-2.7265.498-4.0954.128-1.2852-.949-1.9529-1.492-2.8649-.544-.9154-1.11-1.8596-1.751-2.7027-1.328-1.7506-2.08-3.7605-3.032-5.6936-.866-1.7585-1.569-3.5723-2.3532-5.3566-1.0161-2.303-1.8258-4.6886-3.0286-6.9224-.7801-1.4368-1.0827-3.1295-1.1955-4.7645-.0596-.8437-.5725-1.3995-.7737-2.1356-.7552-2.7604 1.3821-4.7273 3.8956-4.7271 3.2444-.002 6.4694.3384 9.5844 1.3121 2.104.6559 4.141 1.5663 6.274 2.0947 1.704.4187 3.06 1.3911 4.543 2.171.956.5029 1.747.4343 2.72-.2137 1.308-.8695 2.797-1.4972 4.186-2.2565 1.374-.7517 2.888-1.0568 4.309-1.6234 1.252-.5019 2.689-.6587 4.052-.9348 2.002-.4049 3.8-1.3245 5.678-2.0484.386-.1499.395-.5665.359-.8745-.225-2.0814.604-4.0308.743-6.055.13-1.9013.43-3.7864.563-5.6888.096-1.3619.654-2.6461 1.296-3.8792.376-.7204.836-1.4324.801-2.341-.046-1.3159 1.188-3.1106 2.249-3.5768.887-.3886 1.575-.1472 2.153.5072.715.8038 1.4 1.6388 2.061 2.4879 1.508 1.9273 3.21 3.6825 4.813 5.5184.915 1.0445 1.954 1.986 2.54 3.3935.893 2.1619 2.001 4.2583 3.107 6.3167 1.066 1.9839 2.331 3.9024 3.541 5.8284.601.9581 1.054 2.0566 1.337 3.0962.538 1.9783 1.689 2.8779 3.609 3.1497 2.302.324 4.516 1.0707 6.773 1.5581 2.031.4395 3.671 1.4325 5.367 2.4538.655.3937.561 1.3598-.238 2.2789-.966 1.107-1.451 2.3447-1.477 3.8386-.011.6536-.397 1.3225-.686 1.9498-.932 2.043-1.905 4.062-2.847 6.0958-.375.813-.61 1.6817-.71 2.5682-.09.8064.175 1.4753.847 2.0191.574.4658 1.027 1.0725 1.559 1.5962.532.5273 1.082.5117 1.554-.0834.266-.3346.5-.7071.691-1.0914 1.325-2.729 2.708-5.4583 3.475-8.3902.548-2.0756 1.584-3.9333 2.201-5.9653.273-.9021.067-1.8186.335-2.6806.685-2.1857 1.345-4.3882 3.414-5.7596 1.424-.9433 3.649-.7185 4.929.3288.804.6597 1.586 1.2944 2.288 2.0785.625.6999.994 1.426 1.227 2.2967.178.6613.507 1.2818.749 1.9257.416 1.1044.957 2.1407.895 3.412-.04.8474.357 1.6782.693 2.5137 1.192 2.9761 1.892 6.0648 2.143 9.3127Z" fill="#F69322"/>
+ <path d="M177.325 59.9162c-2.298-.8289-4.729-1.0291-7.086-1.5864-1.687-.3964-3.45-.5009-5.184-.6714-.723-.0693-1.297-.3028-1.45-1.0172-.283-1.3182-1.041-2.2382-2.157-2.9191-.85.0925-1.432-.4757-2.06-.8807-1.056-.6738-2.278-.7992-3.43-1.1646-.379.3768-.764.7471-1.139 1.1227-.504.5066-1.055 1.0069-1.814.761-.83-.2654-1.387-.8832-1.556-1.775-.092-.502-.141-1.0156-.208-1.5246-.39.004-.776.0069-1.166.0107-.31 1.0278-1.191.9892-1.989 1.0054-.55.012-.624-.5222-.765-.9337-.767-2.2419-.956-4.5924-1.318-6.912-.367-2.3377-.103-4.705-.246-7.0599-.599 2.0426-1.049 4.0918-1.257 6.235-.212 2.214-.123 4.4827-.895 6.6455-.336.942-1.107 1.4196-1.816 1.5051-2.502.2871-4.817 1.3025-7.263 1.714-1.574.267-3.059.8238-4.649 1.0637-1.67.2541-3.289 1.0056-4.477 2.3813-.402.4678-.953.6812-1.551.7448-.282.0328-.425.1913-.637.341-2.105 1.4511-3.76 2.6459-6.384.8472-.489-.3375-1.063-.1954-1.6-.2643-1.627-.2031-3.249-.663-4.654-1.4832-.979-.5742-2.012-.3246-2.989-.6783-1.314-.4805-2.721-.7155-4.009-1.3153-1.08-.5044-2.271-.0924-3.453-.2248.844.4901 1.651 1.0718 2.54 1.4569 3.123 1.3476 6.05 3.0649 8.98 4.7659 1.763 1.0265 3.403 2.2484 4.907 3.654.531.4929 1.304.704 1.452 1.5743.111.6478.009 1.2058-.609 1.4722-.478.2095-1.026.275-1.521-.0687-.243-.1712-.498-.3274-.747-.4893-.206.9807-.415 1.9625-.621 2.9431.181.2539.383.49.54.7577.728 1.2263-.262 2.4018-1.988 2.4381-.408 2.3944-1.274 4.6675-1.958 6.9847-.089.3028-.094.5904-.135.8842 1.235 1.4854.907 3.2387.412 4.7615-.461 1.4133-.313 2.8182-.473 4.201-.308 2.6385-.033 5.3261-.08 7.9955-.023 1.1874-.037 2.407.159 3.6018.144.898.562 1.491 1.601 1.538.792.036 1.576.372 2.355-.042.032-.288.158-.48.443-.618 1.497-.727 2.628-1.9866 4.088-2.8079 1.396-.7886 2.799-1.5672 4.256-2.1978 1.695-.729 3.485-1.2902 5.278-1.7359 1.321-.3308 2.648-.6707 3.988-.9293.872-.1716 1.825-.0398 2.65-.3151 1.508-.5009 3.06-.5026 4.591-.5718.848-.0415 1.707.1272 2.582-.0763.704-.1616 1.389-.6821 2.171-.249-.084-.9068.385-1.6289.848-2.3144 1.465-2.1626 3.665-3.3057 5.959-4.3817 1.577-.736 3.052-.7092 4.608-.1619.081-.6375.477-1.1696.624-1.7746.36-1.4752.907-2.83 1.769-4.1103.557-.8269 1.373-1.3789 1.891-2.1915.823-1.2933 1.938-2.3511 2.806-3.6179.781-1.1348 1.806-2.1339 2.855-3.0462.992-.8662 2.08-1.6766 3.251-2.2653 1.473-.7435 2.883-1.582 4.307-2.4092.975-.5673 1.798-1.4575 3.018-1.5716l.004-.001c.071-.1237.138-.25.197-.378.058-.128.118-.2525.172-.3831.035-.0869.07-.1736.104-.2605.067-.1725.127-.3514.18-.5283.277-.8913.436-1.8132.663-2.7144.083-.3281-.46-.6201-.915-.7848Zm-40.101 21.1487c-.347 1.5375-1.32 2.0112-2.901 1.9507-2.862-.0614-3.78-1.9534-3.93-4.2484-.14-2.0811 2.857-3.097 4.666-2.211 1.204.5912 2.463 3.1934 2.165 4.5087Zm17.634-10.0392c.006 1.4391-1.17 2.947-2.496 3.2871-.971.2485-1.593-.4832-2.178-.9578-1.191-.9627-1.671-2.3947-1.779-3.8955-.077-1.0215.852-1.8356 1.907-1.886 1.816-.0877 3.986 1.333 4.427 2.8337.07.2329.102.4528.119.6185Z" fill="#F69322"/>
+ <path d="M199.896 81.4336c.002-.0007.005-.0001.008.0017l.003.0118-.011-.0135Z" fill="#383431"/>
+ <path d="M202.439 78.2929c.18 2.2755.359 4.5783.627 6.8612.2 1.7588.17 3.5134-.057 5.3094-.175 1.3713-.387 2.7331-.6 4.0915-.089.5622-.179 1.1245-.268 1.6869-.238 1.4967-.607 2.0291-1.732 1.9783-.485-.0209-.871-.2004-.901-.7036-.044-.7278-.057-1.4563-.022-2.1782.057-1.2623.265-2.5071.74-3.7147.079-.2536.202-.5034.23-.7588.316-3.0398-.282-6.0667-.166-9.103.01-.2815-.168-.323-.386-.3266-.019-.0567-.051-.1179-.052-.1797-.128-2.2853-.662-4.5084-.991-6.7633.446-.5029-.214-.8838-.143-1.3713.244-1.6765-.405-3.2454-.762-4.8227-.541-2.3801-1.321-4.7271-2.504-6.8732-.558-1.0124-.984-2.153-1.982-2.9156-.997-.759-1.745-.6592-2.701.081-1.353 1.0482-1.854 2.5338-2.191 4.0223-.585 2.5694-1.238 5.1067-2.342 7.49-.635 1.3709-1.02 2.7404-.97 4.2413-.117.2405-.296.4704-.341.7226-.329 1.7767-1.528 3.1707-2.122 4.8403-.482 1.353-1.914 2.1511-2.523 3.4916-.087.1938-.257.1813-.424.195-1.693.1284-3.103-.4811-4.142-1.7867-.719-.9035-1.224-1.9802-2.304-2.5545-1.351-1.6749-1.376-2.9232-.2-4.8222 1.158-1.8788 1.829-3.9834 2.639-6.0206.105-.2722.175-.562.339-.8152.514-.7999.864-1.6487.733-2.6283l-.001-.0035c.071-.1239.138-.2502.201-.3755.059-.128.118-.2526.172-.3832.035-.0868.07-.1735.105-.2604.066-.1725.127-.3514.18-.5283.276-.8913.436-1.8132.663-2.7144.082-.3281-.461-.6201-.916-.7848-2.297-.8289-4.729-1.0292-7.086-1.5864-1.686-.3964-3.449-.5009-5.183-.6714-.724-.0693-1.298-.3028-1.45-1.0172-.284-1.3182-1.042-2.2382-2.157-2.9191-.02-.231.058-.5771-.071-.6819-1.138-.9655-1.163-2.4922-1.861-3.6919-1.055-1.816-1.85-3.7988-2.817-5.6854-.754-1.471-1.695-2.8297-2.552-4.2345-.843-1.3849-2.011-2.563-2.879-3.9649-.619-.9959-1.51-1.822-2.486-2.9623-.012 2.8303-.081 5.3349-.011 7.8336.06 2.2068.25 4.4021.719 6.5847.231 1.0959.693 2.1842.584 3.3521-.309 1.0278-1.191.9892-1.988 1.0054-.551.012-.624-.5222-.765-.9337-.768-2.2419-.956-4.5924-1.318-6.912-.367-2.3377-.103-4.705-.246-7.0599-.599 2.0426-1.049 4.0918-1.257 6.235-.213 2.2139-.123 4.4827-.895 6.6455-.337.942-1.107 1.4196-1.816 1.5051-2.503.2871-4.817 1.3025-7.263 1.7139-1.575.2671-3.06.8239-4.649 1.0638-1.671.2541-3.29 1.0056-4.478 2.3813-.401.4678-.952.6812-1.551.7448-.281.0327-.425.1913-.636.341-2.106 1.4511-3.761 2.6459-6.384.8472-.49-.3375-1.063-.1954-1.601-.2643-1.627-.2031-3.249-.663-4.653-1.4832-.979-.5743-2.012-.3246-2.99-.6783-1.314-.4805-2.721-.7155-4.008-1.3153-1.08-.5044-2.271-.0924-3.453-.2248.844.4901 1.65 1.0718 2.54 1.4569 3.122 1.3476 6.049 3.0649 8.98 4.7659 1.762 1.0265 3.402 2.2484 4.906 3.654.531.4929 1.304.704 1.452 1.5743.112.6478.009 1.2058-.608 1.4722-.479.2095-1.027.275-1.521-.0688-.244-.1711-.499-.3273-.747-.4892-1.536-1.3932-3.289-2.5034-5.05-3.5381-3.042-1.7835-6.318-3.1556-9.307-5.0461-.18-.1104-.36-.3334-.637-.2552-.1974.1612-.1507.4509-.066.5519.881 1.0186.85 2.3904 1.32 3.5657.625 1.5674 1.086 3.2446 1.664 4.8365.514 1.4115 1.016 2.8801 2.003 4.1801.734.9614 1.211 2.2508 1.749 3.4196.945 2.0357 2.332 3.8018 3.386 5.7694.142.268.34.6175.776.524 1.234 1.4854.906 3.2387.412 4.7614-.462 1.4134-.314 2.8183-.474 4.2011-.307 2.6385-.032 5.3261-.08 7.9955-.023 1.1874-.037 2.407.16 3.602.144.898.562 1.491 1.601 1.538.792.036 1.575.372 2.355-.043.424.471.963.184 1.453.207 2.726.114 5.478.008 8.135.76.545.156.986-.121 1.537-.033 1.023.164 2.006.869 3.059.521.826-.272 1.519-.055 2.254.201.517.179 1.169.043 1.429-.247.709-.779.981.093 1.379.277.507.228.315.671.171 1.128-.319 1.007-.443 2.062-.822 3.062-.624 1.647-.986 3.371-1.277 5.106-.005.025-.007.045-.013.066-.12.504-.558.432-.938.429-.171-.001-.342-.005-.493-.046-.214-.063-.375-.201-.402-.531-.024-.292-.059-.569.005-.877.355-1.71.656-3.436 1.014-5.147.129-.62-.077-.897-.68-.934-2.512-.14-5.021-.311-7.537-.408-1.46-.058-2.832-.554-4.269-.699-1.402-.143-2.869-.777-4.182-.328-2.117.726-3.917-.267-5.854-.546-.455-.064-.575-.295-.63-.613-.231-1.34-.517-2.681-.619-4.0324-.119-1.6295-.395-3.2518-.224-4.9087.203-1.9326.376-3.8729.537-5.802.115-1.3785.361-2.7265.498-4.0954.128-1.2852-.949-1.9529-1.492-2.8649-.544-.9154-1.11-1.8596-1.751-2.7027-1.328-1.7506-2.08-3.7605-3.032-5.6936-.866-1.7585-1.569-3.5723-2.3532-5.3566-1.0161-2.303-1.8258-4.6886-3.0286-6.9224-.7801-1.4369-1.0827-3.1295-1.1955-4.7645-.0596-.8437-.5725-1.3995-.7737-2.1356-.7552-2.7604 1.3821-4.7273 3.8956-4.7271 3.2444-.002 6.4694.3384 9.5844 1.3121 2.104.6559 4.141 1.5663 6.274 2.0947 1.704.4187 3.06 1.3911 4.543 2.171.956.5029 1.747.4343 2.72-.2137 1.308-.8695 2.797-1.4972 4.186-2.2565 1.374-.7517 2.888-1.0568 4.309-1.6234 1.252-.5019 2.689-.6587 4.052-.9348 2.002-.4049 3.8-1.3245 5.678-2.0484.386-.1499.395-.5665.359-.8745-.225-2.0814.604-4.0308.743-6.055.13-1.9013.43-3.7864.563-5.6888.096-1.3619.654-2.6461 1.296-3.8792.376-.7204.836-1.4324.801-2.341-.046-1.3159 1.188-3.1106 2.249-3.5768.887-.3886 1.575-.1472 2.153.5072.715.8038 1.4 1.6388 2.061 2.4879 1.508 1.9273 3.21 3.6825 4.813 5.5184.915 1.0445 1.954 1.986 2.54 3.3935.893 2.1619 2.001 4.2583 3.107 6.3167 1.066 1.9839 2.331 3.9024 3.541 5.8284.601.9581 1.054 2.0566 1.337 3.0962.538 1.9783 1.689 2.8779 3.609 3.1497 2.302.324 4.516 1.0707 6.773 1.5581 2.031.4395 3.671 1.4325 5.367 2.4538.655.3937.561 1.3598-.238 2.2789-.966 1.107-1.451 2.3447-1.477 3.8386-.011.6536-.397 1.3225-.686 1.9498-.932 2.043-1.905 4.062-2.847 6.0958-.375.813-.61 1.6817-.71 2.5682-.09.8064.175 1.4753.847 2.0191.574.4659 1.027 1.0725 1.559 1.5962.532.5273 1.082.5117 1.554-.0834.266-.3346.5-.7071.691-1.0914 1.325-2.729 2.708-5.4583 3.476-8.3902.547-2.0756 1.583-3.9333 2.2-5.9653.273-.9021.067-1.8186.335-2.6806.685-2.1857 1.345-4.3882 3.414-5.7596 1.424-.9433 3.649-.7185 4.929.3288.804.6597 1.586 1.2944 2.288 2.0785.625.6998.994 1.426 1.227 2.2967.178.6613.507 1.2819.749 1.9257.416 1.1044.957 2.1407.895 3.412-.04.8474.357 1.6782.693 2.5137 1.192 2.9761 1.892 6.0648 2.143 9.3127Z" fill="#000"/>
+ <path d="M200.29 81.7618c-.116 3.0362.482 6.0632.166 9.103-.028.2553-.151.5051-.23.7587-1.595.497-3.185 1.0083-4.764 1.5477-1.298.4447-2.726.6375-4.02 1.1121-1.865.6857-3.946.6082-5.686 1.6711-.03.0196-.058.0463-.088.0505-2.24.1512-4.471.9891-6.722.1476-1.412-.5313-1.683-1.9152-2.12-3.1263-.578-1.5955-.82-3.3083-1.646-4.8297-.368-.6797-.097-1.4611-.283-2.182-.494-1.9162-.938-3.8461-1.417-5.7662-.082-.3343-.148-.6536-.07-.9961 1.08.5743 1.585 1.651 2.304 2.5545 1.039 1.3056 2.449 1.9151 4.142 1.7867.167-.0137.337-.0012.424-.195.609-1.3405 2.041-2.1386 2.523-3.4915.594-1.6696 1.793-3.0637 2.122-4.8404.045-.2522.224-.4821.341-.7226.739.3014 1.427.6555 2.023 1.2199.659.6213 1.434 1.1608 2.351 1.287 1.384.1908 2.783-.0062 4.158-.1654 1.014-.117 2.068-.6084 2.762-1.2824.72-.6963 1.442-.8473 2.301-.9109.329 2.2549.863 4.478.991 6.7633.001.0618.033.123.052.1797.218.0037.396.0451.386.3267Z" fill="#F69322"/>
+ <path d="M156.677 90.2854c-.441 1.1135-1.817 1.9471-3.168 2.3827-1.187.3838-2.469.6422-3.432 1.4578-.503.4215-.898.783-1.586.7854-.881.0077-1.582-.2074-2.149-.9655-.342-.4544-.72-.9805-1.357-1.135-.085-.9069.384-1.6289.847-2.3144 1.465-2.1627 3.665-3.3058 5.959-4.3818 1.577-.736 3.052-.7092 4.608-.1618.688 1.411.781 3.071.278 4.3326ZM151.606 100.811c-1.077.448-2.195.782-3.385.737-2.244-.022-3.012-.576-3.505-2.3566-.159-.5653-.008-.9852.35-1.2943.377-.3295.866-.2824 1.331-.0353.433.2287.801.5637 1.328.6355.848.1137 1.625.1687 2.443-.3061 1.316-.7552 1.988-.5017 2.597.7602.339.6994-.051 1.4006-1.159 1.8596Z" fill="#000"/>
+ <path d="M110.964 80.2559c-.436.092-.634-.2556-.777-.523-1.052-1.9678-2.44-3.735-3.383-5.772-.54-1.1657-1.019-2.4582-1.749-3.418-.989-1.2993-1.489-2.7675-2.003-4.1813-.579-1.5912-1.041-3.2688-1.666-4.8367-.47-1.1751-.437-2.5454-1.319-3.5664-.0847-.0984-.1304-.3878.066-.5503.276-.0792.457.1435.635.2561 2.993 1.8903 6.267 3.2625 9.308 5.0467 1.762 1.0336 3.516 2.1449 5.05 3.5372-.207.9812-.414 1.9625-.621 2.9434-.137.108-.262.0482-.352-.0559-1.153-1.321-2.39-2.5536-3.727-3.6898-.417-.3545-.913-.4176-1.339-.2653-.464.1657-.745.541-.724 1.1735.038 1.1138.718 1.8308 1.479 2.3622.762.5313.499.8218-.002 1.1826-.624.4499-.315 1.1174-.459 1.6768.626.0087.529 1.1676 1.493.8299.65-.2278 1.45-.0287 2.183-.0206-.409 2.3969-1.274 4.6675-1.957 6.9878-.089.3013-.095.5887-.136.8831ZM150.075 50.2704c.111-1.1669-.351-2.2553-.586-3.3516-.466-2.1828-.656-4.3781-.718-6.5854-.07-2.4985 0-5.0009.011-7.833.977 1.143 1.868 1.9677 2.486 2.9622.87 1.4012 2.037 2.5827 2.881 3.9661.856 1.404 1.798 2.7651 2.552 4.2354.965 1.8845 1.761 3.8689 2.815 5.6848.698 1.2013.725 2.7259 1.864 3.6907.126.1064.051.4498.069.6832-.85.093-1.431-.4771-2.061-.8798-1.055-.6748-2.279-.8009-3.43-1.165.177-.311.366-.6162.53-.9341.405-.7855-.034-1.7339-.861-1.8601-.513-.0783-.984.0838-1.438.3079-.064-.4428-.144-.87-.184-1.3009-.042-.4563-.042-.9163-.068-1.3741-.057-.9774-.657-1.7247-1.406-1.7592-.642-.0296-1.31.7782-1.464 1.6063-.246 1.3211.174 2.5964.175 3.8969-.389.0032-.778.0065-1.167.0097Z" fill="#fff"/>
+ <path d="M134.322 83.0147c-2.861-.0621-3.778-1.9535-3.93-4.247-.139-2.0796 2.857-3.0984 4.666-2.2119 1.208.5915 2.467 3.195 2.168 4.5091-.35 1.5365-1.319 2.0118-2.904 1.9498ZM154.856 71.0253c.006 1.4386-1.168 2.9465-2.494 3.286-.972.2489-1.591-.4814-2.177-.9555-1.191-.9648-1.671-2.3952-1.781-3.8962-.074-1.0238.853-1.8374 1.906-1.8875 1.819-.0865 3.99 1.3345 4.43 2.8347.068.2328.099.4531.116.6185ZM151.241 50.2605c-.001-1.3004-.421-2.5758-.175-3.8969.155-.828.822-1.6359 1.465-1.6062.748.0345 1.348.7818 1.405 1.7591.027.4579.027.9179.069 1.3741.04.4309.12.8582.184 1.3009.453-.224.925-.3861 1.438-.3078.827.1261 1.266 1.0745.861 1.8601-.164.3179-.353.6231-.53.9341-.38.3741-.764.7449-1.14 1.1232-.502.5057-1.056 1.0041-1.812.7606-.831-.2677-1.389-.8845-1.555-1.7756-.094-.5041-.141-1.0168-.21-1.5256ZM113.056 72.3855c-.733-.0081-1.533-.2072-2.183.0205-.964.3378-.866-.8211-1.493-.8298.145-.5594-.165-1.2269.459-1.6768.501-.3608.764-.6513.003-1.1826-.762-.5314-1.442-1.2484-1.479-2.3623-.021-.6324.259-1.0077.723-1.1734.426-.1524.922-.0892 1.339.2653 1.337 1.1362 2.574 2.3688 3.727 3.6898.091.1041.215.1639.352.0559.181.2518.383.4911.54.7569.726 1.2255-.263 2.402-1.988 2.4365Z" fill="#000"/>
+ <path d="M195.452 61.4251c-.558-1.0123-.984-2.1529-1.982-2.9156-.997-.759-1.745-.6592-2.701.081-1.353 1.0482-1.854 2.5338-2.191 4.0223-.585 2.5694-1.237 5.1067-2.341 7.49-.636 1.371-1.02 2.7404-.971 4.2413.74.3014 1.427.6555 2.024 1.2199.658.6214 1.434 1.1608 2.351 1.287 1.383.1908 2.782-.0061 4.157-.1654 1.015-.117 2.068-.6084 2.762-1.2824.72-.6963 1.443-.8473 2.301-.9109.446-.5029-.214-.8837-.143-1.3713.244-1.6765-.405-3.2453-.762-4.8227-.541-2.38-1.321-4.7271-2.504-6.8732Zm-6.62 4.4464c.009-1.1527.423-1.5425 1.651-1.5151.625.2081.867.0425.533-.6814-.08-.1684-.022-.4006-.033-.6029-.025-.5548-.004-1.1413.547-1.413.438-.2142.842.1537 1.188.4019.488.3494.636.8868.564 1.4561-.106.8456-.527 1.3417-1.473 1.1772-.663-.1169-.893.3824-.514.7145.635.562.178 1.0523-.024 1.3697-.339.5285-1.053.4488-1.577.287-.493-.1505-.866-.5887-.862-1.194Zm7.586 4.8953c.038.7063-.536.8177-1.114.8874-.636.0813-1.266.2308-1.9.3505l-.011.0029c-.013.0111-.023.0175-.035.0286-.049.0362-.101.0734-.145.1087-.004-.0416-.006-.0798-.005-.1188-.001-.0036.003-.0045.002-.0082l-.001-.0037c-1.141-.0079-2.184-.4023-3.234-.7949-.637-.236-.789-.776-.674-1.2869.103-.4656.387-.8977 1.006-1.0442 1.118-.2648 2.221-.15 3.248.1984.609.2084 1.19.0335 1.793.2167.826.2509 1.033.8038 1.07 1.4635Zm-.503-5.2597c.002 1.0489-.32 1.4371-1.249 1.423-.805.0608-1.346-.3094-1.226-1.2207.091-.6866.048-1.5697 1.078-1.6561.69-.057 1.392.7152 1.397 1.4538Z" fill="#fff"/>
+ <path d="M199.897 81.4334c-.021.0168-.042.0337-.063.0505.025-.0123.05-.0246.075-.0365 0 .0004-.012-.014-.012-.014Z" fill="#383431"/>
+ <path d="M193.208 72.0144c-1.14-.0089-2.184-.4004-3.232-.7934-.639-.2392-.791-.7791-.676-1.2899.103-.4633.386-.8978 1.006-1.0443 1.12-.2647 2.224-.1482 3.249.2003.611.2075 1.19.033 1.794.2161.824.2502 1.031.8037 1.068 1.4629.039.7071-.535.8164-1.113.8893-.642.0811-1.275.233-1.912.354l.016.0292c-.005-.0479-.01-.0957-.015-.1435-.066.0431-.133.0862-.199.1293l.014-.01ZM190.484 64.3566c.623.2085.865.0419.532-.6802-.079-.1699-.022-.401-.032-.6038-.026-.5538-.004-1.1406.544-1.4115.441-.2175.844.1511 1.191.3995.486.3481.636.8872.564 1.4564-.107.8461-.526 1.3428-1.473 1.1773-.663-.116-.894.3809-.515.7145.635.56.179 1.0514-.024 1.3696-.338.5294-1.054.4475-1.577.287-.494-.1518-.867-.5903-.862-1.1939.009-1.1514.422-1.5427 1.652-1.5149ZM194.665 66.9316c-.803.0584-1.343-.3106-1.223-1.2227.089-.6849.047-1.5715 1.077-1.6567.688-.0569 1.392.7141 1.395 1.4535.003 1.0518-.317 1.4394-1.249 1.4259Z" fill="#000"/>
+ <path d="M193.392 72.0093c-.06.045-.121.09-.181.135-.001-.0431-.003-.0863-.004-.1297.001-.0002-.013.0098-.013.0098.071.0047.143.0095.214.0142l-.016-.0293Z" fill="#383431"/>
+ <path d="M193.409 72.0387c-.072-.0048-.143-.0095-.215-.0143.067-.0433.133-.0866.2-.1299.005.048.01.0961.015.1442Z" fill="#fff"/>
+ <path d="M290.558 44.9806c-.958.1884-1.914.3913-2.875.5612-.974.1721-1.961.2758-2.929.4736-1.522.3111-3.033.6818-4.551 1.0161-1.229.2706-2.477.4672-3.688.8007-1.552.4277-3.064 1.0041-4.616 1.4323-1.192.3287-2.431.4869-3.63.7925-2.324.5923-4.634 1.2401-6.953 1.855-1.624.4309-3.248.8688-4.882 1.2605-1.5.3596-3.009.6921-4.525.979-1.176.2225-2.399-.6111-2.35-1.627.039-.7941.692-1.2928 1.369-1.5026 1.558-.4821 3.243-.6375 4.715-1.2877 2.069-.9134 4.307-1.1507 6.405-1.9604 1.914-.7385 4.058-.8592 6.07-1.3741 2.918-.747 5.802-1.6239 8.712-2.4021.96-.2566 1.964-.344 2.934-.5698 2.077-.4837 4.138-1.0388 6.219-1.5014 1.108-.2462 2.254-.3206 3.368-.5433 1.842-.3681 3.676-.7747 5.504-1.2057.572-.1348 1.098-.4761 1.671-.5864.652-.1253.985.1944.995.922.033 2.2631-.564 2.9579-2.999 3.4942-1.144.2519-2.266.6055-3.399.908-.182.0487-.372.0706-.558.1049-.002-.0131-.005-.0263-.007-.0395ZM21.6416 103.126c1.2027-.27 2.4018-.558 3.6093-.806 1.1539-.236 2.3118-.463 3.4767-.634 1.3661-.202 2.7597-.222 4.032-.89.3099-.163.7497-.081 1.1298-.111.2992-.024.6104-.003.8956-.079 1.0186-.272 2.0205-.6075 3.0432-.8615 2.1172-.5258 4.2418-1.0223 6.367-1.515.9115-.2113 1.8362-.3657 2.7474-.5782.786-.1833 1.3557.1975 1.6942.7832.3724.6445-.0204 2.1015-.5977 2.3685-.981.454-1.9807.916-3.0224 1.179-1.5931.403-3.237.601-4.8441.955-2.2334.492-4.4452 1.083-6.6813 1.561-1.1257.241-2.2955.273-3.4262.496-2.1099.415-4.2008.926-6.309 1.35-1.9933.401-4.0073.702-5.9962 1.122-1.7038.36-3.3748.875-5.0792 1.231-1.5967.333-3.22721.504-4.82652.827-1.48255.299-2.93352.756-4.41813 1.042-.78085.15-1.62961.213-2.3978.062-.42241-.083-.9735104-.656-1.03471026-1.071-.05052644-.342.45004726-.957.85046926-1.143 2.100941-.975 4.279561-1.721 6.579681-2.142 2.84191-.52 5.66851-1.135 8.48211-1.792 1.766-.413 3.4952-.981 5.2437-1.469.144-.04.3091-.005.4644-.005l.0177.12ZM53.1678 124.427c1.0383.08 1.9326 1.009 1.5897 1.899-.3025.784-.799 1.584-1.4239 2.137-1.4683 1.299-3.1162 2.395-4.598 3.681-2.7855 2.416-5.5274 4.884-8.2438 7.377-1.6999 1.56-3.2968 3.232-4.9835 4.807-1.3706 1.279-2.8102 2.485-4.2119 3.732-2.5456 2.265-5.0834 4.538-7.6292 6.803-1.0134.901-2.0214 1.81-3.0662 2.674-.6623.548-1.3075 1.089-2.3359.898-.7068-.131-.8699-.444-.7649-1.021.1716-.942.5545-1.733 1.345-2.391 1.0311-.858 1.9071-1.899 2.877-2.833 1.0344-.996 2.0902-1.971 3.1547-2.935 2.3629-2.141 4.7258-4.283 7.1132-6.397.7663-.678 1.6499-1.226 2.4039-1.916.5922-.543 1.0327-1.246 1.6042-1.815.6185-.615 1.3242-1.142 1.9685-1.732 2.0325-1.864 4.0481-3.746 6.0819-5.608 1.2801-1.172 2.5642-2.34 3.8775-3.475 1.2006-1.037 2.4239-2.051 3.6766-3.025.4639-.36 1.0401-.578 1.5651-.86ZM247.792 31.6815c.058-1.0706.831-1.7639 1.506-2.4391.99-.9896 2.104-1.856 3.17-2.7691 1.382-1.1842 2.778-2.3534 4.153-3.546 2.034-1.7648 4.04-3.5632 6.09-5.3105 1.147-.9781 2.375-1.862 3.535-2.8251 1.147-.9514 2.259-1.9451 3.379-2.9279.701-.6154 1.367-1.2728 2.089-1.8628 2.042-1.66876 4.086-3.33646 6.172-4.9503.564-.43694 1.264-.71584 1.929-1.00418.698-.30253 1.829.12231 2.155.74798.348.66698.051 1.67089-.56 2.15317-1.709 1.34878-3.396 2.72606-5.092 4.09083-.379.3046-.772.5916-1.141.9079-1.522 1.3064-3.031 2.6269-4.556 3.9306-1.216 1.0399-2.447 2.0624-3.67 3.0933-1.965 1.6553-3.939 3.3009-5.892 4.9697-1.94 1.657-3.82 3.3867-5.803 4.9901-1.272 1.0286-2.69 1.8767-4.027 2.8266-.427.303-.777.7154-1.212 1.0044-1.13.7513-2.102.268-2.225-1.0796ZM54.1316 73.4234c-.0704.8109-1.0111 1.6943-1.7702 1.6464-.8113-.0512-1.6286-.0609-2.4323-.1695-2.3586-.3185-4.7087-.7008-7.0686-1.0093-1.0723-.1402-2.1608-.1537-3.2402-.2456-1.4979-.1276-2.9956-.4043-4.4905-.3854-2.6717.0338-5.2388-.9413-7.9476-.6422-1.0362.1145-2.1285-.3697-3.2051-.5006-1.4013-.1705-2.8144-.2428-4.2187-.3921-.9314-.0991-1.8535-.2846-2.7848-.3853-1.2266-.1327-2.4736-.1374-3.6815-.3601-.6548-.1208-1.3538-.4665-1.8364-.9188-.4719-.4424-.7535-1.265-.1902-1.7885.4795-.4456 1.2459-.8564 1.8666-.8308 2.2688.0932 4.5302.3703 6.7935.5877 2.2734.2184 4.5488.4205 6.8175.6801 2.6175.2994 5.2241.6983 7.8442.9699 1.99.2062 3.999.2286 5.9898.4288 1.9444.1955 3.873.5424 5.8153.7633.9079.1033 1.8442-.0176 2.7457.113 1.3239.1918 2.6473.4506 3.9335.8131.7246.2042 1.1713.7959 1.06 1.6259ZM106.292 137.204c-.58-.091-1.21-.39-1.485-.194-.633.451-1.114.012-1.519-.163-.426-.185-.99-.82-.931-1.163.083-.487.602-1.038 1.079-1.282.504-.258 1.184-.153 1.774-.27.702-.138 1.399-.319 2.084-.526 1.4-.423 2.783-.901 4.187-1.31 1.603-.467 3.224-.871 4.83-1.329 1.207-.343 2.397-.743 3.606-1.075.16-.044.392.169.516.228 1.345-1.251 3.188-.935 4.725-1.579.066.226.133.451.227.771.136-.147.198-.201.246-.267.176-.24.302-.632.529-.701 1.488-.453 2.994-.847 4.499-1.241 2.111-.552 4.221-1.107 6.341-1.623 1.839-.447 3.695-.819 5.534-1.264 1.416-.342 2.812-.761 4.224-1.118 2.022-.511 4.046-1.013 6.077-1.488 1.111-.26 2.242-.433 3.353-.691.663-.155 1.296-.434 1.958-.597 2.201-.545 4.403-1.087 6.616-1.582 1.426-.319 2.871-.555 4.308-.822.844-.157 1.694-.282 2.53-.472.161-.036.269-.305.416-.485.121.189.203.318.176.277.548-.138.981-.258 1.419-.354.706-.155 1.419-.274 2.121-.442 1.551-.372 3.087-.806 4.645-1.137 1.837-.391 3.694-.685 5.537-1.049 1.455-.288 2.899-.632 4.353-.927 1.299-.263 2.602-.512 3.909-.73 1.178-.197 2.451-.125 3.528-.556 2.126-.853 4.451-.67 6.569-1.481.449-.171 1.021-.025 1.765-.025.76-.214 1.779-.559 2.825-.78 1.058-.224 2.143-.326 3.176-.502.718-.11 1.442-.191 2.152-.336 1.9-.389 3.795-.807 5.692-1.21.362-.077.728-.142 1.093-.209 1.713-.311 3.417-.71 5.144-.912 2.864-.334 5.755-.7 8.386 1.037.804.531 1.799.817 2.51 1.439 1.267 1.108 2.705 1.94 4.062 2.903 2.115 1.501 4.171 3.095 6.16 4.758.662.552 1.069 1.422 1.536 2.181.116.188.053.519.003.77-.477 2.378-2.195 3.512-4.309 4.259-.704.25-1.381.577-2.077.852-1.227.486-2.411.965-3.799 1.08-1.324.11-2.597.842-3.894 1.297-.408.143-.814.299-1.232.406-1.286.329-2.575.647-3.867.951-1.143.268-2.308.459-3.435.782-.978.279-1.903.738-2.876 1.039-1.358.419-2.756.715-4.106 1.157-1.624.531-3.21 1.176-4.825 1.738-1.022.356-2.066.651-3.102.968-.168.052-.354.052-.516.117-1.523.607-2.995 1.424-4.574 1.79-2.63.61-5.008 1.869-7.578 2.627-2.336.688-4.573 1.704-6.854 2.575-1.754.67-3.49 1.395-5.269 1.992-1.371.46-2.861.609-4.18 1.172-1.359.58-2.67 1.157-4.147 1.442-1.084.209-2.075.876-3.12 1.309-.931.386-1.882.721-2.818 1.096-1.719.691-3.43 1.406-5.152 2.091-1.962.78-3.936 1.528-5.897 2.31-1.552.619-3.08 1.302-4.641 1.898-2.387.91-4.803 1.742-7.186 2.661-1.538.593-3.011 1.356-4.561 1.91-1.564.558-3.304.729-4.746 1.487-1.174.616-2.4.897-3.604 1.31-1.03.354-2.114.552-3.176.811-.667.162-1.367.235-2 .48-1.208.47-2.359.012-3.522-.117-1.566-.173-2.862-.864-3.96-2.06-1.003-1.092-2.222-1.984-3.314-2.999-.378-.352-.637-.828-.991-1.209-.273-.295-.615-.524-.916-.793-.606-.542-1.198-1.1-1.809-1.636-.81-.71-1.684-1.354-2.438-2.118-.847-.859-1.585-1.826-2.382-2.735-.961-1.098-1.977-2.153-2.889-3.29-.586-.728-1.04-1.563-1.529-2.365-.319-.523-.566-1.09-.894-1.608-.999-1.581-1.429-3.2-.3-5.149Zm52.059-13.129c-1.36.355-2.818.768-4.293 1.114-1.982.464-3.981.857-5.964 1.318-1.815.423-3.62.889-5.425 1.351-1.344.343-2.68.716-4.023 1.065-1.731.448-3.459.912-5.2 1.319-1.639.383-3.295.688-4.939 1.049-.718.158-1.43.349-2.136.558-1.873.554-3.736 1.145-5.614 1.683-1.593.456-3.238.757-4.789 1.32-1.049.381-1.951.843-2.614-.189-.279.377-.501.991-.834 1.058-.676.137-1.223.238-1.495.968-.104.281-.375.519-.614.729-1.181 1.036-1.353 1.992-.515 3.372.727 1.2 1.417 2.437 2.283 3.534 1.299 1.646 2.716 3.203 4.123 4.762 1.012 1.122 2.061 2.213 3.145 3.265.923.897 1.961 1.678 2.873 2.585.956.951 1.747 2.075 2.749 2.968 1.093.974 2.239 2.009 3.888 1.894 1.166-.082 2.396-.017 3.472-.385 1.061-.363 2.064-.852 3.209-.938.392-.03.789-.138 1.159-.275.839-.311 1.648-.704 2.495-.987 1.211-.404 2.458-.703 3.662-1.123.543-.189.995-.631 1.535-.835.853-.324 1.752-.527 2.621-.814 1.053-.346 2.106-.698 3.139-1.1.793-.309 1.544-.722 2.332-1.046.897-.369 1.82-.674 2.72-1.038.998-.403 1.972-.869 2.976-1.255.776-.298 1.602-.47 2.373-.778 1.944-.777 3.868-1.608 5.806-2.402 2.205-.904 4.414-1.8 6.628-2.685 2.066-.826 4.135-1.648 6.214-2.441 1.222-.467 2.441-1.081 3.71-1.236.879-.108 1.407-.69 2.163-.892.717-.191 1.406-.485 2.115-.711 1.031-.328 2.077-.609 3.1-.959.987-.337 1.953-.735 2.928-1.108 1.266-.485 2.527-.987 3.8-1.456 1.813-.668 3.635-1.312 5.453-1.967.637-.23 1.268-.482 1.912-.692 1.66-.541 3.334-1.04 4.988-1.599 2.199-.744 4.38-1.544 6.579-2.289.742-.251 1.536-.355 2.271-.621 1.03-.372 2-.923 3.045-1.235 1.626-.487 3.299-.819 4.942-1.255.815-.216 1.596-.56 2.412-.772 2.668-.696 5.346-1.355 8.018-2.037.456-.116.9-.277 1.35-.417 1.26-.392 2.554-.702 3.769-1.201 1.088-.447 2.387-.577 3.144-1.64-.795-.779-1.486-1.561-2.283-2.214-1.231-1.008-2.534-1.929-3.808-2.883-.552-.413-1.093-.845-1.671-1.218-.921-.595-1.926-1.074-2.794-1.735-1.257-.958-2.511-1.794-4.198-1.582-2.12.267-4.249.47-6.36.792-1.325.202-2.618.608-3.938.855-1.231.23-2.539.196-3.705.592-1.906.649-3.949.605-5.829 1.343-.552.216-1.245.045-1.855.154-1.489.266-2.962.62-4.451.885-1.575.28-3.164.474-4.74.749-2.267.396-4.532.803-6.788 1.257-1.922.387-3.831.844-5.744 1.277-1.192.27-2.372.6-3.572.819-1.56.285-3.146.431-4.7.739-1.547.308-3.059.787-4.603 1.109-1.932.404-3.895.666-5.821 1.098-2.034.456-4.036 1.058-6.06 1.56-.75.185-1.525.268-2.259.393.714 1.229 1.287 2.306 1.945 3.329.999 1.554 1.859 1.878 3.273 1.437 1.137-.355 2.295-.644 3.447-.95.865-.231 1.735-.443 2.805-.714-.327-.403-.532-.628-.705-.874-.38-.542-.067-1.44.532-1.39.555.047 1.213-.055 1.561.745.19.435.862.92 1.322.925.888.009 1.787-.274 2.667-.494 2.722-.679 5.433-1.406 8.159-2.074 1.205-.296 1.499-1.22.714-2.254-.19-.249-.147-.674-.212-1.018.501-.015.975-.774 1.472-.159.464.574.919 1.214 1.146 1.901.225.677.572.588 1.036.46.305-.084.601-.2.908-.276 2.573-.635 5.148-1.265 7.712-1.894-.04-.212-.041-.283-.068-.344-.381-.864-.06-1.518.743-1.827.643-.248.886.272 1.188.81.244.433.637.998 1.488.612.812-.368 1.766-.429 2.658-.619 1.085-.232 2.172-.461 3.259-.686 1.337-.276 2.675-.544 4.012-.82.701-.145 1.396-.32 2.1-.446.848-.152 1.287-.533.878-1.405.389-.273.723-.507 1.067-.749.409.547.787 1.052 1.152 1.539 1.406-.276 2.781-.598 4.174-.803 1.018-.15 2.068-.254 3.084-.16.425.039 1.015.588 1.128 1.012.099.372-.242 1.092-.6 1.306-.691.413-1.52.613-2.312.833-1.108.308-2.233.553-3.431.845.463.844.81 1.692 1.348 2.395.575.751 1.244 1.499 2.03 2.001.794.507.049.888.042 1.291-.003.198-.542.516-.866.556-.879.107-1.801-.035-2.652.158-1.33.303-2.609.819-3.921 1.208-1.806.536-3.622 1.042-5.435 1.552-.803.226-1.775.256-2.139 1.137-.308.747-.793.709-1.261.429-.748-.448-1.458-.102-2.16-.017-.652.078-1.273.398-1.915.589-1.848.551-3.684 1.155-5.557 1.605-.929.223-1.564.446-1.177 1.514-.745.552-1.449.884-2.138.061-.379-.452-.831-.466-1.325-.3-.615.207-1.212.475-1.835.651-1.201.34-2.419.619-3.621.953-1.149.318-2.281.694-3.432 1.004-.672.181-1.367.282-2.056.42.086.335.085.41.12.459.562.764.383 1.58-.277 2.009-.589.383-1.403.445-1.999-.36-.568-.765-1.274-1.44-2.379-.862-.211.111-.401.3-.623.348-1.577.339-3.163.639-4.735.999-.112.025-.245.462-.184.649.224.692.687 1.345.745 2.038.045.531-.306 1.157-.642 1.626-.127.177-.874.192-1.05.007-.766-.804-1.563-1.636-2.075-2.602-.319-.603-.68-.598-1.101-.524-.551.096-1.065.386-1.613.509-1.245.278-2.515.455-3.743.788-.292.079-.708.675-.641.918.211.774.507 1.582.989 2.211.565.737.312 1.216-.259 1.615-.494.345-1.105.638-1.65.009-.449-.518-.913-1.027-1.313-1.582-.462-.642-.861-1.33-1.158-1.794-2.102.541-3.968 1.02-5.903 1.518.062.181.156.499.278.805.137.343.317.669.447 1.014.254.671-.151 1.938-.658 2.113-.855.297-2.275-.424-2.551-1.294-.3-.944-1.242-1.508-2.191-1.249-1.161.318-2.302.705-3.461 1.031-1.046.294-2.108.529-3.151.83-.219.063-.387.302-.538.427 1.073 1.896 2.866 3.349 2.784 5.731h-1.509l.512-.47c-.538-.233-1.19-.348-1.587-.728-.639-.61-1.106-1.398-1.652-2.106-.205-.267-.522-.487-.629-.785-.335-.936-.951-1.026-1.795-.768-1.132.347-2.267.709-3.426.937-1.658.327-3.339.538-4.91.783-.165-.496-.273-.821-.408-1.229 1.326-.323 2.731-.625 4.053-1.258 1.39-.666 2.884-1.118 4.229-1.625-.767-1.156-1.375-2.096-2.011-3.017-.249-.361-.591-.66-.832-1.025-.492-.744-.913-1.537-1.438-2.257-.122-.166-.573-.221-.82-.149-1.325.384-2.613.915-3.953 1.225-2.267.525-4.559.945-6.85 1.362-.974.177-1.792-.437-1.514-1.14.165-.419.761-.774 1.24-.943 1.195-.425 2.444-.694 3.652-1.087 1.213-.394 2.405-.852 3.598-1.303.81-.306 1.606-.649 2.519-1.021-.91-1.326-1.748-2.546-2.619-3.815.44-.212.706-.339 1.126-.542.908 1.035 1.832 2.088 2.754 3.142.406.463.694.893 1.512.47 1.02-.528 2.173-.826 3.295-1.126 1.997-.533 4.014-.993 6.015-1.483-.245-1.319-1.19-2.492-.274-3.786 1.753.175 2.322 1.654 3.207 2.981 2.563-.607 5.202-1.233 7.95-1.884-1.217-1.554-1.37-2.495-.471-3.299.537.635 1.225 1.193 1.552 1.913.299.658.63.95 1.279.841.822-.137 1.631-.351 2.445-.535.901-.203 1.8-.414 2.702-.613.762-.167 1.527-.321 2.166-.455-.822-1.851-1.544-3.474-2.275-5.121Zm-13.068 18.962c-1.061-1.922-2.043-3.733-3.071-5.517-.107-.187-.508-.353-.726-.307-1.672.353-3.341.727-4.993 1.163-1.464.387-2.905.861-4.347 1.294.113.177.358.544.584.922.325.544.508 1.281.981 1.608 1.15.798 1.837 1.888 2.513 3.047.229.394.613.724 1.31.419 1.45-.635 2.976-1.103 4.48-1.61 1.083-.365 2.182-.682 3.269-1.019Zm30.273-13.82c.888 1.458 1.637 2.771 2.488 4.016.161.236.758.351 1.09.269 1.59-.392 3.156-.88 4.735-1.318 1.66-.46 3.33-.883 4.982-1.366.408-.119.795-.374 1.128-.644.12-.098.138-.581.062-.621-1.134-.587-1.295-1.856-1.993-2.737-.161-.203-.497-.451-.697-.41-1.094.224-2.166.549-3.253.808-2.831.673-5.666 1.33-8.542 2.003Zm39.794-9.328c-4.362.915-8.658 1.816-12.953 2.717l-.12.35c.846.948 1.668 1.92 2.56 2.824.184.186.649.218.946.151 1.114-.251 2.213-.569 3.316-.869 2.69-.733 5.379-1.469 8.03-2.194-.571-.956-1.177-1.97-1.779-2.979Zm-70.149 16.259c1.337 2.069 2.538 3.93 3.816 5.909.13-.206.171-.357.249-.379 1.596-.456 3.203-.88 4.793-1.356.311-.093.671-.326.804-.595.09-.181-.171-.542-.292-.816-.053-.12-.163-.215-.221-.334-.574-1.164-1.115-2.346-1.735-3.485-.119-.22-.566-.428-.815-.384-.989.177-1.954.475-2.936.693-1.154.256-2.317.475-3.663.747Zm19.625 1.051c-.101-.299-.168-.648-.328-.948-.496-.931-.992-1.865-1.557-2.754-.277-.436-.662-1.021-1.08-1.098-.585-.108-1.252.173-1.873.327-1.248.309-2.477.718-3.738.951-1.339.248-1.4.269-.729 1.502.153.282.362.532.531.805.442.712.965 1.392 1.287 2.155.283.669.794 1.03 1.516.825.597-.169 1.213-.267 1.821-.396-.019-.028-.039-.055-.058-.082 1.388-.425 2.775-.849 4.208-1.287Zm3.448-6.139-.045-.165c-.814.187-1.651.313-2.43.597-.235.086-.526.731-.423.911.646 1.127 1.436 2.171 2.094 3.292.339.578.712.688 1.31.515 1.569-.456 3.152-.869 4.722-1.32 1.487-.428 1.53-.46 1.012-1.679-.406-.957-.899-1.888-1.456-2.766-.176-.277-.713-.519-1.037-.47-.829.125-1.632.417-2.442.655-.439.13-.87.286-1.305.43Zm31.075-7.633c-2.862.692-5.803 1.403-8.981 2.172.953 1.478 1.811 2.811 2.537 3.936 3.167-.897 6.019-1.704 8.96-2.536-.935-1.327-1.693-2.404-2.516-3.572ZM223.329 150.075c.291-.222.636.031 2.125 1.633.687.739 1.476 1.396 2.085 2.191.648.847 1.137 1.814 1.624 2.611-.217.514-.279 1.084-.597 1.342-1.341 1.091-2.706 2.17-4.162 3.097-1.479.941-3.073 1.704-4.623 2.532-2.048 1.095-4.087 2.209-6.16 3.256-1.718.869-3.485 1.643-5.221 2.478-1.511.727-2.999 1.503-4.516 2.217-1.786.842-3.6 1.625-5.389 2.462-2.248 1.054-4.441 2.239-6.737 3.175-1.911.778-3.955 1.225-5.903 1.922-1.279.457-1.984-.404-2.655-1.081-.766-.773-1.325-1.76-1.917-2.69-.536-.844-.98-1.745-1.493-2.603-.671-1.121-1.3-2.276-2.072-3.325-1.419-1.928-2.954-3.77-4.393-5.684-1.145-1.524-2.269-3.07-3.307-4.667-.848-1.305-1.595-2.681-2.291-4.073-.143-.286.003-.94.25-1.151.592-.504 1.3-.894 2.007-1.236.535-.259 1.142-.368 1.714-.553 1.145-.37 2.282-.766 3.433-1.115.938-.284 1.898-.496 2.837-.777.878-.262 1.735-.59 2.611-.855.565-.169 1.15-.267 1.722-.414.331-.086.652-.213.981-.312 1.319-.396 2.637-.797 3.96-1.181 2.271-.659 4.553-1.286 6.818-1.966 1.551-.467 3.08-1.006 4.623-1.503 1.12-.361 2.252-.687 3.368-1.064.955-.322 1.869-.834 2.847-1.014 1.993-.366 3.785-1.872 5.953-1.159.659.216 1.267.673 1.815 1.121 1.497 1.223 2.926 2.528 4.427 3.746 1.165.945 2.395 1.811 3.6 2.706.847.629 1.701 1.249 2.636 1.934Zm1.614 6.304c-.218-.67-.233-1.327-.569-1.624-.8-.707-1.791-1.194-2.631-1.862-.816-.649-1.975-.792-2.526-1.874-.203-.4-.91-.519-1.329-.842-1.346-1.041-2.662-2.121-3.995-3.179-.857-.681-1.693-1.396-2.596-2.011-.916-.624-1.896-1.203-3.091-.806-.461.153-.888.405-1.348.561-1.472.499-2.958.959-4.428 1.465-1.887.65-3.754 1.361-5.65 1.986-1.279.421-2.591.746-3.89 1.104-1.244.342-2.491.674-3.737 1.006-.647.173-1.3.323-1.943.509-.919.265-1.823.578-2.746.823-.751.198-1.546.251-2.276.5-1.913.652-3.781 1.445-5.709 2.05-1.51.475-3.089.732-4.624 1.138-.268.07-.506.371-.673.621-.038.057.274.354.436.531.31.337.65.65.939 1.004 1.559 1.911 3.053 3.879 4.675 5.737 1.546 1.769 3.154 3.451 4.197 5.617.811 1.687 1.991 3.196 2.845 4.865.931 1.818 1.001 1.923 2.866 1.286 1.383-.473 2.818-.821 4.149-1.407 2.584-1.136 5.118-2.387 7.66-3.617 1.512-.732 2.982-1.553 4.505-2.263 1.331-.621 2.732-1.095 4.062-1.718 1.752-.822 3.468-1.722 5.195-2.598 1.925-.977 3.851-1.951 5.764-2.952 1.596-.836 3.2-1.665 4.748-2.584.659-.39 1.186-1.002 1.72-1.466ZM134.823 114.077c-.421.68-1.069.957-2.139.898-1.06-.058-2.147.438-3.229.657-1.341.271-2.745.854-4.018.651-1.016-.162-1.68.542-2.644.371-.855-.151-1.809.343-2.731.449-.884.102-1.788.026-2.674.115-.691.07-1.362.341-2.053.404-1.576.144-3.163.175-4.738.327-1.232.119-2.449.388-3.68.519-.809.086-1.632.049-2.448.06-1.129.017-2.259.003-3.386.046-1.046.04-2.0884.185-3.1332.195-.6932.006-1.386-.186-2.0822-.217-1.4842-.068-2.8785-.394-4.0826-1.301-.9737-.733-1.8382-1.541-2.1872-2.792-.1213-.436-.562-.772-.7904-1.19-1.0668-1.95-1.3941-4.116-1.7077-6.266-.3731-2.557-.6458-5.129-.9218-7.6985-.3003-2.7964-.5716-5.5962-.8231-8.3975-.2003-2.231-.3097-4.4706-.5384-6.6984-.1865-1.8163-.4923-3.6204-.7407-5.4305-.291-2.1199-.6113-4.2366-.8546-6.362-.1905-1.6647-.2991-3.3395-.4153-5.0117-.1484-2.1382-.2739-4.2781-.3981-6.4178-.1193-2.055-.2216-4.111-.3364-6.1662-.091-1.6278-.2216-3.2541-.2755-4.8831-.0506-1.5275-.0106-3.0577-.0341-4.5864-.0262-1.7095-.0388-3.4208-.1327-5.1272-.0751-1.3624-.2729-2.7178-.3954-4.0783-.0373-.4145-.0363-.8379.0004-1.2526.1807-2.0413.3265-4.0885.6171-6.1148.0567-.3955.7003-.7074.8738-.8705.1214-.5522.0866-1.0093.2989-1.2504.7961-.9041 1.572-1.8867 2.5536-2.5475.6986-.4703 1.7046-.5637 2.5918-.6644 2.1857-.2482 4.3841-.3825 6.5734-.6018 2.65-.2655 5.2974-.5602 7.9424-.8668.729-.0845 1.443-.3039 2.173-.3771 1.234-.1238 2.477-.1627 3.714-.2722.755-.0669 1.502-.2229 2.257-.2964 1.458-.1417 2.926-.1999 4.377-.3922 1.52-.2016 3.02-.5553 4.539-.7715.715-.1018 1.462.0235 2.182-.0598 2.066-.2388 4.127-.5318 6.189-.8023.067-.0087.152-.032.2-.0026 1.124.6829 2.155-.0875 3.22-.2193.811-.1002 1.568-.2161 2.428-.1061 1.022.1306 2.108-.345 3.176-.4482 1.801-.1739 3.613-.2239 5.413-.4002.957-.0936 1.891-.3974 2.847-.5108 1.823-.2165 3.653-.3876 5.483-.5355 2.726-.2202 5.453-.4172 8.181-.5964 1.067-.07 2.143-.0085 3.206-.1084 1.301-.1223 2.588-.4037 3.889-.5199 1.429-.1275 2.872-.0981 4.301-.2271.973-.0879 1.926-.4148 2.898-.4826 1.171-.0817 2.36.0837 3.528-.0169 1.124-.0968 2.224-.4385 3.346-.5926.836-.1149 1.694-.0622 2.535-.1543 1.961-.2149 3.916-.496 5.878-.7028 1.123-.1183 2.26-.1016 3.383-.2208 1.543-.1637 3.076-.4134 4.617-.5948.515-.0607 1.042-.0127 1.563-.0357.781-.0344 1.561-.0824 2.341-.135.377-.0254.754-.073 1.131-.1133.958-.1027 1.916-.212 2.875-.3083.452-.0453.906-.0736 1.36-.098 1.67-.0898 3.34-.2279 5.012-.2477 2.047-.0243 4.111-.0926 6.137.13 1.658.182 3.287.7121 4.894 1.2002.438.133.781.6473 1.115 1.0313.326.3744.681.7695.856 1.2201.371.9594.747 1.9415.918 2.9486.388 2.2807.763 4.5737.94 6.8773.247 3.198.309 6.4101.446 9.6163.033.7631.045 1.5271.074 2.2904.068 1.7752.148 3.5499.209 5.3254.068 1.9936.113 3.9881.183 5.9817.076 2.1695.109 4.3429.274 6.5061.123 1.6089.467 3.1999.634 4.807.104.9977.024 2.0133.096 3.0157.092 1.262.263 2.5181.385 3.7781.092.9464.19 1.8937.233 2.8429.064 1.4429.092 2.8876.12 4.3318.04 2.1547.249 4.3268.048 6.4597-.21 2.2179-.638 4.4565-1.317 6.5761-.55 1.7178-1.688 3.1266-3.281 4.2549-2.124 1.5057-4.605 1.9216-6.93 2.8052-1.898.7213-3.829 1.3694-5.776 1.9442-1.162.343-2.393.4462-3.577.7228-1.136.2651-2.26.5884-3.374.9357-.96.2995-1.891.693-2.848 1.0016-1.631.5256-3.272 1.0215-4.911 1.5218-1.928.5883-3.86 1.1613-5.787 1.7533-1.7.524-3.387 1.089-5.094 1.589-.875.256-1.782.4-2.67.613-1.242.298-2.478.62-3.72.919-1.002.242-2.011.452-3.011.697-1.366.335-2.717.732-4.092 1.023-1.473.313-2.969.52-4.45.799-1.16.219-2.309.498-3.469.714-1.146.213-2.26.398-3.39.825-1.793.677-3.763.885-5.654 1.309-2.1.47-4.204.924-6.288 1.454-1.304.331-2.567.821-3.865 1.179-.617.17-1.281.157-1.909.294-1.396.306-2.776.683-4.175.976-1.02.213-2.056.37-3.093.484-.289.032-.604-.179-.985-.304ZM93.638 26.2674c-.1926.1375-.4595.4852-.7544.5106-1.1097.0953-2.2295.0662-3.3432.1258-.4043.0216-1.0089.0259-1.1694.2692-.9939 1.5065-2.2468 2.8423-2.7184 4.6925-.494 1.938-.5357 3.8926-.5805 5.8503-.0489 2.1362.0397 4.2757.077 6.4135.0435 2.4889.0713 4.9784.1532 7.4661.0641 1.9449.1937 3.8877.3069 5.8308.0826 1.4161.1946 2.8305.2751 4.2467.0292.5141-.0328 1.035.021 1.5451.0277.2632.2999.503.3209.7645.1037 1.2885.1226 2.5842.2433 3.8706.1437 1.5323.3598 3.0578.546 4.586.1968 1.616.3992 3.2313.5914 4.8478.0775.6513.1496 1.3041.1933 1.9582.0176.2638-.0853.5359-.066.7994.0302.4136.1828.8259.1654 1.2338-.026.6113.2389 1.1507.2081 1.8114-.0685 1.4655.3772 2.951.5684 4.4341.1009.7834.0889 1.5805.1608 2.3684.1706 1.8707.3468 3.7412.5477 5.6089.1648 1.533.3673 3.062.5552 4.5929.292 2.377.4886 4.772.9053 7.128.4474 2.529.9957 5.074 2.8966 7.017.3915.4.9229.883 1.4206.921 1.5896.119 3.1937.045 4.7922.049 1.6555.004 3.3145.071 4.9675 0 1.248-.054 2.492-.255 3.731-.437 1.365-.201 2.715-.522 4.085-.671 1.639-.179 3.322-.074 4.929-.386 1.467-.284 2.971-.237 4.424-.713 1.282-.419 2.667-.546 4.015-.732 1.173-.162 2.37-.155 3.536-.348 1.868-.309 3.726-.691 5.576-1.098 1.55-.342 3.078-1.051 4.625-1.081 2.117-.04 3.959-.966 5.966-1.321 2.429-.43 4.799-1.194 7.2-1.789 1.358-.336 2.725-.642 4.096-.927 1.383-.287 2.781-.502 4.162-.801 1.381-.3 2.746-.678 4.124-.991.419-.095.875-.034 1.29-.139.971-.246 1.916-.601 2.893-.817 1.022-.227 2.08-.294 3.103-.519 1.846-.406 3.684-.851 5.513-1.327 2.71-.707 5.415-1.4346 8.11-2.1952 1.266-.3574 2.501-.8265 3.758-1.2196 1.327-.415 2.66-.8128 3.998-1.1938 1.174-.3344 2.311-.7762 3.462-1.1673 2.246-.7629 4.568-1.3063 6.866-1.915 1.474-.3905 2.972-.6953 4.438-1.1129 1.232-.3509 2.425-.838 3.65-1.2134 1.842-.5642 3.709-1.0467 5.542-1.6365.977-.3144 1.894-.8083 2.857-1.1736 1.931-.7333 3.029-2.139 3.533-4.1028.567-2.213.408-4.4736.549-6.716.202-3.2138-.049-6.402-.398-9.5916-.13-1.1966-.151-2.405-.226-3.6077-.067-1.0831-.142-2.1656-.207-3.2488-.015-.2549-.002-.5115-.002-.7674-.008-.3373-.257-.6684-.307-1.027-.133-.9553-.189-1.9217-.261-2.8848-.17-2.28-.325-4.5612-.503-6.8406-.056-.7153-.234-1.4253-.244-2.1392-.035-2.7444-.033-5.4895-.029-8.2343.003-1.4095.086-2.8202.051-4.2282-.044-1.7305-.17-3.459-.269-5.1878-.024-.4133-.034-.8365-.134-1.2347-.281-1.1312-.093-2.2906-.324-3.4436-.435-2.171-.552-4.4047-.972-6.5795-.251-1.3025-.572-2.7475-2.356-2.9183-.565-.0541-1.126-.179-1.691-.1933-1.932-.0489-3.866-.1287-5.795-.071-1.782.0533-3.559.3544-5.341.3872-1.683.031-3.34.1694-5.007.4046-1.809.2553-3.645.3268-5.468.4891-1.909.1699-3.818.3417-5.725.5328-1.452.1455-2.899.3391-4.352.4797-.918.0889-1.843.1023-2.762.1801-1.791.1517-3.579.3324-5.369.4865-1.268.1091-2.539.1889-3.807.2916-1.326.1072-2.652.3283-3.976.3097-1.207-.0169-2.358.6678-3.632.1257-.44-.1875-1.129.276-1.715.3404-1.222.1342-2.452.1948-3.678.2962-1.34.1109-2.681.215-4.018.3563-1.597.1688-3.185.4231-4.785.5513-2.217.1777-4.447.2119-6.661.4199-2.199.2067-4.382.5877-6.579.8274-2.346.2558-4.701.4224-7.049.6531-1.911.1877-3.818.419-5.728.6187-1.32.138-2.645.2372-3.964.3866-1.385.1568-2.762.3815-4.149.5234-1.415.1449-2.844.173-4.256.3474-1.584.1959-3.152.5301-4.735.7446-1.325.1796-2.663.2604-3.993.4095-1.025.115-2.043.2904-3.069.3984-1.089.1147-2.1864.1545-3.2745.2763-1.3201.1479-2.6326.3644-3.9533.5051-.1863.0198-.4007-.2217-.6022-.3423Z" fill="#000"/>
+ <path d="M230.65 122.39c-.336.199-.59.349-1.037.612-.451-.578-.907-1.191-1.393-1.78-.446-.54-.975-1.019-1.373-1.59-.531-.765-.996-1.578-1.441-2.397-.543-.998-1.136-1.988-1.511-3.05-.214-.606-.039-1.35-.039-2.062.227-.07.543-.169 1.058-.33.963 1.714 1.852 3.514 2.945 5.181 1.129 1.722 2.466 3.309 2.791 5.416Z" fill="#000"/>
+ <path d="M287.826 105.728c-.194-.026-.59-.082-.987-.136-.245-.033-.495-.043-.735-.097-1.33-.299-2.644-.391-3.911-1.229-.728-.481-1.555-1.061-2.152-1.602-.802-.726-1.111-2.024-1.548-3.1103-.7-1.7351-.768-3.529-.462-5.3751.193-1.1693.536-2.1435 1.609-2.8148.431-.2694.635-.8784 1.043-1.2092 1.073-.8703 2.227-1.6415 3.302-2.5101 1.483-1.1979 2.922-2.4489 4.38-3.6774.403-.3395.812-.6716 1.206-1.0213 1.64-1.4576 2.934-3.235 3.816-5.1823.75-1.6579.662-3.5174-.209-5.2655-.688-1.3805-1.382-2.7604-2.528-3.8005-.989-.8969-2.02-1.8643-3.214-2.392-1.562-.6905-3.282-1.2242-4.973-1.3716-1.689-.1471-3.451.1426-5.135.4717-1.37.2675-2.742.7389-3.985 1.3714-1.332.6782-2.519 1.643-3.758 2.4977-.463.3193-.913.662-1.341 1.0271-1.037.8858-2.124 1.7283-3.066 2.7078-.795.8277-1.485 1.78-2.094 2.756-.716 1.1453-1.071 2.4052-1.345 3.7704-.379 1.8814.774 3.2398 1.084 4.8584.14.7283 1.034 1.2823 1.447 1.9953.889 1.537 1.481 3.292 2.58 4.6482 1.185 1.4636 1.306 3.2631 2.12 4.818.314.5979.182 1.414.439 2.0565.653 1.6301-.021 3.1926-.167 4.7706-.046.488-.589.936-.918 1.392-1.675 2.323-5.764 3.093-8.265 1.547-1.682-1.041-3.286-2.232-5.045-3.118-1.569-.79-3.341-1.119-4.928.036-.628.457-.547 1.293-.526 2.062.019.692-.208 1.391-.366 2.32 1.402.921 3.229 1.878 4.751 3.189 1.458 1.256 3.17 2.055 4.68 3.168 1.524 1.123 3.336 1.854 4.711 3.057 1.372 1.2 3.039 1.768 4.451 2.827 1.975 1.482 4.171 2.666 6.213 4.064 1.602 1.096 3.062 2.399 4.68 3.467 1.339.885 1.679 2.219 2.1 3.583.515 1.665.496 3.336.427 5.061-.055 1.394.449 2.8.545 4.211.177 2.629.212 5.245-1.489 7.537-.588.793-.912 1.784-1.521 2.556-.604.767-1.429 1.358-2.129 2.054-1 .994-1.926 2.067-2.973 3.008-1.212 1.09-2.369 2.242-3.944 2.899-.97.405-1.774 1.191-2.681 1.759-1.337.837-2.71 1.617-4.049 2.452-1.072.669-2.067 1.479-3.183 2.058-1.734.9-3.553 1.635-5.316 2.482-1.385.664-2.731 1.408-4.109 2.087-1.097.54-2.223 1.023-3.326 1.553-1.744.837-3.464 1.724-5.223 2.526-.924.421-1.93.663-2.863 1.068-.769.334-1.468.825-2.229 1.183-1.887.889-3.787 1.753-5.691 2.606-1.084.485-2.196.91-3.28 1.398-.969.436-1.899.958-2.877 1.371-.714.301-1.506.424-2.212.74-.96.43-1.872.969-2.806 1.458-1.195.627-2.384 1.268-3.591 1.871-1.858.929-3.718 1.854-5.599 2.737-1.191.559-2.429 1.016-3.629 1.557-1.728.779-3.434 1.608-5.163 2.386-.985.443-2.002.817-2.997 1.239-1.457.617-2.909 1.246-4.359 1.877-1.869.812-3.752 1.597-5.598 2.459-1.433.67-2.803 1.474-4.234 2.151-.91.431-1.891.711-2.818 1.108-.692.296-1.366.643-2.018 1.019-1.344.775-2.591 1.795-4.023 2.317-1.227.448-2.176 1.537-3.668 1.459-.491-.025-.986.758-1.539 1.06-1.732.946-3.499 1.829-5.241 2.756-1.576.839-3.124 1.732-4.711 2.55-1.761.909-3.538 1.794-5.338 2.625-1.13.521-2.302.966-3.484 1.359-.454.152-1.004.154-1.484.071-1.1-.191-2.193-.172-3.301-.179-.773-.005-1.593-.278-2.303-.616-.788-.375-1.534-.894-2.194-1.469-.899-.782-1.631-1.762-2.558-2.502-1.467-1.17-2.215-3.041-3.952-3.925-.059-.03-.151-.049-.169-.096-.59-1.521-2.038-2.327-2.99-3.549-.92-1.181-1.984-2.249-2.97-3.378-1.007-1.153-1.988-2.328-3-3.476-.255-.289-.614-.486-.877-.769-1.242-1.339-2.484-2.678-3.69-4.048-.563-.639-1.01-1.378-1.573-2.016-.377-.428-.912-.716-1.294-1.141-2.006-2.229-3.98-4.487-5.982-6.721-.363-.406-.846-.709-1.197-1.123-.732-.866-1.255-2.021-2.16-2.593-.854-.541-1.212-1.356-1.839-1.997-1.151-1.177-2.159-2.492-3.292-3.689-.906-.955-1.941-1.79-2.856-2.737-.484-.501-.806-1.154-1.254-1.694-1.0989-1.327-2.4417-2.51-3.271-3.984-.5444-.967-1.3588-1.572-1.9666-2.403-.4063-.556-.6983-1.196-1.1159-1.742-.9516-1.244-1.9664-2.44-2.9207-3.682-.5147-.67-.9224-1.422-1.4405-2.089-.9381-1.208-1.948-2.36-2.8785-3.574-.5659-.738-1.0416-1.545-1.5535-2.324-.6983-1.062-1.4822-2.081-2.0661-3.203-.761-1.463-1.3352-3.014-1.4331-4.696-.0479-.821-.1659-1.641-.1666-2.461-.0002-.225.3086-.451.5736-.808-.0788-.032-.3511-.142-.6868-.277.0657-.089.2683-.338.2561-.349-1.0745-.962-.536-2.623-1.6003-3.604-.704-.649-.8129-1.747-1.3475-2.399-.8482-1.034-.8415-2.251-1.2765-3.35-.5285-1.335-.813-2.771-1.1403-4.178-.1309-.562-.0391-1.174-.1436-1.746-.4767-2.609-1.0045-5.209-1.4759-7.819-.1609-.89-.1733-1.807-.3208-2.701-.1807-1.095-.4697-2.173-.645-3.268-.3521-2.201-.6634-4.408-.9821-6.614-.1305-.903-.5091-1.8839-.2862-2.6962.2975-1.0838-.4008-1.8624-.4066-2.8143-.0061-1.0011-.1246-2.003-.224-3.0017-.2823-2.8377-.6228-5.6705-.8541-8.5122-.1234-1.517-.0382-3.0499-.1087-4.5727-.0298-.6453-.2856-1.2795-.3215-1.9253-.1125-2.0256-.1391-4.0562-.2621-6.0811-.0521-.8579-.3015-1.7023-.3893-2.5602-.1083-1.0588-.1368-2.1255-.2089-3.1881-.0679-.9999-.1881-1.998-.2098-2.9985-.0186-.8571.097-1.7163.1021-2.5749.0042-.7062-.0516-1.414-.1077-2.1189-.0839-1.0542-.2215-2.1048-.2825-3.16-.1193-2.0628-.2107-4.1274-.2953-6.192-.0416-1.0149-.0046-2.0341-.0721-3.0467-.0681-1.0216-.2242-2.0373-.3371-3.0561-.2821-2.5464-.5594-5.0932-.8429-7.6394-.212-1.9044-.497-3.8035-.6299-5.7132-.1706-2.4504-.0061-4.8901.9359-7.1974.5727-1.4032 2.0129-1.4948 3.2238-1.8998.1546-.0517.3307-.0395.5545-.063-.048-.2428-.0901-.4553-.1325-.6698.8105-.2783 1.5922-.6771 2.4162-.8046 2.2802-.3529 4.5844-.5503 6.8668-.8904 1.7991-.268 3.5764-.6779 5.3704-.9833.9966-.1696 2.0071-.2594 3.0125-.3759 2.8061-.3252 5.6162-.619 8.4177-.9794 1.322-.1701 2.6209-.5151 3.9429-.6881 1.329-.174 2.677-.2094 4.011-.3503.874-.0922 1.736-.3538 2.608-.3786 1.251-.0356 2.402-.5531 3.737-.3824 1.164.1487 2.413-.4848 3.64-.6687 1.839-.2757 3.692-.4561 5.538-.6859.718-.0893 1.432-.2083 2.149-.3043 2.256-.302 4.514-.5838 6.766-.90373 1.667-.23665 3.323-.54387 4.991-.77378.846-.11675 1.709-.10872 2.561-.19813 2.004-.21043 4.005-.44485 6.007-.67111.443-.05009.887-.09917 1.328-.16142 1.531-.2158 3.056-.47868 4.592-.64569 1.806-.19638 3.622-.30168 5.432-.46485 1.434-.12936 2.867-.28226 4.3-.4322 1.937-.20277 3.874-.41316 5.811-.61945 1.611-.17154 3.221-.35642 4.834-.50921 2.174-.20596 4.366-.28359 6.521-.61342 1.527-.23381 3.096-.09762 4.6-.64666.676-.24697 1.51-.04999 2.271-.08784.91-.04525 1.818-.1355 2.727-.18989 2.337-.13973 4.68-.21377 7.01-.42265 1.858-.16655 3.702-.49279 5.552-.74958.101-.01391.207-.07647.297-.05689 2.151.46591 4.25-.5661 6.422-.19163.739.12742 1.565-.34392 2.363-.43379 1.134-.12767 2.281-.13649 3.42-.23172 1.098-.09182 2.192-.2273 3.288-.34642 1.95-.21198 3.9-.4178 5.849-.641642 1.96-.225277 3.914-.530295 5.88-.685338 1.491-.1175587 3.003-.1466914 4.492-.037299.894.065712 1.663 1.227849 1.793 2.212789.248 1.86964.725 3.73771.709 5.60301-.01 1.17119.408 2.22704.391 3.37494-.022 1.4888.069 2.9913.263 4.468.25 1.896.7 3.7654.971 5.6593.194 1.3513.306 2.7231.325 4.0875.016 1.1531-.224 2.309-.22 3.4633.003 1.2256.188 2.4495.243 3.6764.075 1.67.083 3.3429.155 5.0131.066 1.5377.2 3.0725.268 4.6101.099 2.2445.159 4.4907.251 6.7355.063 1.524.198 3.0463.215 4.5702.018 1.5855-.089 3.1719-.102 4.7582-.008 1.037.093 2.0753.074 3.1117-.018 1.0118-.338 2.0646-.145 3.0229.283 1.3968.095 2.7707.156 4.1498.095 2.1773.008 4.3619.065 6.5416.075 2.8301.219 5.6582.328 8.4874.075 1.9334.105 3.8693.222 5.7999.122 2.0017.37 3.9963.468 5.9986.038.7558-.188 1.5244-.301 2.3408 1.471.9985 3.056 1.9904 4.545 3.1087 1.26.947 2.405 2.045 3.613 3.062.126.107.383.211.489.152.147-.081.33-.36.288-.479-.437-1.22.314-2.231.83-3.089.451-.7499 1.506-1.2847 2.406-1.5847 1.21-.4037 2.478-.5598 3.833-.3972 1.699.2038 3.197.7932 4.627 1.6099 1.155.661 2.185 1.54 3.352 2.175.667.362 1.499.594 2.25.578.552-.012 1.109-.496 1.636-.816 1.074-.651.931-1.859 1.105-2.8365.125-.6978-.224-1.5114-.473-2.2353-.349-1.0162-.751-2.0222-1.227-2.9853-.403-.8167-.962-1.5559-1.42-2.3476-.999-1.7263-2.065-3.4215-2.937-5.2104-.736-1.5106-1.328-3.1078-1.815-4.7173-.481-1.5875-.237-3.1358.419-4.7168.513-1.2332.852-2.5456 1.652-3.6337.866-1.1781 1.819-2.2938 2.747-3.4262.317-.3875.673-.7441 1.013-1.113 1.246-1.3508 2.677-2.452 4.311-3.3116.639-.3362 1.147-.9266 1.793-1.2421 1.125-.5494 2.289-1.0417 3.478-1.4345 1.17-.3869 2.384-.6569 3.593-.9086.79-.1644 1.603-.2388 2.41-.292 1.004-.0662 2.046-.2442 3.011-.0615 1.803.3409 3.688.3653 5.37 1.2703 1.147.6173 2.48.9644 3.491 1.7406 1.083.8313 1.926 1.9928 2.798 3.0706.556.6872.998 1.4707 1.444 2.2387.181.3115.213.7049.35 1.0464.657 1.6405 1.096 3.3161.941 5.1065-.147 1.6898-.323 3.3446-1.466 4.7541-.562.6941-.869 1.5895-1.403 2.313-.355.4822-.933.795-1.357 1.2355-.235.2439-.292.6698-.542.8851-1.722 1.4875-3.46 2.9576-5.22 4.4002-1.228 1.0063-2.477 1.9913-3.759 2.9272-1.033.7539-1.909 1.555-2.13 2.909-.291 1.7829.301 3.2056 1.414 4.5902.899 1.12 2.216 1.506 3.319 2.242.65.435 1.645.531 2.461.47.401-.03.924-.705 1.088-1.189.534-1.579 1.471-2.7915 2.841-3.7167.843-.5698 1.653-1.1895 2.482-1.7811 1.73-1.2354 3.656-1.9774 5.703-2.574 1.698-.4947 3.379-.8736 5.131-.9428 2.727-.1078 5.411.2465 8.031.9824 1.476.4145 2.915.959 4.367 1.4549.574.1958 1.318.2645 1.665.6654.526.6068 1.222.7457 1.845 1.0709.817.4261 1.695.734 2.516 1.1513 1.837.9332 3.645 1.9234 5.487 2.8457.65.326 1.404.452 2.043.793 1.445.773 2.987 1.458 4.228 2.49 1.111.924 1.984 2.197 2.76 3.441.925 1.483 1.223 3.211 1.62 4.915.623 2.681.765 5.37.569 8.07-.131 1.807-.529 3.606-.939 5.379-.28 1.211-.656 2.44-1.236 3.532-.419.789-1.154 1.496-1.907 2.007-1.433.972-2.946 1.844-4.493 2.626-.838.423-1.992.348-2.688.896-1.131.89-2.469.788-3.682 1.103-2.176.564-4.423.91-6.719.329-1.426-.36-2.931-.398-4.377-.694-1.681-.344-3.367-.718-4.994-1.25-1.765-.578-3.447-1.405-5.2-2.025-1.242-.439-2.537-.736-3.818-1.055-.795-.198-1.476-.43-2.008-1.175-.386-.541-1.125-.832-1.71-1.23-1.354-.923-2.784-1.753-4.038-2.794-.812-.674-1.415-1.623-2.027-2.505-.69-.995-1.416-1.998-1.893-3.098-.704-1.624-1.432-3.297-1.731-5.022-.373-2.157-.412-4.386-.414-6.585 0-.953.451-1.907.782-3.187ZM73.5908 55.1454c-.0281-.9707-.0562-1.9415-.0843-2.9122l-.3509.0163c0 .9214-.0071 1.843.0142 2.764.0016.069.2056.1335.3155.2-.0571.3151-.1693.6323-.1577.9448.0148.4007.1897.7978.1889 1.1963-.0021 1.0608-.11 2.1226-.0849 3.1819.0273 1.1539.1837 2.3045.2256 3.4586.0128.3528-.1664.7125-.1957.8269.1687 1.0917.3588 2.0254.4475 2.9685.1208 1.2839.1428 2.5769.2491 3.8625.056.6765.2615 1.3428.2935 2.0187.0609 1.2856.0085 2.5765.0722 3.8618.0657 1.3246.2119 2.6454.3261 3.9676.0887 1.0261.2064 2.0504.2683 3.0781.0945 1.5676.1555 3.1372.2239 4.7063.0491 1.1268-.1513 2.3335.1931 3.3601.3855 1.1493.2363 2.2565.3286 3.3802.0332.4047-.0208.8162.0079 1.2217.0344.486.1146.9687.1909 1.581.5313.2046.7456-.078.6742-.8649-.1913-2.1093-.3493-4.2224-.4736-6.3367-.1332-2.2651-.1858-4.535-.3242-6.7998-.1114-1.8245-.3243-3.6427-.4434-5.4668-.098-1.5029-.0933-3.0124-.1903-4.5154-.1307-2.0253-.3408-4.0455-.4695-6.0708-.1252-1.969-.1858-3.9419-.2841-5.9126-.0691-1.3848-.086-2.7769-.2521-4.1506-.145-1.1995-.4657-2.3778-.7088-3.5655ZM108.75 157.874c1.533.118 1.692 1.933 2.771 2.788.444.351.674.96 1.043 1.419 1.123 1.402 2.278 2.779 3.397 4.183.654.82 1.227 1.704 1.902 2.505 1.137 1.348 2.35 2.633 3.486 3.982 1.119 1.329 2.167 2.718 3.275 4.057.844 1.019 1.75 1.987 2.6 3.001 1.222 1.457 2.382 2.967 3.635 4.396 1.419 1.617 2.929 3.154 4.362 4.759.567.635.893 1.6 1.573 1.993 1.346.775 2.121 2.032 3.139 3.079 1.079 1.111 2.027 2.356 3.164 3.401.993.914 2.087 1.686 2.15 3.194.002.051.085.099.133.146 1.002.949 2.269 1.268 3.524.962 1.548-.377 3.048-.994 4.525-1.612 2.452-1.025 4.868-2.135 7.301-3.205 1.891-.832 3.783-1.659 5.677-2.483.604-.263 1.232-.476 1.817-.774 1.236-.631 2.432-1.338 3.676-1.949 2.2-1.08 4.434-2.092 6.633-3.173 1.057-.519 2.063-1.14 3.1-1.7 1.01-.545 2.024-1.08 3.046-1.602.727-.372 1.473-.71 2.206-1.072.716-.354 1.429-.714 2.141-1.077 1.256-.641 2.511-1.282 3.763-1.929 1.33-.687 2.666-1.365 3.981-2.081.771-.42 1.478-.963 2.264-1.348 1.529-.752 3.095-1.43 4.644-2.142 1.235-.568 2.489-1.098 3.694-1.724 1.25-.651 2.434-1.427 3.677-2.092 1.274-.68 2.611-1.243 3.872-1.944 1.847-1.027 3.658-2.115 5.655-2.845.252-.092.485-.237.72-.37 2.073-1.176 4.131-2.377 6.221-3.52.863-.473 1.819-.775 2.686-1.239 1.505-.805 2.97-1.685 4.461-2.518 1.019-.569 2.054-1.111 3.082-1.664 1.136-.611 2.266-1.236 3.413-1.827 1.019-.525 2.083-.97 3.085-1.527 1.825-1.014 3.612-2.098 5.429-3.128 1.177-.668 2.399-1.258 3.563-1.947 1.317-.779 2.574-1.659 3.889-2.441 1.215-.722 2.479-1.363 3.711-2.058 2.659-1.499 5.309-3.015 7.969-4.513.759-.427 1.55-.796 2.31-1.223 1.15-.647 2.277-1.335 3.43-1.977.519-.289 1.157-.413 1.598-.781.572-.479 1.369-1.112 1.393-1.705.025-.618.162-1.129.348-1.678.267-.785-.719-3.204-1.348-3.571-1.475-.864-2.939-1.749-4.366-2.688-1.306-.86-2.534-1.838-3.839-2.698-1.093-.72-2.26-1.326-3.372-2.017-1.163-.723-2.297-1.493-3.449-2.233-1.577-1.013-3.167-2.007-4.737-3.031-1.298-.845-2.591-1.701-3.857-2.593-.734-.517-1.339-1.257-2.126-1.649-1.637-.814-2.693-2.343-4.331-3.193-1.196-.62-2.048-1.868-3.139-2.727-1.052-.828-2.252-1.468-3.314-2.283-.777-.596-1.336-1.545-2.178-1.968-.946-.476-1.568-1.153-2.237-1.897-.471-.523-1.134-.9959-1.799-1.1862-.52-.1489-1.187.1282-1.767.2909-1.013.2835-1.992.7033-3.016.9223-1.419.305-2.874.441-4.3.716-1.835.354-3.658.775-5.487 1.164-2.154.458-4.303.948-6.466 1.359-2.143.406-4.208 1.23-6.434 1.195-.153-.003-.308.051-.459.09-1.058.276-2.106.603-3.176.821-1.996.407-4.009.727-6.006 1.129-1.646.332-3.274.747-4.917 1.094-1.053.223-2.12.378-3.174.593-.316.064-.601.269-.916.339-2.006.44-4.017.854-6.022 1.294-.369.081-.711.306-1.08.36-1.014.146-2.048.179-3.054.365-1.083.199-2.139.535-3.214.783-.704.162-1.422.261-2.128.412-1.004.215-2 .472-3.007.672-.707.141-1.434.183-2.139.332-1.195.253-2.37.601-3.569.827-1.297.245-2.606.491-3.897.713-1.181.204-2.373.734-3.617 1.009-2.692.595-5.338 1.394-8.009 2.083-1.24.319-2.525.487-3.732.894-.729.245-1.406.608-2.2.689-.642.065-1.278.231-1.904.397-.459.122-.885.38-1.347.47-2.573.501-5.178.815-7.686 1.652-1.028.343-2.163.356-3.24.568-1.773.348-3.535.752-5.307 1.104-2.487.494-4.982.949-7.468 1.446-1.508.302-3.001.679-4.511.972-1.596.31-3.21.531-4.806.847-1.247.247-2.475.59-3.719.857-.108.023-.272-.207-.41-.32.013.09.025.181.038.271-5.0749 1.117-10.1806 2.094-15.2162 2.986.9646 1.015 1.9123 1.982 2.8258 2.98 1.6591 1.813 3.4485 3.534 4.8972 5.503 1.138 1.547 2.3324 3.045 3.4688 4.585.8262 1.12 1.4951 2.334 2.5844 3.256.453.383.78.918 1.143 1.4.392.522.725 1.092 1.145 1.59.753.895 1.568 1.738 2.327 2.627.556.652 1.05 1.357 1.597 2.017.73.881 1.499 1.731 2.216 2.622.125.156.075.453.116.761ZM76.06 40.1386c.0482.1613.2254.5513.2745.9566.141 1.1642.2371 2.3341.3382 3.5029.1175 1.3588.2391 2.7176.3273 4.0785.1282 1.9805.2161 3.9636.3454 5.944.062.9492.1933 1.8937.2681 2.8422.0621.7877.0616 1.5806.1359 2.3667.077.8137.2659 1.6193.3065 2.4334.0598 1.1956-.1428 2.4288.0798 3.5861.3654 1.8991.2028 3.8041.3508 5.7009.0986 1.2627-.0901 2.5872.229 3.7836.4338 1.6269-.0991 3.2782.4881 4.9169.3761 1.0495.0611 2.3356.1077 3.5137.0897 2.2651.2229 4.5284.3242 6.793.0415.9275-.1587 1.9241.1207 2.7677.3513 1.0607.365 2.1136.4664 3.179.1283 1.3484.2391 2.6987.3814 4.0452.1864 1.764.4096 3.523.5923 5.287.2044 1.972.3786 3.947.5707 5.921.3491 3.586.6165 7.183 1.1075 10.749.1375.999.3177 2.205 1.2977 2.914.5937.429 1.3108.707 1.8515 1.188.883.785 1.6945.648 2.565.057.0736-.05.1851-.046.2796-.064 2.246-.428 4.4974-.829 6.7368-1.288 2.6939-.553 5.3709-1.187 8.0689-1.72 1.114-.221 2.206-.509 3.385-.53 1.089-.019 2.155-.617 3.255-.853 1.623-.349 3.268-.6 4.902-.902.611-.113 1.212-.304 1.828-.373.841-.093 1.705-.028 2.536-.169.986-.167 1.941-.503 2.92-.723.568-.127 1.17-.115 1.733-.261 1.419-.368 2.828-.777 4.233-1.194 1.844-.548 3.798-.452 5.646-1.073 1.376-.463 2.877-.544 4.301-.881 1.032-.243 2.017-.675 3.044-.941 1.995-.517 4.009-.962 6.007-1.466 1-.252 1.975-.601 2.976-.846 1.913-.468 3.88-.766 5.74-1.385 1.017-.339 2.078-.314 3.105-.734.924-.377 2.093-.26 3.077-.754.185-.093.455-.004.683-.024.521-.047 1.207.077 1.526-.205.673-.596 1.305-.546 2.07-.385.278.058.625-.164.929-.289.276-.113.523-.335.806-.392 1.494-.298 3-.535 4.494-.837 2.664-.539 5.327-1.092 7.981-1.678.659-.146 1.322-.707 1.915-.62 1.231.181 2.28-.32 3.396-.546 1.375-.279 2.722-.696 4.095-.992 2.067-.447 4.142-.855 6.219-1.252 1.49-.285 2.986-.55 4.486-.767.459-.067 1.192.263 1.377.05.869-1.007 2.144-.625 3.181-1.032 1.655-.649 3.499-.818 5.265-1.181 2.204-.454 4.41-.8948 6.613-1.3491 1.513-.3118 3.023-.6369 4.534-.9569 1.548-.3279 3.087-.7078 4.646-.9698 1.359-.2284 2.78-.1772 4.1-.5249 1.075-.2829 2.044-.9679 3.05-1.4936.086-.0449.129-.2309.137-.3548.028-.454.076-.9125.041-1.3637-.161-2.1134-.385-4.2226-.512-6.3377-.138-2.2925-.215-4.5893-.275-6.8853-.04-1.497-.056-2.9986.014-4.4935.129-2.7185-.251-5.4301.039-8.159.172-1.6257-.063-3.2926-.088-4.9414-.034-2.3001-.026-4.6009-.068-6.9008-.052-2.8796-.101-5.7599-.214-8.6375-.124-3.1847-.345-6.3657-.474-9.5503-.09-2.2111-.077-4.4262-.148-6.6383-.043-1.3271-.171-2.6512-.238-3.9777-.036-.7161.02-1.4384-.041-2.1514-.157-1.8258-.355-3.6483-.541-5.4716-.204-1.9986-.436-3.9946-.613-5.9955-.228-2.5885-.414-5.18071-.621-7.81424-.418-.32335-.942-.75597-1.495-1.14882-.387-.27484-.819-.71188-1.22-.70057-1.347.03799-2.689.2413-4.033.38775-.707.07713-1.438.07954-2.114.2712-1.213.34374-2.476.08609-3.709.52507-.978.34829-2.129.21685-3.203.29015-.415.02828-.831.04107-1.247.04803-.748.0125-1.504-.05046-2.243.03486-1.951.22535-3.892.54271-5.844.76458-1.084.12318-2.184.09362-3.271.19501-1.707.15919-3.407.39017-5.114.5512-.716.06763-1.447-.0134-2.164.05656-1.611.1574-3.215.39715-4.827.54776-2.151.20093-4.307.34015-6.46.52252-1.956.16577-3.911.36061-5.867.53006-1.83.15858-3.668.25427-5.493.46181-2.24.25478-4.466.63188-6.706.88936-1.553.17844-3.141.1192-4.671.39661-1.42.2574-2.855.2632-4.278.5058-2.108.3596-4.27.407-6.409.5912-1.49.1285-2.986.2188-4.469.4079-1.578.2011-3.138.536-4.716.7432-1.544.2028-3.105.279-4.649.4818-2.14.2812-4.267.6575-6.407.9387-1.673.2199-3.36.3308-5.035.5391-1.378.1714-2.743.436-4.12.6128-.401.0513-.839-.147-1.23-.0733-.71.1341-1.388.4505-2.099.575-1.316.23-2.65.3583-3.971.5633-1.154.1792-2.293.4703-3.452.5978-2.507.2758-5.025.4434-7.53.729-.952.1085-1.883.2372-2.8509.2755-1.5875.0627-3.1441.6812-4.7348.9345-2.1415.3409-4.3006.5771-6.4563.8227-2.838.3235-5.679.623-8.5209.9098-.8814.089-1.917-.1683-2.6237.2109-1.2822.6881-1.8639 2.127-2.2106 3.4541-.228.8724.1514 1.9094.2904 2.8681.1311.9035.3745 1.7965.4335 2.7028.0408.6262-.1478 1.2672-.216 1.7702.1865.4073.4454.7566.4993 1.1348.1189.8331.1185 1.6823.1956 2.5223.1239 1.3491.2919 2.6945.3944 4.045.0268.3532-.1195.7195-.22 1.2615Zm73.935 164.9144c.184 2.243.357 4.358.536 6.534.461-.097.807-.108 1.095-.241 1.596-.738 3.216-1.436 4.754-2.281 1.533-.842 2.974-1.834 4.63-2.463.908-.345 1.74-.898 2.585-1.394.813-.477 1.564-1.068 2.402-1.491 1.699-.858 3.448-1.616 5.158-2.45 1.997-.974 3.985-1.967 5.958-2.988 1.014-.526 1.896-1.226 3.106-1.457.859-.164 1.584-.953 2.409-1.387.517-.272 1.336-.238 1.62-.629.697-.958 1.86-.84 2.725-1.428 1.108-.754 2.545-1.015 3.812-1.555.843-.359 1.619-1.141 2.457-1.19 1.447-.084 2.28-1.192 3.498-1.615 1.715-.597 3.381-1.342 5.044-2.077 1.118-.494 2.194-1.083 3.29-1.625.822-.405 1.638-.821 2.473-1.196.819-.367 1.67-.664 2.486-1.036.609-.278 1.172-.654 1.778-.938.894-.417 1.825-.757 2.708-1.193.942-.465 1.829-1.044 2.774-1.503 1.251-.608 2.547-1.125 3.802-1.727.649-.312 1.322-.43 1.94-1.02.685-.654 1.967-.643 2.924-1.065 2.008-.886 3.959-1.899 5.96-2.8 1.88-.846 3.799-1.606 5.692-2.423 1.321-.57 2.633-1.161 3.939-1.765 1.09-.503 2.166-1.036 3.245-1.561.387-.189.764-.397 1.147-.594.896-.459 1.783-.938 2.692-1.369 1.153-.548 2.341-1.025 3.484-1.591 1.168-.58 2.298-1.237 3.45-1.85 1.331-.709 2.666-1.411 4.005-2.105.448-.232.904-.455 1.373-.639.429-.169 1.12-.147 1.281-.438.62-1.114 1.843-1.323 2.742-1.993 1.576-1.177 3.407-2.034 4.907-3.29 1.097-.919 2.35-1.671 3.224-2.928.827-1.188 2.136-2.031 3.122-3.126.652-.723 1.288-1.557 1.608-2.456.493-1.381.54-2.869.307-4.342-.065-.412-.092-.831-.126-1.147-2.221 1.162-4.455 2.347-6.706 3.5-.885.454-1.846.77-2.702 1.269-1.348.785-2.606 1.724-3.957 2.502-1.673.964-3.428 1.786-5.099 2.752-2.036 1.176-3.996 2.485-6.038 3.651-2.322 1.326-4.702 2.552-7.052 3.832-1.611.878-3.21 1.778-4.82 2.657-2.076 1.132-4.155 2.26-6.239 3.375-1.739.931-3.478 1.863-5.241 2.748-.674.339-1.681.347-2.072.858-1.044 1.365-2.721 1.586-3.995 2.519-1.195.875-2.672 1.362-4.012 2.046-.948.483-1.865 1.029-2.813 1.511-1.295.658-2.616 1.265-3.909 1.927-.949.486-1.842 1.086-2.81 1.526-1.272.577-2.581 1.038-3.701 1.938-.513.412-1.27.517-1.905.787-.726.309-1.468.599-2.152.986-.918.518-1.753 1.187-2.685 1.673-1.609.84-3.278 1.562-4.897 2.382-1.332.675-2.622 1.432-3.943 2.129-1.659.876-3.334 1.721-4.995 2.594-.812.427-1.563 1.119-2.419 1.281-1.514.285-2.587 1.378-4.018 1.829-1.335.422-2.481 1.411-3.749 2.079-1.433.755-2.899 1.45-4.368 2.136-1.153.538-2.333 1.019-3.498 1.531-1.648.725-3.299 1.442-4.936 2.19-.949.435-1.856.965-2.811 1.384-2.263.992-4.54 1.953-6.824 2.896-.258.107-.6.015-.916.015-.493 1.319-2.103.6-2.734 1.329Zm151.805-77.14c.834.191 1.663.299 2.433.574 1.409.502 2.762 1.161 4.176 1.645 1.546.53 3.134.943 4.707 1.395 1.235.356 2.463.912 3.715.977 1.173.06 2.192.78 3.462.476 1.102-.263 2.309-.06 3.466-.125 2.381-.134 4.608-.895 6.765-1.837 1.247-.545 2.576-1.074 3.594-1.932 1.35-1.138 2.245-2.69 2.648-4.471.461-2.033.714-4.097.688-6.169-.023-1.893-.187-3.794-.441-5.671-.267-1.979-1.145-3.836-2.604-5.115-1.666-1.461-3.54-2.756-5.677-3.561-.851-.321-1.674-.718-2.499-1.101-.783-.363-1.557-.745-2.327-1.134-.651-.33-1.291-.682-2.002-1.059-2.489 1.225-5.215 2.394-7.413 4.451-.416.348-.864.696-1.255 1.1-1.112 1.147-2.261 2.265-3.279 3.492-.86 1.037-1.548 2.215-2.328 3.32-.425.603-.657 1.438-1.032 1.89-1.186 1.428-1.701 3.084-2.272 4.745-.326.948-.522 1.94-.816 2.9-.442 1.442-.917 2.874-1.38 4.309-.07.215-.155.425-.329.901Zm-216.7177 5.863-.294.198c.0976.531.213 1.059.2881 1.592.091.648.1565 1.299.2175 1.95.0801.855.0105 1.734.4293 2.531.4576.871.8633 1.775 1.3887 2.603.6935 1.094 1.5026 2.114 2.2223 3.191.6048.906 1.103 1.885 1.741 2.765.5463.753 1.2436 1.396 1.8356 2.12.3297.402.5781.871.8678 1.307.7057 1.062 1.3535 2.169 2.1372 3.17.9141 1.169 1.9789 2.218 2.9228 3.365 1.4644 1.779 2.8614 3.613 4.3264 5.39.747.905 1.616 1.71 2.366 2.613.631.761 1.175 1.595 1.748 2.403.467.659.917 1.33 1.381 1.99.053.076.149.175.224.174.97-.021 1.232.934 1.798 1.407 1.132.949 2.006 2.201 3.018 3.3.477.519 1.066.937 1.533 1.464 1.032 1.162 1.991 2.39 3.032 3.544 1.287 1.427 2.646 2.79 3.94 4.211 1.79 1.964 3.552 3.953 5.32 5.938.883.992 1.741 2.007 2.629 2.994 1.328 1.477 2.68 2.932 4.007 4.409.578.644 1.097 1.341 1.684 1.976.715.772 1.496 1.483 2.209 2.258.854.929 1.639 1.921 2.503 2.841.908.967 1.871 1.883 2.815 2.816.923.911 1.844 1.826 2.79 2.713.142.133.419.162.633.161.075 0 .21-.235.213-.366.045-1.654.093-3.309.07-4.963-.003-.205-.383-.476-.644-.595-1.089-.493-2.463-.689-3.218-1.481-.607-.635-1.111-1.545-1.693-2.31-.689-.905-1.314-1.869-2.081-2.701-1.319-1.431-2.745-2.764-4.092-4.171-.741-.775-1.405-1.623-2.116-2.428-.865-.98-1.742-1.95-2.617-2.92-.858-.951-1.74-1.882-2.577-2.85-.836-.965-1.613-1.98-2.447-2.947-.62-.719-1.319-1.371-1.925-2.099-.366-.44-1.123-.658-.929-1.457-1.221-.043-1.117-1.317-1.767-1.898-.407-.364-.714-.837-1.086-1.242-.577-.628-1.209-1.208-1.748-1.865-.802-.98-1.516-2.032-2.319-3.011-.693-.845-1.496-1.6-2.18-2.451-.889-1.105-1.674-2.283-2.656-3.328-.948-1.01-1.696-2.205-2.557-3.299-1.404-1.783-2.799-3.574-4.251-5.318-1.325-1.591-2.731-3.115-4.075-4.691-.2484-.292-.3085-.746-.5618-1.031-.6389-.721-1.3361-1.39-2.0149-2.074-.2466-.249-.6365-.44-.7367-.734-.2799-.82-.7707-1.396-1.3685-2.039-1.2795-1.376-2.2835-3.008-3.3931-4.54-.4903-.677-.9359-1.387-1.4488-2.046-1.3601-1.747-2.7318-3.486-4.1304-5.203-.3992-.49-.906-.893-1.3635-1.336Zm214.8887-7.493c.065-1.143.019-2.148.198-3.112.371-1.992.823-3.971 1.325-5.935.163-.637.608-1.198.885-1.812.505-1.119.885-2.305 1.497-3.359.506-.87 1.289-1.577 1.919-2.38.986-1.253 1.947-2.525 2.957-3.84-.522-.344-1.191-.976-1.986-1.264-1.44-.522-2.943-.893-4.442-1.229-2.375-.533-4.786-.913-7.144-1.507-.929-.234-1.579-.258-2.043.639-.088.168-.06.408-.17.551-.842 1.099-1.552 2.248-1.831 3.639-.254 1.27-.439 2.537-.526 3.834-.176 2.584.097 5.081 1.121 7.471.199.465.487.896.769 1.321.769 1.159 1.42 2.436 2.371 3.427 1.313 1.368 2.93 2.418 4.554 3.419.211.13.505.128.546.137Zm-2.383-27.6112c.675.1921 1.381.6404 1.957.5119 1.942-.4327 3.608.545 5.259 1.0713 2.048.654 4.184 1.385 5.931 2.772.543.431.904.455 1.397-.047.389-.396.897-.674 1.348-1.011 1.359-1.014 2.715-2.0301 4.152-3.1048-.874-.3548-1.807-.7378-2.744-1.1136-2.178-.8738-4.415-1.5289-6.774-1.6392-1.739-.0812-3.444-.0022-5.192.3127-2.052.3697-3.878.9714-5.334 2.2477ZM76.8825 99.9056c-.1233-.0081-.2466-.0161-.3699-.0242.048.8566.096 1.7126.144 2.5686.0753.004.1506.009.2259.014v-2.5584Z" fill="#000"/>
+ </g>
+ <defs>
+ <linearGradient id="b" x1="68" y1="3" x2="278" y2="3" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#9059FF"/>
+ <stop offset=".520833" stop-color="#FF4AA2"/>
+ <stop offset="1" stop-color="#FFBD4F"/>
+ </linearGradient>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h341v215H0z"/>
+ </clipPath>
+ </defs>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/firefox.svg b/browser/components/newtab/data/content/assets/firefox.svg
new file mode 100644
index 0000000000..0587828f60
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/firefox.svg
@@ -0,0 +1,168 @@
+<?xml version="1.0" encoding="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/. -->
+<!-- Generator: Adobe Illustrator 23.0.4, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1856 1847.5" style="enable-background:new 0 0 1856 1847.5;" xml:space="preserve">
+<style type="text/css">
+ .st0{display:none;}
+ .st1{fill:url(#SVGID_1_);}
+ .st2{opacity:0.67;}
+ .st3{fill:url(#SVGID_2_);}
+ .st4{fill:url(#SVGID_3_);}
+ .st5{fill:url(#SVGID_4_);}
+ .st6{fill:url(#SVGID_5_);}
+ .st7{fill:url(#SVGID_6_);}
+ .st8{fill:url(#SVGID_7_);}
+ .st9{fill:url(#SVGID_8_);}
+ .st10{opacity:0.53;fill:url(#SVGID_9_);enable-background:new ;}
+ .st11{opacity:0.53;fill:url(#SVGID_10_);enable-background:new ;}
+ .st12{fill:url(#SVGID_11_);}
+ .st13{fill:url(#SVGID_12_);}
+ .st14{fill:url(#SVGID_13_);}
+ .st15{fill:url(#SVGID_14_);}
+ .st16{fill:none;}
+</style>
+<g id="LiveType" class="st0">
+</g>
+<g id="Outlined">
+ <g>
+ <g>
+
+ <radialGradient id="SVGID_1_" cx="321.9653" cy="2631.8848" r="1876.7874" fx="389.093" fy="2598.7063" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)" gradientUnits="userSpaceOnUse">
+ <stop offset="0" style="stop-color:#FFF44F"/>
+ <stop offset="0.2949" style="stop-color:#FF980E"/>
+ <stop offset="0.4315" style="stop-color:#FF5D36"/>
+ <stop offset="0.5302" style="stop-color:#FF3750"/>
+ <stop offset="0.7493" style="stop-color:#F5156C"/>
+ <stop offset="0.7648" style="stop-color:#F1136E"/>
+ <stop offset="0.8801" style="stop-color:#DA057A"/>
+ <stop offset="0.9528" style="stop-color:#D2007F"/>
+ </radialGradient>
+ <path class="st1" d="M1588.9,424.3c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100 c100.4-58.1,245.7-91.1,373-89.4c327.3,4.2,678.8,226.5,731,627.3c59.9,460.1-261.3,844-713.1,845.2 C455.4,1585,153,1145.8,232,751.4c3.9-19.7,2-38.9,8.6-57.5c3.8-69.4,30-178.1,86.7-289.1c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688c457.3,0,828.1-370.7,828.1-828.1 C1755.5,735.4,1693.5,562.9,1588.9,424.3z M278.3,496.2L278.3,496.2L278.3,496.2z"/>
+ <g class="st2">
+
+ <radialGradient id="SVGID_2_" cx="-1019.8155" cy="2554.2456" r="1110.733" fx="-980.0875" fy="2534.6096" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)" gradientUnits="userSpaceOnUse">
+ <stop offset="0" style="stop-color:#B5007F"/>
+ <stop offset="1" style="stop-color:#F5156C;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st3" d="M1588.9,424.3c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100 c100.4-58.1,245.7-91.1,373-89.4c327.3,4.2,678.8,226.5,731,627.3c59.9,460.1-261.3,844-713.1,845.2 C455.4,1585,153,1145.8,232,751.4c3.9-19.7,2-38.9,8.6-57.5c3.8-69.4,30-178.1,86.7-289.1c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688 c457.3,0,828.1-370.7,828.1-828.1C1755.5,735.4,1693.5,562.9,1588.9,424.3z M278.3,496.2L278.3,496.2L278.3,496.2z"/>
+ </g>
+
+ <radialGradient id="SVGID_3_" cx="482.4009" cy="2738.6748" r="2203.8347" fx="561.2262" fy="2699.7146" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)" gradientUnits="userSpaceOnUse">
+ <stop offset="0" style="stop-color:#FFDD00;stop-opacity:0.6"/>
+ <stop offset="8.366719e-02" style="stop-color:#FFD801;stop-opacity:0.5244"/>
+ <stop offset="0.1822" style="stop-color:#FECA05;stop-opacity:0.4353"/>
+ <stop offset="0.2884" style="stop-color:#FEB20C;stop-opacity:0.3394"/>
+ <stop offset="0.3998" style="stop-color:#FD9115;stop-opacity:0.2388"/>
+ <stop offset="0.5154" style="stop-color:#FB6621;stop-opacity:0.1343"/>
+ <stop offset="0.6329" style="stop-color:#F9332F;stop-opacity:2.816400e-02"/>
+ <stop offset="0.664" style="stop-color:#F92433;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st4" d="M1588.9,424.3c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100 c100.4-58.1,245.7-91.1,373-89.4c327.3,4.2,678.8,226.5,731,627.3c59.9,460.1-261.3,844-713.1,845.2 C455.4,1585,153,1145.8,232,751.4c3.9-19.7,2-38.9,8.6-57.5c3.8-69.4,30-178.1,86.7-289.1c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688c457.3,0,828.1-370.7,828.1-828.1 C1755.5,735.4,1693.5,562.9,1588.9,424.3z M278.3,496.2L278.3,496.2L278.3,496.2z"/>
+ </g>
+ <g>
+
+ <radialGradient id="SVGID_4_" cx="975.7665" cy="1493.5381" r="2843.1211" gradientTransform="matrix(1 0 0 -1 0 2512)" gradientUnits="userSpaceOnUse">
+ <stop offset="0.1528" style="stop-color:#960E18"/>
+ <stop offset="0.2061" style="stop-color:#CC2335;stop-opacity:0.5541"/>
+ <stop offset="0.2495" style="stop-color:#F13148;stop-opacity:0.1914"/>
+ <stop offset="0.2724" style="stop-color:#FF3750;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st5" d="M1588.9,424.3c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100 c100.4-58.1,245.7-91.1,373-89.4c327.3,4.2,678.8,226.5,731,627.3c59.9,460.1-261.3,844-713.1,845.2 C455.4,1585,153,1145.8,232,751.4c3.9-19.7,2-38.9,8.6-57.5c3.8-69.4,30-178.1,86.7-289.1c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688c457.3,0,828.1-370.7,828.1-828.1 C1755.5,735.4,1693.5,562.9,1588.9,424.3z M278.3,496.2L278.3,496.2L278.3,496.2z"/>
+
+ <radialGradient id="SVGID_5_" cx="760.6194" cy="1529.2881" r="2843.1211" gradientTransform="matrix(1 0 0 -1 0 2512)" gradientUnits="userSpaceOnUse">
+ <stop offset="0.1129" style="stop-color:#960E18"/>
+ <stop offset="0.1893" style="stop-color:#CC2335;stop-opacity:0.5541"/>
+ <stop offset="0.2515" style="stop-color:#F13148;stop-opacity:0.1914"/>
+ <stop offset="0.2843" style="stop-color:#FF3750;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st6" d="M1588.9,424.3c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100 c100.4-58.1,245.7-91.1,373-89.4c327.3,4.2,678.8,226.5,731,627.3c59.9,460.1-261.3,844-713.1,845.2 C455.4,1585,153,1145.8,232,751.4c3.9-19.7,2-38.9,8.6-57.5c3.8-69.4,30-178.1,86.7-289.1c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688c457.3,0,828.1-370.7,828.1-828.1 C1755.5,735.4,1693.5,562.9,1588.9,424.3z M278.3,496.2L278.3,496.2L278.3,496.2z"/>
+ </g>
+
+ <linearGradient id="SVGID_6_" gradientUnits="userSpaceOnUse" x1="-209.3687" y1="2784.0808" x2="277.0962" y2="1941.499" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)">
+ <stop offset="0" style="stop-color:#FFBC04"/>
+ <stop offset="0.2597" style="stop-color:#FFA202;stop-opacity:0.4886"/>
+ <stop offset="0.5078" style="stop-color:#FF8E00;stop-opacity:0"/>
+ </linearGradient>
+ <path class="st7" d="M1665.6,738.5c6.6,50.8,8.6,100.8,6.2,149.5c27.4-4.1,54.9-7.7,82.4-10.9c-9.2-169.5-69.2-325.4-165.3-452.8 c-149.5-196.4-382.5-318.8-627.6-323.6c-192-3.8-324.7,53.7-399.7,100c100.4-58.1,245.7-91.1,373-89.4 C1261.9,115.4,1613.4,337.7,1665.6,738.5z"/>
+ <g>
+
+ <radialGradient id="SVGID_7_" cx="244.0767" cy="2202.7847" r="1837.1556" fx="309.7869" fy="2170.3069" gradientTransform="matrix(0.9589 0 0 -0.9589 1306.9894 2461.7681)" gradientUnits="userSpaceOnUse">
+ <stop offset="0" style="stop-color:#FF980E"/>
+ <stop offset="0.295" style="stop-color:#FF7139"/>
+ <stop offset="0.4846" style="stop-color:#FF5B51"/>
+ <stop offset="0.626" style="stop-color:#FF4F5E"/>
+ <stop offset="0.7365" style="stop-color:#FF4055"/>
+ <stop offset="0.8428" style="stop-color:#FF3750"/>
+ </radialGradient>
+ <path class="st8" d="M1685.7,715.6c-46.5-418.8-421-607.1-751.1-604.4c-127.2,1-272.5,31.3-373,89.4 c-46.9,28.9-71.3,53.4-73.6,55.8c2.7-2.2,10.6-8.7,23.8-17.8c0.4-0.3,0.9-0.6,1.3-0.9c0.4-0.3,0.8-0.5,1.2-0.8 c47.9-33,101.9-57,159-73.7c87.3-25.5,181.7-34.1,272.6-31.8c373.4,21.5,636.9,330.7,646.1,659.8 c7.6,272.4-215.9,489.6-473.5,502.2c-187.3,9.1-363.8-81.3-450.1-262.2c-19.2-40.3-33.3-81.2-40.6-130.6 C587,625.2,772.3,390.4,942.3,332.3c-91.7-79.9-321.4-74.5-492.4,51c-123.1,90.4-203,227.9-229.5,391.9 c-20.2,125.1-1.2,255.2,48.4,371.3c50.5,118.4,132.6,222.7,235.8,299.6c112.1,83.4,247.1,132,386.2,142.6 c20.5,1.6,41.1,2.3,61.7,2.3C1499.6,1591,1736.9,1176.7,1685.7,715.6z"/>
+
+ <radialGradient id="SVGID_8_" cx="244.0767" cy="2202.7847" r="1837.1556" fx="309.7869" fy="2170.3069" gradientTransform="matrix(0.9589 0 0 -0.9589 1306.9894 2461.7681)" gradientUnits="userSpaceOnUse">
+ <stop offset="8.407450e-02" style="stop-color:#FFDE08"/>
+ <stop offset="0.2081" style="stop-color:#FFD609;stop-opacity:0.832"/>
+ <stop offset="0.4033" style="stop-color:#FFBF0B;stop-opacity:0.5677"/>
+ <stop offset="0.6437" style="stop-color:#FF9B0F;stop-opacity:0.242"/>
+ <stop offset="0.8224" style="stop-color:#FF7B12;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st9" d="M1685.7,715.6c-46.5-418.8-421-607.1-751.1-604.4c-127.2,1-272.5,31.3-373,89.4 c-46.9,28.9-71.3,53.4-73.6,55.8c2.7-2.2,10.6-8.7,23.8-17.8c0.4-0.3,0.9-0.6,1.3-0.9c0.4-0.3,0.8-0.5,1.2-0.8 c47.9-33,101.9-57,159-73.7c87.3-25.5,181.7-34.1,272.6-31.8c373.4,21.5,636.9,330.7,646.1,659.8 c7.6,272.4-215.9,489.6-473.5,502.2c-187.3,9.1-363.8-81.3-450.1-262.2c-19.2-40.3-33.3-81.2-40.6-130.6 C587,625.2,772.3,390.4,942.3,332.3c-91.7-79.9-321.4-74.5-492.4,51c-123.1,90.4-203,227.9-229.5,391.9 c-20.2,125.1-1.2,255.2,48.4,371.3c50.5,118.4,132.6,222.7,235.8,299.6c112.1,83.4,247.1,132,386.2,142.6 c20.5,1.6,41.1,2.3,61.7,2.3C1499.6,1591,1736.9,1176.7,1685.7,715.6z"/>
+ </g>
+ <g>
+
+ <radialGradient id="SVGID_9_" cx="538.6154" cy="664.721" r="863.9618" gradientTransform="matrix(0.2472 0.969 1.0112 -0.258 328.7156 547.2202)" gradientUnits="userSpaceOnUse">
+ <stop offset="0.3634" style="stop-color:#FF3750"/>
+ <stop offset="0.4111" style="stop-color:#FF444B;stop-opacity:0.7895"/>
+ <stop offset="0.5902" style="stop-color:#FF7139;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st10" d="M1685.7,715.6c-46.5-418.8-421-607.1-751.1-604.4c-127.2,1-272.5,31.3-373,89.4 c-46.9,28.9-71.3,53.4-73.6,55.8c2.7-2.2,10.6-8.7,23.8-17.8c0.4-0.3,0.9-0.6,1.3-0.9c0.4-0.3,0.8-0.5,1.2-0.8 c47.9-33,101.9-57,159-73.7c87.3-25.5,181.7-34.1,272.6-31.8c373.4,21.5,636.9,330.7,646.1,659.8 c7.6,272.4-215.9,489.6-473.5,502.2c-187.3,9.1-363.8-81.3-450.1-262.2c-19.2-40.3-33.3-81.2-40.6-130.6 C587,625.2,772.3,390.4,942.3,332.3c-91.7-79.9-321.4-74.5-492.4,51c-123.1,90.4-203,227.9-229.5,391.9 c-20.2,125.1-1.2,255.2,48.4,371.3c50.5,118.4,132.6,222.7,235.8,299.6c112.1,83.4,247.1,132,386.2,142.6 c20.5,1.6,41.1,2.3,61.7,2.3C1499.6,1591,1736.9,1176.7,1685.7,715.6z"/>
+
+ <radialGradient id="SVGID_10_" cx="389.6962" cy="589.2068" r="862.9537" gradientTransform="matrix(0.2472 0.969 0.9698 -0.2474 318.7961 738.6102)" gradientUnits="userSpaceOnUse">
+ <stop offset="0.2159" style="stop-color:#FF3750;stop-opacity:0.8"/>
+ <stop offset="0.2702" style="stop-color:#FF444B;stop-opacity:0.6316"/>
+ <stop offset="0.4739" style="stop-color:#FF7139;stop-opacity:0"/>
+ </radialGradient>
+ <path class="st11" d="M1685.7,715.6c-46.5-418.8-421-607.1-751.1-604.4c-127.2,1-272.5,31.3-373,89.4 c-46.9,28.9-71.3,53.4-73.6,55.8c2.7-2.2,10.6-8.7,23.8-17.8c0.4-0.3,0.9-0.6,1.3-0.9c0.4-0.3,0.8-0.5,1.2-0.8 c47.9-33,101.9-57,159-73.7c87.3-25.5,181.7-34.1,272.6-31.8c373.4,21.5,636.9,330.7,646.1,659.8 c7.6,272.4-215.9,489.6-473.5,502.2c-187.3,9.1-363.8-81.3-450.1-262.2c-19.2-40.3-33.3-81.2-40.6-130.6 C587,625.2,772.3,390.4,942.3,332.3c-91.7-79.9-321.4-74.5-492.4,51c-123.1,90.4-203,227.9-229.5,391.9 c-20.2,125.1-1.2,255.2,48.4,371.3c50.5,118.4,132.6,222.7,235.8,299.6c112.1,83.4,247.1,132,386.2,142.6 c20.5,1.6,41.1,2.3,61.7,2.3C1499.6,1591,1736.9,1176.7,1685.7,715.6z"/>
+ </g>
+ <g>
+
+ <radialGradient id="SVGID_11_" cx="610.7241" cy="2410.3098" r="3105.1294" gradientTransform="matrix(0.9589 0 0 -0.9589 1306.9894 2461.7681)" gradientUnits="userSpaceOnUse">
+ <stop offset="5.356570e-02" style="stop-color:#FFF44F"/>
+ <stop offset="0.4573" style="stop-color:#FF980E"/>
+ <stop offset="0.5211" style="stop-color:#FF8424"/>
+ <stop offset="0.5871" style="stop-color:#FF7634"/>
+ <stop offset="0.6393" style="stop-color:#FF7139"/>
+ </radialGradient>
+ <path class="st12" d="M1118.5,1293.4c353.6-21.5,504.9-313.4,514.3-520.7c14.8-323.7-177.7-672.7-686.9-641.2 c-90.8-2.3-185.3,6.3-272.6,31.8c-76.5,23.3-129.6,53.8-159,73.7c-0.4,0.3-0.8,0.5-1.2,0.8c-0.5,0.3-0.9,0.6-1.3,0.9 c-7.9,5.5-15.7,11.3-23.2,17.4c14.2-9.7,189.8-113.1,433.8-81.2C1214.7,213.1,1482,440,1482,739.4 c0,230.4-178.4,406.2-387.4,393.7C784.2,1114.4,706,796.8,867.4,659.6c-43.5-9.4-125.4,9-182.3,93.9 c-51.1,76.3-48.2,194.1-16.7,277.6C754.7,1212.1,931.3,1304.8,1118.5,1293.4z"/>
+ </g>
+ <g>
+
+ <linearGradient id="SVGID_12_" gradientUnits="userSpaceOnUse" x1="1321.7657" y1="2265.9978" x2="477.6807" y2="803.9998" gradientTransform="matrix(1 0 0 -1 0 2512)">
+ <stop offset="0" style="stop-color:#FFF44F;stop-opacity:0.8"/>
+ <stop offset="0.75" style="stop-color:#FFF44F;stop-opacity:0"/>
+ </linearGradient>
+ <path class="st13" d="M1588.9,424.3c-22.2-29.1-46.4-56.4-72-82.1c-20.5-21.7-42.6-41.8-65.7-60.3c13.3,11.6,26.1,23.9,38.2,36.9 c44.8,48.3,80.2,105.4,100.9,168c43.2,130.5,40.4,293.9-42.1,422.2c-98.3,152.9-258.2,228.4-431.2,224.7c-7.5,0-15-0.1-22.6-0.6 C784.2,1114.4,706,796.8,867.5,659.6c-43.5-9.4-125.4,9-182.4,93.9c-51.1,76.3-48.2,194.1-16.7,277.6 c-19.2-40.2-33.3-81.2-40.6-130.6C587,625.2,772.3,390.4,942.3,332.3c-91.7-79.9-321.4-74.5-492.4,51 c-99.6,73.1-170.9,177.1-208.5,301.1c5.5-69.5,31.9-173.4,86-279.5c-57.2,29.5-130.1,123-166.1,209.6 c-51.9,124.8-70.2,274.1-53.7,416.1c1.2,10.7,2.4,21.3,3.8,31.9c66.6,390.6,406.6,688,816.2,688c457.3,0,828.1-370.7,828.1-828.1 C1755.5,735.4,1693.5,562.9,1588.9,424.3z"/>
+ </g>
+
+ <linearGradient id="SVGID_13_" gradientUnits="userSpaceOnUse" x1="-205.4111" y1="1906.6858" x2="-205.4111" y2="2933.979" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)">
+ <stop offset="0" style="stop-color:#3A8EE6"/>
+ <stop offset="0.2359" style="stop-color:#5C79F0"/>
+ <stop offset="0.6293" style="stop-color:#9059FF"/>
+ <stop offset="1" style="stop-color:#C139E6"/>
+ </linearGradient>
+ <path class="st14" d="M1590.4,486.7c-20.7-62.5-56.1-119.6-100.9-168c-52.8-56.9-118.5-100.2-188-133.9 c-59.2-28.7-121-51.3-184.8-65.4c-114.4-25.2-234.4-24.7-342.5-2C656.7,142.2,553.4,192.9,488,256.3c49-29.7,117.3-53.8,166-66.1 c226-57,474.8,4.7,644.5,167.1c34.1,32.6,64.7,69.1,89.5,109.4c101.2,164.2,91.6,370.5,12.7,492.2 c-58.6,90.4-184.1,175.2-301.3,174.3c179.7,9.4,347.2-66.2,448.9-224.3C1630.8,780.6,1633.6,617.2,1590.4,486.7z"/>
+
+ <linearGradient id="SVGID_14_" gradientUnits="userSpaceOnUse" x1="-583.4494" y1="2938.6887" x2="250.1202" y2="2105.1191" gradientTransform="matrix(1 0 0 -1 1258.4413 3044.8896)">
+ <stop offset="0.8054" style="stop-color:#9059FF;stop-opacity:0"/>
+ <stop offset="1" style="stop-color:#6E008B;stop-opacity:0.5"/>
+ </linearGradient>
+ <path class="st15" d="M1590.4,486.7c-20.7-62.5-56.1-119.6-100.9-168c-52.8-56.9-118.5-100.2-188-133.9 c-59.2-28.7-121-51.3-184.8-65.4c-114.4-25.2-234.4-24.7-342.5-2C656.7,142.2,553.4,192.9,488,256.3c49-29.7,117.3-53.8,166-66.1 c226-57,474.8,4.7,644.5,167.1c34.1,32.6,64.7,69.1,89.5,109.4c101.2,164.2,91.6,370.5,12.7,492.2 c-58.6,90.4-184.1,175.2-301.3,174.3c179.7,9.4,347.2-66.2,448.9-224.3C1630.8,780.6,1633.6,617.2,1590.4,486.7z"/>
+ </g>
+ <rect x="745.5" y="50.5" class="st16" width="50" height="50"/>
+</g>
+<g id="Layer_3">
+</g>
+<g id="Layer_4">
+</g>
+<g id="Layer_5">
+</g>
+</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-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-20.svg b/browser/components/newtab/data/content/assets/glyph-modal-delete-20.svg
new file mode 100644
index 0000000000..592f9569a1
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-modal-delete-20.svg
@@ -0,0 +1,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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20" fill="context-fill" fill-opacity="context-fill-opacity">
+ <path d="M17.2 4 14 4l0-1.5C14 1.1 12.9 0 11.5 0l-3 0C7.1 0 6 1.1 6 2.5L6 4 2.8 4c-.5 0-.8.3-.8.8s.3.8.8.8l.2 0 0 12C3 18.9 4.1 20 5.5 20l9 0c1.4 0 2.5-1.1 2.5-2.5l0-12 .3 0c.4 0 .8-.3.8-.8s-.4-.7-.9-.7zM7.5 2.3l.8-.8 3.4 0 .8.8 0 1.7-5 0 0-1.7zm8 15.4-.8.8-9.4 0-.8-.8 0-12.2 11 0 0 12.2z"/>
+ <path d="M7.8 16c.4 0 .8-.3.8-.8l0-6.5c0-.4-.3-.8-.8-.8s-.8.4-.8.9l0 6.5c0 .4.3.7.8.7z"/>
+ <path d="M12.2 16c.4 0 .8-.3.8-.8l0-6.5c0-.4-.3-.8-.8-.8s-.8.3-.8.8l0 6.5c.1.5.4.8.8.8z"/>
+</svg>
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-pin-16.svg b/browser/components/newtab/data/content/assets/glyph-pin-16.svg
new file mode 100644
index 0000000000..c951bc1c9d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pin-16.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 xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="context-fill" fill-opacity="context-fill-opacity">
+ <path d="m15.817 13.933-4.092-4.092 2.057-2.057a1.622 1.622 0 0 0 .352-1.771 1.62 1.62 0 0 0-1.501-1.003l-1.851 0-3.175-3.177c-.021-.021-.049-.03-.072-.048l.719-.719A.625.625 0 0 0 7.37.182L1.183 6.37a.625.625 0 0 0 .884.884l.719-.719c.017.023.026.05.047.072L6.01 9.783l0 1.85c0 .66.394 1.249 1.003 1.501a1.623 1.623 0 0 0 1.771-.352l2.057-2.057 4.092 4.092a.625.625 0 0 0 .884-.884zM6.944 2.94l3.079 3.078.623.242 1.987 0c.226 0 .317.162.347.231a.363.363 0 0 1-.082.408L7.9 11.897a.362.362 0 0 1-.408.082.363.363 0 0 1-.231-.347l0-1.992-.25-.625L3.94 5.944l0-.567 2.51-2.509.494.072z"/>
+</svg>
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-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/heart.webp b/browser/components/newtab/data/content/assets/heart.webp
new file mode 100644
index 0000000000..fb9f7fdca5
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/heart.webp
Binary files differ
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/long-zap.svg b/browser/components/newtab/data/content/assets/long-zap.svg
new file mode 100644
index 0000000000..757a5483f9
--- /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 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/mobile-download-qr-existing-user-cn.svg b/browser/components/newtab/data/content/assets/mobile-download-qr-existing-user-cn.svg
new file mode 100644
index 0000000000..99d174a259
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mobile-download-qr-existing-user-cn.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 width="150" height="150" viewBox="0 0 150 150" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M136 1H14C6.82 1 1 6.82 1 14v122c0 7.18 5.82 13 13 13h122c7.18 0 13-5.82 13-13V14c0-7.18-5.82-13-13-13Z" fill="#fff" stroke="#DCDCDC" stroke-width="2"/><path d="M16 16h3.576v3.576H16V16Zm3.576 0h3.575v3.576h-3.575V16Zm3.575 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.575v3.576h-3.575V16Zm17.878 0h3.576v3.576h-3.576V16Zm17.88 0h3.575v3.576h-3.576V16Zm10.726 0h3.576v3.576H83.94V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576H91.09V16Zm3.576 0h3.575v3.576h-3.575V16Zm7.151 0h3.576v3.576h-3.576V16Zm7.152 0h3.575v3.576h-3.575V16Zm3.575 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.576v3.576h-3.576V16Zm3.576 0h3.575v3.576h-3.575V16Zm3.575 0h3.576v3.576h-3.576V16Zm3.576 0H134v3.576h-3.576V16ZM16 19.576h3.576v3.575H16v-3.575Zm21.455 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm10.727 0h3.576v3.575H83.94v-3.575Zm25.031 0h3.575v3.575h-3.575v-3.575Zm21.454 0H134v3.575h-3.576v-3.575ZM16 23.15h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576H83.94v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576H91.09v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0H134v3.576h-3.576v-3.576ZM16 26.727h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm17.878 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576H91.09v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0H134v3.576h-3.576v-3.576ZM16 30.303h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576H91.09v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0H134v3.576h-3.576v-3.576ZM16 33.879h3.576v3.576H16v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm17.88 0h3.575v3.576h-3.576v-3.576Zm3.575 0h3.576v3.576H91.09v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm21.454 0H134v3.576h-3.576v-3.576ZM16 37.455h3.576v3.575H16v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0H134v3.575h-3.576v-3.575ZM51.758 41.03h3.575v3.576h-3.575V41.03Zm3.575 0h3.576v3.576h-3.576V41.03Zm10.728 0h3.575v3.576h-3.575V41.03Zm3.575 0h3.576v3.576h-3.576V41.03Zm14.303 0h3.576v3.576H83.94V41.03Zm14.303 0h3.576v3.576h-3.576V41.03Zm3.576 0h3.576v3.576h-3.576V41.03Zm-78.666 3.576h3.575v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576H41.03v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm28.606 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576H83.94v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576ZM16 48.182h3.576v3.576H16v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm17.879 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm14.303 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0H134v3.576h-3.576v-3.576ZM16 51.758h3.576v3.575H16v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575H41.03v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm10.727 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575H83.94v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575H91.09v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm10.727 0H134v3.575h-3.576v-3.575ZM16 55.333h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm14.303 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576ZM16 58.91h3.576v3.576H16v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576H91.09v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576ZM16 62.485h3.576v3.576H16v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm17.879 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576H91.09v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm21.454 0H134v3.576h-3.576v-3.576ZM16 66.06h3.576v3.575H16v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm10.728 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm10.727 0h3.576v3.575h-3.576v-3.575Zm10.727 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm10.727 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0H134v3.575h-3.576v-3.575ZM16 69.636h3.576v3.576H16v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576H41.03v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576H83.94v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm17.878 0h3.576v3.576h-3.576v-3.576Zm3.576 0H134v3.576h-3.576v-3.576ZM19.576 73.212h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576ZM16 76.788h3.576v3.576H16v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576H41.03v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576H91.09v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm10.728 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0H134v3.576h-3.576v-3.576ZM16 80.364h3.576v3.575H16v-3.575Zm17.879 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm14.303 0h3.575v3.575h-3.575v-3.575Zm14.303 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.576v3.575h-3.576v-3.575Zm21.454 0h3.576v3.575h-3.576v-3.575Zm17.879 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0H134v3.575h-3.576v-3.575ZM19.576 83.939h3.575v3.576h-3.575V83.94Zm3.575 0h3.576v3.576h-3.576V83.94Zm3.576 0h3.576v3.576h-3.576V83.94Zm21.455 0h3.576v3.576h-3.576V83.94Zm14.303 0h3.576v3.576h-3.576V83.94Zm3.576 0h3.575v3.576h-3.575V83.94Zm7.151 0h3.576v3.576h-3.576V83.94Zm7.152 0h3.575v3.576h-3.575V83.94Zm17.878 0h3.576v3.576h-3.576V83.94Zm10.728 0h3.575v3.576h-3.575V83.94Zm3.575 0h3.576v3.576h-3.576V83.94Zm3.576 0h3.576v3.576h-3.576V83.94Zm3.576 0h3.576v3.576h-3.576V83.94Zm7.151 0h3.576v3.576h-3.576V83.94ZM16 87.515h3.576v3.576H16v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576H41.03v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm-92.97 3.576h3.576v3.576h-3.575V91.09Zm7.152 0h3.576v3.576h-3.576V91.09Zm3.576 0h3.576v3.576h-3.576V91.09Zm21.455 0h3.575v3.576h-3.575V91.09Zm7.151 0h3.576v3.576h-3.576V91.09Zm3.576 0h3.576v3.576h-3.576V91.09Zm3.576 0h3.575v3.576h-3.575V91.09Zm3.575 0h3.576v3.576h-3.576V91.09Zm7.152 0h3.576v3.576h-3.576V91.09Zm35.757 0h3.576v3.576h-3.576V91.09Zm7.152 0h3.576v3.576h-3.576V91.09Zm3.576 0h3.575v3.576h-3.575V91.09Zm7.151 0H134v3.576h-3.576V91.09ZM16 94.667h3.576v3.575H16v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575H41.03v-3.575Zm7.152 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm17.879 0h3.576v3.575h-3.576v-3.575Zm7.151 0h3.576v3.575H83.94v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm17.879 0H134v3.575h-3.576v-3.575ZM26.727 98.242h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm17.88 0h3.575v3.576h-3.576v-3.576Zm28.605 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0H134v3.576h-3.576v-3.576ZM16 101.818h3.576v3.576H16v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0H134v3.576h-3.576v-3.576Zm-85.818 3.576h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm17.88 0h3.575v3.576h-3.576v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576H83.94v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576H91.09v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm7.151 0H134v3.576h-3.576v-3.576ZM16 108.97h3.576v3.575H16v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm10.727 0h3.576v3.575h-3.576v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575H83.94v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm14.303 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm14.303 0H134v3.575h-3.576v-3.575ZM16 112.545h3.576v3.576H16v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576H91.09v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm14.303 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0H134v3.576h-3.576v-3.576ZM16 116.121h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm14.303 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576H83.94v-3.576Zm7.152 0h3.576v3.576H91.09v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576ZM16 119.697h3.576v3.576H16v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm17.879 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576H91.09v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm3.575 0h3.576v3.576h-3.576v-3.576ZM16 123.273h3.576v3.575H16v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm7.152 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm10.728 0h3.575v3.575h-3.575v-3.575Zm3.575 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm21.454 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm14.303 0h3.576v3.575h-3.576v-3.575Zm3.576 0h3.576v3.575h-3.576v-3.575Zm7.151 0h3.576v3.575h-3.576v-3.575Zm3.576 0H134v3.575h-3.576v-3.575ZM16 126.848h3.576v3.576H16v-3.576Zm21.455 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm7.152 0h3.575v3.576h-3.575v-3.576Zm7.151 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576Zm10.727 0h3.576v3.576h-3.576v-3.576Zm3.576 0h3.575v3.576h-3.575v-3.576ZM16 130.424h3.576V134H16v-3.576Zm3.576 0h3.575V134h-3.575v-3.576Zm3.575 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.575V134h-3.575v-3.576Zm10.727 0h3.576V134h-3.576v-3.576Zm3.576 0h3.575V134h-3.575v-3.576Zm3.575 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm14.303 0h3.576V134h-3.576v-3.576Zm25.03 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.575V134h-3.575v-3.576Zm7.151 0h3.576V134h-3.576v-3.576Zm3.576 0h3.576V134h-3.576v-3.576Zm3.576 0h3.575V134h-3.575v-3.576Zm7.151 0H134V134h-3.576v-3.576Z" fill="#000"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h150v150H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mobile-download-qr-existing-user.svg b/browser/components/newtab/data/content/assets/mobile-download-qr-existing-user.svg
new file mode 100644
index 0000000000..8c1662bf48
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mobile-download-qr-existing-user.svg
@@ -0,0 +1,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/. -->
+<svg width="150" height="150" viewBox="0 0 150 150" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect x="1" y="1" width="148" height="148" rx="13" fill="white" stroke="#DCDCDC" stroke-width="2"/>
+<path d="M16 16H20.069V20.069H16V16ZM20.069 16H24.1379V20.069H20.069V16ZM24.1379 16H28.2069V20.069H24.1379V16ZM28.2069 16H32.2759V20.069H28.2069V16ZM32.2759 16H36.3448V20.069H32.2759V16ZM36.3448 16H40.4138V20.069H36.3448V16ZM40.4138 16H44.4828V20.069H40.4138V16ZM64.8276 16H68.8966V20.069H64.8276V16ZM68.8966 16H72.9655V20.069H68.8966V16ZM77.0345 16H81.1034V20.069H77.0345V16ZM81.1034 16H85.1724V20.069H81.1034V16ZM85.1724 16H89.2414V20.069H85.1724V16ZM89.2414 16H93.3103V20.069H89.2414V16ZM93.3103 16H97.3793V20.069H93.3103V16ZM105.517 16H109.586V20.069H105.517V16ZM109.586 16H113.655V20.069H109.586V16ZM113.655 16H117.724V20.069H113.655V16ZM117.724 16H121.793V20.069H117.724V16ZM121.793 16H125.862V20.069H121.793V16ZM125.862 16H129.931V20.069H125.862V16ZM129.931 16H134V20.069H129.931V16ZM16 20.069H20.069V24.1379H16V20.069ZM40.4138 20.069H44.4828V24.1379H40.4138V20.069ZM48.5517 20.069H52.6207V24.1379H48.5517V20.069ZM56.6897 20.069H60.7586V24.1379H56.6897V20.069ZM68.8966 20.069H72.9655V24.1379H68.8966V20.069ZM72.9655 20.069H77.0345V24.1379H72.9655V20.069ZM77.0345 20.069H81.1034V24.1379H77.0345V20.069ZM81.1034 20.069H85.1724V24.1379H81.1034V20.069ZM97.3793 20.069H101.448V24.1379H97.3793V20.069ZM105.517 20.069H109.586V24.1379H105.517V20.069ZM129.931 20.069H134V24.1379H129.931V20.069ZM16 24.1379H20.069V28.2069H16V24.1379ZM24.1379 24.1379H28.2069V28.2069H24.1379V24.1379ZM28.2069 24.1379H32.2759V28.2069H28.2069V24.1379ZM32.2759 24.1379H36.3448V28.2069H32.2759V24.1379ZM40.4138 24.1379H44.4828V28.2069H40.4138V24.1379ZM52.6207 24.1379H56.6897V28.2069H52.6207V24.1379ZM56.6897 24.1379H60.7586V28.2069H56.6897V24.1379ZM60.7586 24.1379H64.8276V28.2069H60.7586V24.1379ZM81.1034 24.1379H85.1724V28.2069H81.1034V24.1379ZM85.1724 24.1379H89.2414V28.2069H85.1724V24.1379ZM93.3103 24.1379H97.3793V28.2069H93.3103V24.1379ZM97.3793 24.1379H101.448V28.2069H97.3793V24.1379ZM105.517 24.1379H109.586V28.2069H105.517V24.1379ZM113.655 24.1379H117.724V28.2069H113.655V24.1379ZM117.724 24.1379H121.793V28.2069H117.724V24.1379ZM121.793 24.1379H125.862V28.2069H121.793V24.1379ZM129.931 24.1379H134V28.2069H129.931V24.1379ZM16 28.2069H20.069V32.2759H16V28.2069ZM24.1379 28.2069H28.2069V32.2759H24.1379V28.2069ZM28.2069 28.2069H32.2759V32.2759H28.2069V28.2069ZM32.2759 28.2069H36.3448V32.2759H32.2759V28.2069ZM40.4138 28.2069H44.4828V32.2759H40.4138V28.2069ZM56.6897 28.2069H60.7586V32.2759H56.6897V28.2069ZM60.7586 28.2069H64.8276V32.2759H60.7586V28.2069ZM68.8966 28.2069H72.9655V32.2759H68.8966V28.2069ZM72.9655 28.2069H77.0345V32.2759H72.9655V28.2069ZM77.0345 28.2069H81.1034V32.2759H77.0345V28.2069ZM93.3103 28.2069H97.3793V32.2759H93.3103V28.2069ZM105.517 28.2069H109.586V32.2759H105.517V28.2069ZM113.655 28.2069H117.724V32.2759H113.655V28.2069ZM117.724 28.2069H121.793V32.2759H117.724V28.2069ZM121.793 28.2069H125.862V32.2759H121.793V28.2069ZM129.931 28.2069H134V32.2759H129.931V28.2069ZM16 32.2759H20.069V36.3448H16V32.2759ZM24.1379 32.2759H28.2069V36.3448H24.1379V32.2759ZM28.2069 32.2759H32.2759V36.3448H28.2069V32.2759ZM32.2759 32.2759H36.3448V36.3448H32.2759V32.2759ZM40.4138 32.2759H44.4828V36.3448H40.4138V32.2759ZM60.7586 32.2759H64.8276V36.3448H60.7586V32.2759ZM64.8276 32.2759H68.8966V36.3448H64.8276V32.2759ZM68.8966 32.2759H72.9655V36.3448H68.8966V32.2759ZM72.9655 32.2759H77.0345V36.3448H72.9655V32.2759ZM77.0345 32.2759H81.1034V36.3448H77.0345V32.2759ZM81.1034 32.2759H85.1724V36.3448H81.1034V32.2759ZM89.2414 32.2759H93.3103V36.3448H89.2414V32.2759ZM105.517 32.2759H109.586V36.3448H105.517V32.2759ZM113.655 32.2759H117.724V36.3448H113.655V32.2759ZM117.724 32.2759H121.793V36.3448H117.724V32.2759ZM121.793 32.2759H125.862V36.3448H121.793V32.2759ZM129.931 32.2759H134V36.3448H129.931V32.2759ZM16 36.3448H20.069V40.4138H16V36.3448ZM40.4138 36.3448H44.4828V40.4138H40.4138V36.3448ZM48.5517 36.3448H52.6207V40.4138H48.5517V36.3448ZM52.6207 36.3448H56.6897V40.4138H52.6207V36.3448ZM56.6897 36.3448H60.7586V40.4138H56.6897V36.3448ZM60.7586 36.3448H64.8276V40.4138H60.7586V36.3448ZM68.8966 36.3448H72.9655V40.4138H68.8966V36.3448ZM77.0345 36.3448H81.1034V40.4138H77.0345V36.3448ZM89.2414 36.3448H93.3103V40.4138H89.2414V36.3448ZM93.3103 36.3448H97.3793V40.4138H93.3103V36.3448ZM97.3793 36.3448H101.448V40.4138H97.3793V36.3448ZM105.517 36.3448H109.586V40.4138H105.517V36.3448ZM129.931 36.3448H134V40.4138H129.931V36.3448ZM16 40.4138H20.069V44.4828H16V40.4138ZM20.069 40.4138H24.1379V44.4828H20.069V40.4138ZM24.1379 40.4138H28.2069V44.4828H24.1379V40.4138ZM28.2069 40.4138H32.2759V44.4828H28.2069V40.4138ZM32.2759 40.4138H36.3448V44.4828H32.2759V40.4138ZM36.3448 40.4138H40.4138V44.4828H36.3448V40.4138ZM40.4138 40.4138H44.4828V44.4828H40.4138V40.4138ZM48.5517 40.4138H52.6207V44.4828H48.5517V40.4138ZM56.6897 40.4138H60.7586V44.4828H56.6897V40.4138ZM64.8276 40.4138H68.8966V44.4828H64.8276V40.4138ZM72.9655 40.4138H77.0345V44.4828H72.9655V40.4138ZM81.1034 40.4138H85.1724V44.4828H81.1034V40.4138ZM89.2414 40.4138H93.3103V44.4828H89.2414V40.4138ZM97.3793 40.4138H101.448V44.4828H97.3793V40.4138ZM105.517 40.4138H109.586V44.4828H105.517V40.4138ZM109.586 40.4138H113.655V44.4828H109.586V40.4138ZM113.655 40.4138H117.724V44.4828H113.655V40.4138ZM117.724 40.4138H121.793V44.4828H117.724V40.4138ZM121.793 40.4138H125.862V44.4828H121.793V40.4138ZM125.862 40.4138H129.931V44.4828H125.862V40.4138ZM129.931 40.4138H134V44.4828H129.931V40.4138ZM48.5517 44.4828H52.6207V48.5517H48.5517V44.4828ZM52.6207 44.4828H56.6897V48.5517H52.6207V44.4828ZM56.6897 44.4828H60.7586V48.5517H56.6897V44.4828ZM72.9655 44.4828H77.0345V48.5517H72.9655V44.4828ZM77.0345 44.4828H81.1034V48.5517H77.0345V44.4828ZM85.1724 44.4828H89.2414V48.5517H85.1724V44.4828ZM89.2414 44.4828H93.3103V48.5517H89.2414V44.4828ZM93.3103 44.4828H97.3793V48.5517H93.3103V44.4828ZM32.2759 48.5517H36.3448V52.6207H32.2759V48.5517ZM36.3448 48.5517H40.4138V52.6207H36.3448V48.5517ZM40.4138 48.5517H44.4828V52.6207H40.4138V48.5517ZM44.4828 48.5517H48.5517V52.6207H44.4828V48.5517ZM52.6207 48.5517H56.6897V52.6207H52.6207V48.5517ZM60.7586 48.5517H64.8276V52.6207H60.7586V48.5517ZM64.8276 48.5517H68.8966V52.6207H64.8276V48.5517ZM68.8966 48.5517H72.9655V52.6207H68.8966V48.5517ZM77.0345 48.5517H81.1034V52.6207H77.0345V48.5517ZM81.1034 48.5517H85.1724V52.6207H81.1034V48.5517ZM89.2414 48.5517H93.3103V52.6207H89.2414V48.5517ZM97.3793 48.5517H101.448V52.6207H97.3793V48.5517ZM105.517 48.5517H109.586V52.6207H105.517V48.5517ZM109.586 48.5517H113.655V52.6207H109.586V48.5517ZM125.862 48.5517H129.931V52.6207H125.862V48.5517ZM16 52.6207H20.069V56.6897H16V52.6207ZM20.069 52.6207H24.1379V56.6897H20.069V52.6207ZM28.2069 52.6207H32.2759V56.6897H28.2069V52.6207ZM36.3448 52.6207H40.4138V56.6897H36.3448V52.6207ZM44.4828 52.6207H48.5517V56.6897H44.4828V52.6207ZM48.5517 52.6207H52.6207V56.6897H48.5517V52.6207ZM56.6897 52.6207H60.7586V56.6897H56.6897V52.6207ZM60.7586 52.6207H64.8276V56.6897H60.7586V52.6207ZM68.8966 52.6207H72.9655V56.6897H68.8966V52.6207ZM93.3103 52.6207H97.3793V56.6897H93.3103V52.6207ZM97.3793 52.6207H101.448V56.6897H97.3793V52.6207ZM109.586 52.6207H113.655V56.6897H109.586V52.6207ZM113.655 52.6207H117.724V56.6897H113.655V52.6207ZM117.724 52.6207H121.793V56.6897H117.724V52.6207ZM121.793 52.6207H125.862V56.6897H121.793V52.6207ZM125.862 52.6207H129.931V56.6897H125.862V52.6207ZM129.931 52.6207H134V56.6897H129.931V52.6207ZM16 56.6897H20.069V60.7586H16V56.6897ZM20.069 56.6897H24.1379V60.7586H20.069V56.6897ZM24.1379 56.6897H28.2069V60.7586H24.1379V56.6897ZM28.2069 56.6897H32.2759V60.7586H28.2069V56.6897ZM32.2759 56.6897H36.3448V60.7586H32.2759V56.6897ZM40.4138 56.6897H44.4828V60.7586H40.4138V56.6897ZM44.4828 56.6897H48.5517V60.7586H44.4828V56.6897ZM52.6207 56.6897H56.6897V60.7586H52.6207V56.6897ZM60.7586 56.6897H64.8276V60.7586H60.7586V56.6897ZM64.8276 56.6897H68.8966V60.7586H64.8276V56.6897ZM68.8966 56.6897H72.9655V60.7586H68.8966V56.6897ZM72.9655 56.6897H77.0345V60.7586H72.9655V56.6897ZM77.0345 56.6897H81.1034V60.7586H77.0345V56.6897ZM81.1034 56.6897H85.1724V60.7586H81.1034V56.6897ZM85.1724 56.6897H89.2414V60.7586H85.1724V56.6897ZM89.2414 56.6897H93.3103V60.7586H89.2414V56.6897ZM101.448 56.6897H105.517V60.7586H101.448V56.6897ZM113.655 56.6897H117.724V60.7586H113.655V56.6897ZM117.724 56.6897H121.793V60.7586H117.724V56.6897ZM129.931 56.6897H134V60.7586H129.931V56.6897ZM16 60.7586H20.069V64.8276H16V60.7586ZM24.1379 60.7586H28.2069V64.8276H24.1379V60.7586ZM28.2069 60.7586H32.2759V64.8276H28.2069V60.7586ZM32.2759 60.7586H36.3448V64.8276H32.2759V60.7586ZM48.5517 60.7586H52.6207V64.8276H48.5517V60.7586ZM56.6897 60.7586H60.7586V64.8276H56.6897V60.7586ZM64.8276 60.7586H68.8966V64.8276H64.8276V60.7586ZM72.9655 60.7586H77.0345V64.8276H72.9655V60.7586ZM85.1724 60.7586H89.2414V64.8276H85.1724V60.7586ZM89.2414 60.7586H93.3103V64.8276H89.2414V60.7586ZM101.448 60.7586H105.517V64.8276H101.448V60.7586ZM125.862 60.7586H129.931V64.8276H125.862V60.7586ZM129.931 60.7586H134V64.8276H129.931V60.7586ZM20.069 64.8276H24.1379V68.8966H20.069V64.8276ZM24.1379 64.8276H28.2069V68.8966H24.1379V64.8276ZM32.2759 64.8276H36.3448V68.8966H32.2759V64.8276ZM36.3448 64.8276H40.4138V68.8966H36.3448V64.8276ZM40.4138 64.8276H44.4828V68.8966H40.4138V64.8276ZM48.5517 64.8276H52.6207V68.8966H48.5517V64.8276ZM64.8276 64.8276H68.8966V68.8966H64.8276V64.8276ZM68.8966 64.8276H72.9655V68.8966H68.8966V64.8276ZM72.9655 64.8276H77.0345V68.8966H72.9655V64.8276ZM85.1724 64.8276H89.2414V68.8966H85.1724V64.8276ZM93.3103 64.8276H97.3793V68.8966H93.3103V64.8276ZM109.586 64.8276H113.655V68.8966H109.586V64.8276ZM117.724 64.8276H121.793V68.8966H117.724V64.8276ZM129.931 64.8276H134V68.8966H129.931V64.8276ZM20.069 68.8966H24.1379V72.9655H20.069V68.8966ZM24.1379 68.8966H28.2069V72.9655H24.1379V68.8966ZM28.2069 68.8966H32.2759V72.9655H28.2069V68.8966ZM36.3448 68.8966H40.4138V72.9655H36.3448V68.8966ZM44.4828 68.8966H48.5517V72.9655H44.4828V68.8966ZM48.5517 68.8966H52.6207V72.9655H48.5517V68.8966ZM52.6207 68.8966H56.6897V72.9655H52.6207V68.8966ZM68.8966 68.8966H72.9655V72.9655H68.8966V68.8966ZM77.0345 68.8966H81.1034V72.9655H77.0345V68.8966ZM85.1724 68.8966H89.2414V72.9655H85.1724V68.8966ZM89.2414 68.8966H93.3103V72.9655H89.2414V68.8966ZM105.517 68.8966H109.586V72.9655H105.517V68.8966ZM113.655 68.8966H117.724V72.9655H113.655V68.8966ZM121.793 68.8966H125.862V72.9655H121.793V68.8966ZM129.931 68.8966H134V72.9655H129.931V68.8966ZM16 72.9655H20.069V77.0345H16V72.9655ZM28.2069 72.9655H32.2759V77.0345H28.2069V72.9655ZM40.4138 72.9655H44.4828V77.0345H40.4138V72.9655ZM44.4828 72.9655H48.5517V77.0345H44.4828V72.9655ZM48.5517 72.9655H52.6207V77.0345H48.5517V72.9655ZM52.6207 72.9655H56.6897V77.0345H52.6207V72.9655ZM64.8276 72.9655H68.8966V77.0345H64.8276V72.9655ZM68.8966 72.9655H72.9655V77.0345H68.8966V72.9655ZM72.9655 72.9655H77.0345V77.0345H72.9655V72.9655ZM77.0345 72.9655H81.1034V77.0345H77.0345V72.9655ZM81.1034 72.9655H85.1724V77.0345H81.1034V72.9655ZM97.3793 72.9655H101.448V77.0345H97.3793V72.9655ZM113.655 72.9655H117.724V77.0345H113.655V72.9655ZM129.931 72.9655H134V77.0345H129.931V72.9655ZM16 77.0345H20.069V81.1034H16V77.0345ZM20.069 77.0345H24.1379V81.1034H20.069V77.0345ZM24.1379 77.0345H28.2069V81.1034H24.1379V77.0345ZM28.2069 77.0345H32.2759V81.1034H28.2069V77.0345ZM44.4828 77.0345H48.5517V81.1034H44.4828V77.0345ZM48.5517 77.0345H52.6207V81.1034H48.5517V77.0345ZM52.6207 77.0345H56.6897V81.1034H52.6207V77.0345ZM56.6897 77.0345H60.7586V81.1034H56.6897V77.0345ZM72.9655 77.0345H77.0345V81.1034H72.9655V77.0345ZM77.0345 77.0345H81.1034V81.1034H77.0345V77.0345ZM85.1724 77.0345H89.2414V81.1034H85.1724V77.0345ZM97.3793 77.0345H101.448V81.1034H97.3793V77.0345ZM101.448 77.0345H105.517V81.1034H101.448V77.0345ZM109.586 77.0345H113.655V81.1034H109.586V77.0345ZM117.724 77.0345H121.793V81.1034H117.724V77.0345ZM125.862 77.0345H129.931V81.1034H125.862V77.0345ZM129.931 77.0345H134V81.1034H129.931V77.0345ZM24.1379 81.1034H28.2069V85.1724H24.1379V81.1034ZM28.2069 81.1034H32.2759V85.1724H28.2069V81.1034ZM36.3448 81.1034H40.4138V85.1724H36.3448V81.1034ZM40.4138 81.1034H44.4828V85.1724H40.4138V81.1034ZM48.5517 81.1034H52.6207V85.1724H48.5517V81.1034ZM64.8276 81.1034H68.8966V85.1724H64.8276V81.1034ZM68.8966 81.1034H72.9655V85.1724H68.8966V81.1034ZM81.1034 81.1034H85.1724V85.1724H81.1034V81.1034ZM89.2414 81.1034H93.3103V85.1724H89.2414V81.1034ZM109.586 81.1034H113.655V85.1724H109.586V81.1034ZM113.655 81.1034H117.724V85.1724H113.655V81.1034ZM125.862 81.1034H129.931V85.1724H125.862V81.1034ZM129.931 81.1034H134V85.1724H129.931V81.1034ZM16 85.1724H20.069V89.2414H16V85.1724ZM24.1379 85.1724H28.2069V89.2414H24.1379V85.1724ZM44.4828 85.1724H48.5517V89.2414H44.4828V85.1724ZM48.5517 85.1724H52.6207V89.2414H48.5517V85.1724ZM52.6207 85.1724H56.6897V89.2414H52.6207V85.1724ZM64.8276 85.1724H68.8966V89.2414H64.8276V85.1724ZM68.8966 85.1724H72.9655V89.2414H68.8966V85.1724ZM72.9655 85.1724H77.0345V89.2414H72.9655V85.1724ZM77.0345 85.1724H81.1034V89.2414H77.0345V85.1724ZM93.3103 85.1724H97.3793V89.2414H93.3103V85.1724ZM101.448 85.1724H105.517V89.2414H101.448V85.1724ZM105.517 85.1724H109.586V89.2414H105.517V85.1724ZM109.586 85.1724H113.655V89.2414H109.586V85.1724ZM113.655 85.1724H117.724V89.2414H113.655V85.1724ZM129.931 85.1724H134V89.2414H129.931V85.1724ZM24.1379 89.2414H28.2069V93.3103H24.1379V89.2414ZM28.2069 89.2414H32.2759V93.3103H28.2069V89.2414ZM32.2759 89.2414H36.3448V93.3103H32.2759V89.2414ZM40.4138 89.2414H44.4828V93.3103H40.4138V89.2414ZM44.4828 89.2414H48.5517V93.3103H44.4828V89.2414ZM64.8276 89.2414H68.8966V93.3103H64.8276V89.2414ZM81.1034 89.2414H85.1724V93.3103H81.1034V89.2414ZM85.1724 89.2414H89.2414V93.3103H85.1724V89.2414ZM97.3793 89.2414H101.448V93.3103H97.3793V89.2414ZM109.586 89.2414H113.655V93.3103H109.586V89.2414ZM113.655 89.2414H117.724V93.3103H113.655V89.2414ZM117.724 89.2414H121.793V93.3103H117.724V89.2414ZM121.793 89.2414H125.862V93.3103H121.793V89.2414ZM129.931 89.2414H134V93.3103H129.931V89.2414ZM32.2759 93.3103H36.3448V97.3793H32.2759V93.3103ZM44.4828 93.3103H48.5517V97.3793H44.4828V93.3103ZM48.5517 93.3103H52.6207V97.3793H48.5517V93.3103ZM52.6207 93.3103H56.6897V97.3793H52.6207V93.3103ZM56.6897 93.3103H60.7586V97.3793H56.6897V93.3103ZM68.8966 93.3103H72.9655V97.3793H68.8966V93.3103ZM77.0345 93.3103H81.1034V97.3793H77.0345V93.3103ZM81.1034 93.3103H85.1724V97.3793H81.1034V93.3103ZM85.1724 93.3103H89.2414V97.3793H85.1724V93.3103ZM93.3103 93.3103H97.3793V97.3793H93.3103V93.3103ZM109.586 93.3103H113.655V97.3793H109.586V93.3103ZM125.862 93.3103H129.931V97.3793H125.862V93.3103ZM16 97.3793H20.069V101.448H16V97.3793ZM20.069 97.3793H24.1379V101.448H20.069V97.3793ZM24.1379 97.3793H28.2069V101.448H24.1379V97.3793ZM32.2759 97.3793H36.3448V101.448H32.2759V97.3793ZM36.3448 97.3793H40.4138V101.448H36.3448V97.3793ZM40.4138 97.3793H44.4828V101.448H40.4138V97.3793ZM44.4828 97.3793H48.5517V101.448H44.4828V97.3793ZM52.6207 97.3793H56.6897V101.448H52.6207V97.3793ZM60.7586 97.3793H64.8276V101.448H60.7586V97.3793ZM68.8966 97.3793H72.9655V101.448H68.8966V97.3793ZM72.9655 97.3793H77.0345V101.448H72.9655V97.3793ZM77.0345 97.3793H81.1034V101.448H77.0345V97.3793ZM85.1724 97.3793H89.2414V101.448H85.1724V97.3793ZM89.2414 97.3793H93.3103V101.448H89.2414V97.3793ZM97.3793 97.3793H101.448V101.448H97.3793V97.3793ZM101.448 97.3793H105.517V101.448H101.448V97.3793ZM105.517 97.3793H109.586V101.448H105.517V97.3793ZM109.586 97.3793H113.655V101.448H109.586V97.3793ZM113.655 97.3793H117.724V101.448H113.655V97.3793ZM125.862 97.3793H129.931V101.448H125.862V97.3793ZM48.5517 101.448H52.6207V105.517H48.5517V101.448ZM56.6897 101.448H60.7586V105.517H56.6897V101.448ZM72.9655 101.448H77.0345V105.517H72.9655V101.448ZM77.0345 101.448H81.1034V105.517H77.0345V101.448ZM81.1034 101.448H85.1724V105.517H81.1034V101.448ZM85.1724 101.448H89.2414V105.517H85.1724V101.448ZM89.2414 101.448H93.3103V105.517H89.2414V101.448ZM93.3103 101.448H97.3793V105.517H93.3103V101.448ZM97.3793 101.448H101.448V105.517H97.3793V101.448ZM113.655 101.448H117.724V105.517H113.655V101.448ZM121.793 101.448H125.862V105.517H121.793V101.448ZM129.931 101.448H134V105.517H129.931V101.448ZM16 105.517H20.069V109.586H16V105.517ZM20.069 105.517H24.1379V109.586H20.069V105.517ZM24.1379 105.517H28.2069V109.586H24.1379V105.517ZM28.2069 105.517H32.2759V109.586H28.2069V105.517ZM32.2759 105.517H36.3448V109.586H32.2759V105.517ZM36.3448 105.517H40.4138V109.586H36.3448V105.517ZM40.4138 105.517H44.4828V109.586H40.4138V105.517ZM48.5517 105.517H52.6207V109.586H48.5517V105.517ZM64.8276 105.517H68.8966V109.586H64.8276V105.517ZM68.8966 105.517H72.9655V109.586H68.8966V105.517ZM89.2414 105.517H93.3103V109.586H89.2414V105.517ZM93.3103 105.517H97.3793V109.586H93.3103V105.517ZM97.3793 105.517H101.448V109.586H97.3793V105.517ZM105.517 105.517H109.586V109.586H105.517V105.517ZM113.655 105.517H117.724V109.586H113.655V105.517ZM129.931 105.517H134V109.586H129.931V105.517ZM16 109.586H20.069V113.655H16V109.586ZM40.4138 109.586H44.4828V113.655H40.4138V109.586ZM48.5517 109.586H52.6207V113.655H48.5517V109.586ZM52.6207 109.586H56.6897V113.655H52.6207V109.586ZM72.9655 109.586H77.0345V113.655H72.9655V109.586ZM85.1724 109.586H89.2414V113.655H85.1724V109.586ZM89.2414 109.586H93.3103V113.655H89.2414V109.586ZM93.3103 109.586H97.3793V113.655H93.3103V109.586ZM97.3793 109.586H101.448V113.655H97.3793V109.586ZM113.655 109.586H117.724V113.655H113.655V109.586ZM117.724 109.586H121.793V113.655H117.724V109.586ZM125.862 109.586H129.931V113.655H125.862V109.586ZM16 113.655H20.069V117.724H16V113.655ZM24.1379 113.655H28.2069V117.724H24.1379V113.655ZM28.2069 113.655H32.2759V117.724H28.2069V113.655ZM32.2759 113.655H36.3448V117.724H32.2759V113.655ZM40.4138 113.655H44.4828V117.724H40.4138V113.655ZM48.5517 113.655H52.6207V117.724H48.5517V113.655ZM52.6207 113.655H56.6897V117.724H52.6207V113.655ZM68.8966 113.655H72.9655V117.724H68.8966V113.655ZM72.9655 113.655H77.0345V117.724H72.9655V113.655ZM77.0345 113.655H81.1034V117.724H77.0345V113.655ZM85.1724 113.655H89.2414V117.724H85.1724V113.655ZM93.3103 113.655H97.3793V117.724H93.3103V113.655ZM97.3793 113.655H101.448V117.724H97.3793V113.655ZM101.448 113.655H105.517V117.724H101.448V113.655ZM105.517 113.655H109.586V117.724H105.517V113.655ZM109.586 113.655H113.655V117.724H109.586V113.655ZM113.655 113.655H117.724V117.724H113.655V113.655ZM125.862 113.655H129.931V117.724H125.862V113.655ZM129.931 113.655H134V117.724H129.931V113.655ZM16 117.724H20.069V121.793H16V117.724ZM24.1379 117.724H28.2069V121.793H24.1379V117.724ZM28.2069 117.724H32.2759V121.793H28.2069V117.724ZM32.2759 117.724H36.3448V121.793H32.2759V117.724ZM40.4138 117.724H44.4828V121.793H40.4138V117.724ZM56.6897 117.724H60.7586V121.793H56.6897V117.724ZM60.7586 117.724H64.8276V121.793H60.7586V117.724ZM81.1034 117.724H85.1724V121.793H81.1034V117.724ZM85.1724 117.724H89.2414V121.793H85.1724V117.724ZM89.2414 117.724H93.3103V121.793H89.2414V117.724ZM109.586 117.724H113.655V121.793H109.586V117.724ZM117.724 117.724H121.793V121.793H117.724V117.724ZM121.793 117.724H125.862V121.793H121.793V117.724ZM125.862 117.724H129.931V121.793H125.862V117.724ZM16 121.793H20.069V125.862H16V121.793ZM24.1379 121.793H28.2069V125.862H24.1379V121.793ZM28.2069 121.793H32.2759V125.862H28.2069V121.793ZM32.2759 121.793H36.3448V125.862H32.2759V121.793ZM40.4138 121.793H44.4828V125.862H40.4138V121.793ZM56.6897 121.793H60.7586V125.862H56.6897V121.793ZM64.8276 121.793H68.8966V125.862H64.8276V121.793ZM72.9655 121.793H77.0345V125.862H72.9655V121.793ZM81.1034 121.793H85.1724V125.862H81.1034V121.793ZM85.1724 121.793H89.2414V125.862H85.1724V121.793ZM89.2414 121.793H93.3103V125.862H89.2414V121.793ZM93.3103 121.793H97.3793V125.862H93.3103V121.793ZM97.3793 121.793H101.448V125.862H97.3793V121.793ZM101.448 121.793H105.517V125.862H101.448V121.793ZM117.724 121.793H121.793V125.862H117.724V121.793ZM121.793 121.793H125.862V125.862H121.793V121.793ZM125.862 121.793H129.931V125.862H125.862V121.793ZM129.931 121.793H134V125.862H129.931V121.793ZM16 125.862H20.069V129.931H16V125.862ZM40.4138 125.862H44.4828V129.931H40.4138V125.862ZM52.6207 125.862H56.6897V129.931H52.6207V125.862ZM60.7586 125.862H64.8276V129.931H60.7586V125.862ZM64.8276 125.862H68.8966V129.931H64.8276V125.862ZM72.9655 125.862H77.0345V129.931H72.9655V125.862ZM77.0345 125.862H81.1034V129.931H77.0345V125.862ZM89.2414 125.862H93.3103V129.931H89.2414V125.862ZM101.448 125.862H105.517V129.931H101.448V125.862ZM105.517 125.862H109.586V129.931H105.517V125.862ZM109.586 125.862H113.655V129.931H109.586V125.862ZM117.724 125.862H121.793V129.931H117.724V125.862ZM125.862 125.862H129.931V129.931H125.862V125.862ZM129.931 125.862H134V129.931H129.931V125.862ZM16 129.931H20.069V134H16V129.931ZM20.069 129.931H24.1379V134H20.069V129.931ZM24.1379 129.931H28.2069V134H24.1379V129.931ZM28.2069 129.931H32.2759V134H28.2069V129.931ZM32.2759 129.931H36.3448V134H32.2759V129.931ZM36.3448 129.931H40.4138V134H36.3448V129.931ZM40.4138 129.931H44.4828V134H40.4138V129.931ZM52.6207 129.931H56.6897V134H52.6207V129.931ZM56.6897 129.931H60.7586V134H56.6897V129.931ZM64.8276 129.931H68.8966V134H64.8276V129.931ZM72.9655 129.931H77.0345V134H72.9655V129.931ZM81.1034 129.931H85.1724V134H81.1034V129.931ZM89.2414 129.931H93.3103V134H89.2414V129.931ZM97.3793 129.931H101.448V134H97.3793V129.931ZM113.655 129.931H117.724V134H113.655V129.931ZM121.793 129.931H125.862V134H121.793V129.931ZM125.862 129.931H129.931V134H125.862V129.931Z" fill="black"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/mobile-download-qr-new-user-cn.svg b/browser/components/newtab/data/content/assets/mobile-download-qr-new-user-cn.svg
new file mode 100644
index 0000000000..cf25a0e18d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mobile-download-qr-new-user-cn.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="98" height="98" viewBox="0 0 98 98" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M90 0H8a8 8 0 0 0-8 8v82a8 8 0 0 0 8 8h82a8 8 0 0 0 8-8V8a8 8 0 0 0-8-8Z" fill="#fff"/><path d="M11 11h2.328v2.328H11V11Zm2.328 0h2.327v2.328h-2.327V11Zm2.327 0h2.328v2.328h-2.328V11Zm2.328 0h2.327v2.328h-2.327V11Zm2.327 0h2.328v2.328H20.31V11Zm2.328 0h2.327v2.328h-2.327V11Zm2.327 0h2.328v2.328h-2.328V11Zm11.638 0h2.328v2.328h-2.328V11Zm11.638 0h2.328v2.328H48.24V11Zm6.983 0h2.328v2.328h-2.328V11Zm2.328 0h2.327v2.328h-2.328V11Zm2.327 0h2.328v2.328h-2.328V11Zm2.328 0h2.327v2.328h-2.327V11Zm4.655 0h2.327v2.328h-2.327V11Zm4.655 0h2.328v2.328h-2.328V11Zm2.328 0h2.327v2.328h-2.328V11Zm2.327 0H78.5v2.328h-2.328V11Zm2.328 0h2.327v2.328H78.5V11Zm2.327 0h2.328v2.328h-2.328V11Zm2.328 0h2.327v2.328h-2.327V11Zm2.327 0h2.328v2.328h-2.328V11ZM11 13.328h2.328v2.327H11v-2.327Zm13.965 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327H38.93v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H48.24v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm16.293 0h2.328v2.327h-2.328v-2.327Zm13.965 0h2.328v2.327h-2.328v-2.327ZM11 15.655h2.328v2.328H11v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm9.31 0h2.328v2.328H38.93v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm6.982 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.655 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328ZM11 17.983h2.328v2.327H11v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H20.31v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm11.638 0h2.327v2.327h-2.327v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm4.655 0H78.5v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327H78.5v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327ZM11 20.31h2.328v2.328H11V20.31Zm4.655 0h2.328v2.328h-2.328V20.31Zm2.328 0h2.327v2.328h-2.327V20.31Zm2.327 0h2.328v2.328H20.31V20.31Zm4.655 0h2.328v2.328h-2.328V20.31Zm4.656 0h2.327v2.328h-2.327V20.31Zm4.655 0h2.327v2.328h-2.327V20.31Zm2.327 0h2.328v2.328h-2.328V20.31Zm2.328 0h2.328v2.328H38.93V20.31Zm4.655 0h2.328v2.328h-2.328V20.31Zm4.655 0h2.328v2.328H48.24V20.31Zm2.328 0h2.327v2.328H50.57V20.31Zm2.327 0h2.328v2.328h-2.328V20.31Zm2.328 0h2.328v2.328h-2.328V20.31Zm2.328 0h2.327v2.328h-2.328V20.31Zm2.327 0h2.328v2.328h-2.328V20.31Zm2.328 0h2.327v2.328h-2.327V20.31Zm2.327 0h2.328v2.328h-2.328V20.31Zm6.983 0h2.328v2.328h-2.328V20.31Zm4.655 0H78.5v2.328h-2.328V20.31Zm2.328 0h2.327v2.328H78.5V20.31Zm2.327 0h2.328v2.328h-2.328V20.31Zm4.655 0h2.328v2.328h-2.328V20.31ZM11 22.638h2.328v2.327H11v-2.327Zm13.965 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.328v2.327H38.93v-2.327Zm9.31 0h2.328v2.327H48.24v-2.327Zm11.638 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm13.965 0h2.328v2.327h-2.328v-2.327ZM11 24.965h2.328v2.328H11v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.328v2.328H38.93v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328H48.24v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm2.327 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm-51.206 2.328h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm6.982 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm-51.207 2.328h2.328v2.327h-2.328v-2.327Zm6.983 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327Zm9.31 0h2.328v2.327h-2.327v-2.327Zm2.328 0h2.328v2.327H48.24v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm9.31 0h2.328v2.327h-2.327v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.328v-2.327Zm2.327 0H78.5v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327H78.5v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327ZM11 31.948h2.328v2.328H11v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm11.638 0h2.327v2.328h-2.327v-2.328Zm11.638 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H48.24v-2.328Zm2.328 0h2.327v2.328H50.57v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm9.31 0h2.328v2.328h-2.327v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm4.655 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328ZM11 34.276h2.328v2.327H11v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H20.31v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H48.24v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.328v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.328v-2.327Zm2.327 0H78.5v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327H78.5v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327ZM11 36.603h2.328v2.328H11v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm11.638 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328H38.93v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328H48.24v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm9.31 0h2.328v2.328h-2.327v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.328v-2.328Zm9.31 0h2.327v2.328h-2.327v-2.328ZM11 38.931h2.328v2.328H11V38.93Zm13.965 0h2.328v2.328h-2.328V38.93Zm4.656 0h2.327v2.328h-2.327V38.93Zm2.327 0h2.328v2.328h-2.328V38.93Zm2.328 0h2.327v2.328h-2.327V38.93Zm2.327 0h2.328v2.328h-2.328V38.93Zm9.31 0h2.328v2.328h-2.327V38.93Zm2.328 0h2.328v2.328H48.24V38.93Zm2.328 0h2.327v2.328H50.57V38.93Zm9.31 0h2.328v2.328h-2.328V38.93Zm2.328 0h2.327v2.328h-2.327V38.93Zm2.327 0h2.328v2.328h-2.328V38.93Zm2.328 0h2.327v2.328h-2.327V38.93Zm4.655 0h2.328v2.328h-2.328V38.93Zm4.655 0H78.5v2.328h-2.328V38.93Zm2.328 0h2.327v2.328H78.5V38.93ZM11 41.259h2.328v2.327H11v-2.328Zm6.983 0h2.327v2.327h-2.327v-2.328Zm2.327 0h2.328v2.327H20.31v-2.328Zm9.31 0h2.328v2.327h-2.327v-2.328Zm2.328 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm2.327 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.328v2.327H38.93v-2.328Zm6.983 0h2.327v2.327h-2.327v-2.328Zm6.982 0h2.328v2.327h-2.328v-2.328Zm6.983 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm2.327 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm4.655 0h2.328v2.327h-2.328v-2.328Zm13.965 0h2.328v2.327h-2.328v-2.328ZM11 43.585h2.328v2.328H11v-2.328Zm13.965 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.327v2.328h-2.327v-2.328Zm6.982 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328H48.24v-2.328Zm2.328 0h2.327v2.328H50.57v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm4.655 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328ZM11 45.914h2.328v2.327H11v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm6.982 0h2.328v2.327H20.31v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H48.24v-2.327Zm2.328 0h2.327v2.327H50.57v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.328v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm11.638 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327ZM13.328 48.24h2.327v2.328h-2.327V48.24Zm2.327 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.327v2.328h-2.327V48.24Zm6.982 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.327v2.328h-2.327V48.24Zm2.327 0h2.328v2.328h-2.328V48.24Zm4.655 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.328v2.328H38.93V48.24Zm2.328 0h2.327v2.328h-2.328V48.24Zm4.655 0h2.327v2.328h-2.327V48.24Zm2.327 0h2.328v2.328H48.24V48.24Zm13.966 0h2.327v2.328h-2.327V48.24Zm6.982 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.328v2.328h-2.328V48.24Zm6.983 0h2.327v2.328H78.5V48.24Zm2.327 0h2.328v2.328h-2.328V48.24Zm2.328 0h2.327v2.328h-2.327V48.24ZM13.328 50.57h2.327v2.327h-2.327V50.57Zm4.655 0h2.327v2.327h-2.327V50.57Zm2.327 0h2.328v2.327H20.31V50.57Zm2.328 0h2.327v2.327h-2.327V50.57Zm4.655 0h2.328v2.327h-2.328V50.57Zm2.328 0h2.327v2.327h-2.327V50.57Zm6.982 0h2.328v2.327h-2.328V50.57Zm6.983 0h2.328v2.327h-2.328V50.57Zm6.983 0h2.327v2.327H50.57V50.57Zm6.982 0h2.328v2.327h-2.328V50.57Zm2.328 0h2.328v2.327h-2.328V50.57Zm4.655 0h2.328v2.327h-2.328V50.57Zm4.655 0h2.328v2.327h-2.328V50.57Zm2.328 0h2.328v2.327h-2.328V50.57Zm2.328 0h2.327v2.327h-2.328V50.57Zm6.982 0h2.328v2.327h-2.328V50.57Zm2.328 0h2.327v2.327h-2.327V50.57Zm2.327 0h2.328v2.327h-2.328V50.57Zm-72.154 2.327h2.327v2.328h-2.327v-2.328Zm6.982 0h2.328v2.328H20.31v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm9.31 0h2.328v2.328h-2.327v-2.328Zm9.311 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328H50.57v-2.328Zm13.965 0h2.328v2.328h-2.328v-2.328Zm11.638 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328ZM11 55.224h2.328v2.328H11v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328H48.24v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm11.638 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm2.327 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328ZM11 57.552h2.328v2.327H11v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm11.637 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm6.982 0h2.328v2.327h-2.328v-2.328Zm4.655 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm6.982 0h2.328v2.327h-2.328v-2.328Zm11.638 0h2.328v2.327h-2.328v-2.328Zm9.31 0h2.328v2.327h-2.328v-2.328Zm-55.861 2.327h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm13.966 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328H50.57v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm18.62 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328ZM11 62.207h2.328v2.327H11v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327H20.31v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm11.638 0h2.328v2.327H48.24v-2.327Zm2.328 0h2.327v2.327H50.57v-2.327Zm11.638 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.328v-2.327Zm11.637 0h2.328v2.327h-2.328v-2.327Zm-67.5 2.327h2.328v2.328h-2.327v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328H38.93v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H48.24v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328Zm18.621 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328ZM11 66.862h2.328v2.327H11v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm9.31 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327H50.57v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.327v2.327h-2.328v-2.327Zm2.327 0H78.5v2.327h-2.328v-2.327Zm6.983 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm-55.861 2.327h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm11.638 0h2.328v2.328H48.24v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm9.31 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328ZM11 71.517h2.328v2.328H11v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm11.638 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H48.24v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm9.31 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.655 0H78.5v2.328h-2.328v-2.328Zm9.31 0h2.328v2.328h-2.328v-2.328ZM11 73.845h2.328v2.327H11v-2.328Zm13.965 0h2.328v2.327h-2.328v-2.328Zm4.656 0h2.327v2.327h-2.327v-2.328Zm2.327 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327h-2.327v-2.328Zm4.655 0h2.328v2.327H38.93v-2.328Zm2.328 0h2.327v2.327h-2.328v-2.328Zm2.327 0h2.328v2.327h-2.328v-2.328Zm4.655 0h2.328v2.327H48.24v-2.328Zm9.31 0h2.328v2.327h-2.328v-2.328Zm2.328 0h2.328v2.327h-2.328v-2.328Zm6.983 0h2.327v2.327h-2.327v-2.328Zm9.31 0H78.5v2.327h-2.328v-2.328Zm2.328 0h2.327v2.327H78.5v-2.328Zm4.655 0h2.327v2.327h-2.327v-2.328Zm2.327 0h2.328v2.327h-2.328v-2.328ZM11 76.171h2.328V78.5H11v-2.328Zm4.655 0h2.328V78.5h-2.328v-2.328Zm2.328 0h2.327V78.5h-2.327v-2.328Zm2.327 0h2.328V78.5H20.31v-2.328Zm4.655 0h2.328V78.5h-2.328v-2.328Zm11.638 0h2.328V78.5h-2.328v-2.328Zm11.638 0h2.328V78.5H48.24v-2.328Zm6.983 0h2.328V78.5h-2.328v-2.328Zm4.655 0h2.328V78.5h-2.328v-2.328Zm4.655 0h2.328V78.5h-2.328v-2.328Zm2.328 0h2.327V78.5h-2.327v-2.328Zm2.327 0h2.328V78.5h-2.328v-2.328Zm2.328 0h2.328V78.5h-2.328v-2.328Zm2.328 0h2.327V78.5h-2.328v-2.328Zm2.327 0H78.5V78.5h-2.328v-2.328Zm2.328 0h2.327V78.5H78.5v-2.328ZM11 78.5h2.328v2.327H11V78.5Zm4.655 0h2.328v2.327h-2.328V78.5Zm2.328 0h2.327v2.327h-2.327V78.5Zm2.327 0h2.328v2.327H20.31V78.5Zm4.655 0h2.328v2.327h-2.328V78.5Zm6.983 0h2.328v2.327h-2.328V78.5Zm2.328 0h2.327v2.327h-2.327V78.5Zm13.965 0h2.328v2.327H48.24V78.5Zm11.638 0h2.328v2.327h-2.328V78.5Zm6.983 0h2.327v2.327h-2.327V78.5Zm2.327 0h2.328v2.327h-2.328V78.5Zm4.656 0h2.327v2.327h-2.328V78.5Zm2.327 0H78.5v2.327h-2.328V78.5Zm2.328 0h2.327v2.327H78.5V78.5Zm2.327 0h2.328v2.327h-2.328V78.5Zm2.328 0h2.327v2.327h-2.327V78.5ZM11 80.827h2.328v2.328H11v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Zm4.656 0h2.327v2.328h-2.327v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H48.24v-2.328Zm2.328 0h2.327v2.328H50.57v-2.328Zm13.965 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm9.31 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm4.655 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328ZM11 83.155h2.328v2.327H11v-2.327Zm13.965 0h2.328v2.327h-2.328v-2.327Zm6.983 0h2.328v2.327h-2.328v-2.327Zm4.655 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327H38.93v-2.327Zm6.983 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327H48.24v-2.327Zm2.328 0h2.327v2.327H50.57v-2.327Zm6.982 0h2.328v2.327h-2.328v-2.327Zm4.656 0h2.327v2.327h-2.327v-2.327Zm4.655 0h2.327v2.327h-2.327v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327Zm2.328 0h2.328v2.327h-2.328v-2.327Zm6.983 0h2.327v2.327H78.5v-2.327Zm2.327 0h2.328v2.327h-2.328v-2.327ZM11 85.482h2.328v2.328H11v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328H20.31v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm6.983 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328H38.93v-2.328Zm2.328 0h2.327v2.328h-2.328v-2.328Zm9.31 0h2.327v2.328H50.57v-2.328Zm16.293 0h2.327v2.328h-2.327v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm2.328 0h2.328v2.328h-2.328v-2.328Zm4.655 0H78.5v2.328h-2.328v-2.328Zm2.328 0h2.327v2.328H78.5v-2.328Zm2.327 0h2.328v2.328h-2.328v-2.328Zm4.655 0h2.328v2.328h-2.328v-2.328Z" fill="#000"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h98v98H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mobile-download-qr-new-user.svg b/browser/components/newtab/data/content/assets/mobile-download-qr-new-user.svg
new file mode 100644
index 0000000000..9a8f61a95c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mobile-download-qr-new-user.svg
@@ -0,0 +1,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/. -->
+<svg width="98" height="98" viewBox="0 0 98 98" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="98" height="98" rx="8" fill="white"/>
+<path d="M10.5945 10.5947H13.2431V13.2434H10.5945V10.5947ZM13.2431 10.5947H15.8918V13.2434H13.2431V10.5947ZM15.8918 10.5947H18.5404V13.2434H15.8918V10.5947ZM18.5404 10.5947H21.1891V13.2434H18.5404V10.5947ZM21.1891 10.5947H23.8377V13.2434H21.1891V10.5947ZM23.8377 10.5947H26.4864V13.2434H23.8377V10.5947ZM26.4864 10.5947H29.135V13.2434H26.4864V10.5947ZM34.4323 10.5947H37.081V13.2434H34.4323V10.5947ZM42.3783 10.5947H45.0269V13.2434H42.3783V10.5947ZM45.0269 10.5947H47.6756V13.2434H45.0269V10.5947ZM50.3242 10.5947H52.9729V13.2434H50.3242V10.5947ZM52.9729 10.5947H55.6215V13.2434H52.9729V10.5947ZM58.2702 10.5947H60.9188V13.2434H58.2702V10.5947ZM60.9188 10.5947H63.5675V13.2434H60.9188V10.5947ZM68.8648 10.5947H71.5134V13.2434H68.8648V10.5947ZM71.5134 10.5947H74.1621V13.2434H71.5134V10.5947ZM74.1621 10.5947H76.8107V13.2434H74.1621V10.5947ZM76.8107 10.5947H79.4593V13.2434H76.8107V10.5947ZM79.4593 10.5947H82.108V13.2434H79.4593V10.5947ZM82.108 10.5947H84.7566V13.2434H82.108V10.5947ZM84.7566 10.5947H87.4053V13.2434H84.7566V10.5947ZM10.5945 13.2434H13.2431V15.892H10.5945V13.2434ZM26.4864 13.2434H29.135V15.892H26.4864V13.2434ZM37.081 13.2434H39.7296V15.892H37.081V13.2434ZM39.7296 13.2434H42.3783V15.892H39.7296V13.2434ZM45.0269 13.2434H47.6756V15.892H45.0269V13.2434ZM47.6756 13.2434H50.3242V15.892H47.6756V13.2434ZM50.3242 13.2434H52.9729V15.892H50.3242V13.2434ZM63.5675 13.2434H66.2161V15.892H63.5675V13.2434ZM68.8648 13.2434H71.5134V15.892H68.8648V13.2434ZM84.7566 13.2434H87.4053V15.892H84.7566V13.2434ZM10.5945 15.892H13.2431V18.5407H10.5945V15.892ZM15.8918 15.892H18.5404V18.5407H15.8918V15.892ZM18.5404 15.892H21.1891V18.5407H18.5404V15.892ZM21.1891 15.892H23.8377V18.5407H21.1891V15.892ZM26.4864 15.892H29.135V18.5407H26.4864V15.892ZM31.7837 15.892H34.4323V18.5407H31.7837V15.892ZM34.4323 15.892H37.081V18.5407H34.4323V15.892ZM37.081 15.892H39.7296V18.5407H37.081V15.892ZM45.0269 15.892H47.6756V18.5407H45.0269V15.892ZM50.3242 15.892H52.9729V18.5407H50.3242V15.892ZM58.2702 15.892H60.9188V18.5407H58.2702V15.892ZM63.5675 15.892H66.2161V18.5407H63.5675V15.892ZM68.8648 15.892H71.5134V18.5407H68.8648V15.892ZM74.1621 15.892H76.8107V18.5407H74.1621V15.892ZM76.8107 15.892H79.4593V18.5407H76.8107V15.892ZM79.4593 15.892H82.108V18.5407H79.4593V15.892ZM84.7566 15.892H87.4053V18.5407H84.7566V15.892ZM10.5945 18.5407H13.2431V21.1893H10.5945V18.5407ZM15.8918 18.5407H18.5404V21.1893H15.8918V18.5407ZM18.5404 18.5407H21.1891V21.1893H18.5404V18.5407ZM21.1891 18.5407H23.8377V21.1893H21.1891V18.5407ZM26.4864 18.5407H29.135V21.1893H26.4864V18.5407ZM31.7837 18.5407H34.4323V21.1893H31.7837V18.5407ZM34.4323 18.5407H37.081V21.1893H34.4323V18.5407ZM37.081 18.5407H39.7296V21.1893H37.081V18.5407ZM42.3783 18.5407H45.0269V21.1893H42.3783V18.5407ZM45.0269 18.5407H47.6756V21.1893H45.0269V18.5407ZM50.3242 18.5407H52.9729V21.1893H50.3242V18.5407ZM55.6215 18.5407H58.2702V21.1893H55.6215V18.5407ZM58.2702 18.5407H60.9188V21.1893H58.2702V18.5407ZM60.9188 18.5407H63.5675V21.1893H60.9188V18.5407ZM63.5675 18.5407H66.2161V21.1893H63.5675V18.5407ZM68.8648 18.5407H71.5134V21.1893H68.8648V18.5407ZM74.1621 18.5407H76.8107V21.1893H74.1621V18.5407ZM76.8107 18.5407H79.4593V21.1893H76.8107V18.5407ZM79.4593 18.5407H82.108V21.1893H79.4593V18.5407ZM84.7566 18.5407H87.4053V21.1893H84.7566V18.5407ZM10.5945 21.1893H13.2431V23.838H10.5945V21.1893ZM15.8918 21.1893H18.5404V23.838H15.8918V21.1893ZM18.5404 21.1893H21.1891V23.838H18.5404V21.1893ZM21.1891 21.1893H23.8377V23.838H21.1891V21.1893ZM26.4864 21.1893H29.135V23.838H26.4864V21.1893ZM42.3783 21.1893H45.0269V23.838H42.3783V21.1893ZM45.0269 21.1893H47.6756V23.838H45.0269V21.1893ZM47.6756 21.1893H50.3242V23.838H47.6756V21.1893ZM52.9729 21.1893H55.6215V23.838H52.9729V21.1893ZM55.6215 21.1893H58.2702V23.838H55.6215V21.1893ZM58.2702 21.1893H60.9188V23.838H58.2702V21.1893ZM60.9188 21.1893H63.5675V23.838H60.9188V21.1893ZM68.8648 21.1893H71.5134V23.838H68.8648V21.1893ZM74.1621 21.1893H76.8107V23.838H74.1621V21.1893ZM76.8107 21.1893H79.4593V23.838H76.8107V21.1893ZM79.4593 21.1893H82.108V23.838H79.4593V21.1893ZM84.7566 21.1893H87.4053V23.838H84.7566V21.1893ZM10.5945 23.838H13.2431V26.4866H10.5945V23.838ZM26.4864 23.838H29.135V26.4866H26.4864V23.838ZM50.3242 23.838H52.9729V26.4866H50.3242V23.838ZM52.9729 23.838H55.6215V26.4866H52.9729V23.838ZM55.6215 23.838H58.2702V26.4866H55.6215V23.838ZM58.2702 23.838H60.9188V26.4866H58.2702V23.838ZM68.8648 23.838H71.5134V26.4866H68.8648V23.838ZM84.7566 23.838H87.4053V26.4866H84.7566V23.838ZM10.5945 26.4866H13.2431V29.1353H10.5945V26.4866ZM13.2431 26.4866H15.8918V29.1353H13.2431V26.4866ZM15.8918 26.4866H18.5404V29.1353H15.8918V26.4866ZM18.5404 26.4866H21.1891V29.1353H18.5404V26.4866ZM21.1891 26.4866H23.8377V29.1353H21.1891V26.4866ZM23.8377 26.4866H26.4864V29.1353H23.8377V26.4866ZM26.4864 26.4866H29.135V29.1353H26.4864V26.4866ZM31.7837 26.4866H34.4323V29.1353H31.7837V26.4866ZM37.081 26.4866H39.7296V29.1353H37.081V26.4866ZM42.3783 26.4866H45.0269V29.1353H42.3783V26.4866ZM47.6756 26.4866H50.3242V29.1353H47.6756V26.4866ZM52.9729 26.4866H55.6215V29.1353H52.9729V26.4866ZM58.2702 26.4866H60.9188V29.1353H58.2702V26.4866ZM63.5675 26.4866H66.2161V29.1353H63.5675V26.4866ZM68.8648 26.4866H71.5134V29.1353H68.8648V26.4866ZM71.5134 26.4866H74.1621V29.1353H71.5134V26.4866ZM74.1621 26.4866H76.8107V29.1353H74.1621V26.4866ZM76.8107 26.4866H79.4593V29.1353H76.8107V26.4866ZM79.4593 26.4866H82.108V29.1353H79.4593V26.4866ZM82.108 26.4866H84.7566V29.1353H82.108V26.4866ZM84.7566 26.4866H87.4053V29.1353H84.7566V26.4866ZM37.081 29.1353H39.7296V31.7839H37.081V29.1353ZM39.7296 29.1353H42.3783V31.7839H39.7296V29.1353ZM42.3783 29.1353H45.0269V31.7839H42.3783V29.1353ZM52.9729 29.1353H55.6215V31.7839H52.9729V29.1353ZM63.5675 29.1353H66.2161V31.7839H63.5675V29.1353ZM18.5404 31.7839H21.1891V34.4326H18.5404V31.7839ZM21.1891 31.7839H23.8377V34.4326H21.1891V31.7839ZM26.4864 31.7839H29.135V34.4326H26.4864V31.7839ZM29.135 31.7839H31.7837V34.4326H29.135V31.7839ZM34.4323 31.7839H37.081V34.4326H34.4323V31.7839ZM37.081 31.7839H39.7296V34.4326H37.081V31.7839ZM39.7296 31.7839H42.3783V34.4326H39.7296V31.7839ZM58.2702 31.7839H60.9188V34.4326H58.2702V31.7839ZM76.8107 31.7839H79.4593V34.4326H76.8107V31.7839ZM79.4593 31.7839H82.108V34.4326H79.4593V31.7839ZM10.5945 34.4326H13.2431V37.0812H10.5945V34.4326ZM13.2431 34.4326H15.8918V37.0812H13.2431V34.4326ZM21.1891 34.4326H23.8377V37.0812H21.1891V34.4326ZM23.8377 34.4326H26.4864V37.0812H23.8377V34.4326ZM37.081 34.4326H39.7296V37.0812H37.081V34.4326ZM39.7296 34.4326H42.3783V37.0812H39.7296V34.4326ZM47.6756 34.4326H50.3242V37.0812H47.6756V34.4326ZM63.5675 34.4326H66.2161V37.0812H63.5675V34.4326ZM71.5134 34.4326H74.1621V37.0812H71.5134V34.4326ZM74.1621 34.4326H76.8107V37.0812H74.1621V34.4326ZM79.4593 34.4326H82.108V37.0812H79.4593V34.4326ZM82.108 34.4326H84.7566V37.0812H82.108V34.4326ZM13.2431 37.0812H15.8918V39.7299H13.2431V37.0812ZM15.8918 37.0812H18.5404V39.7299H15.8918V37.0812ZM18.5404 37.0812H21.1891V39.7299H18.5404V37.0812ZM26.4864 37.0812H29.135V39.7299H26.4864V37.0812ZM29.135 37.0812H31.7837V39.7299H29.135V37.0812ZM31.7837 37.0812H34.4323V39.7299H31.7837V37.0812ZM34.4323 37.0812H37.081V39.7299H34.4323V37.0812ZM37.081 37.0812H39.7296V39.7299H37.081V37.0812ZM39.7296 37.0812H42.3783V39.7299H39.7296V37.0812ZM45.0269 37.0812H47.6756V39.7299H45.0269V37.0812ZM50.3242 37.0812H52.9729V39.7299H50.3242V37.0812ZM55.6215 37.0812H58.2702V39.7299H55.6215V37.0812ZM66.2161 37.0812H68.8648V39.7299H66.2161V37.0812ZM68.8648 37.0812H71.5134V39.7299H68.8648V37.0812ZM74.1621 37.0812H76.8107V39.7299H74.1621V37.0812ZM76.8107 37.0812H79.4593V39.7299H76.8107V37.0812ZM79.4593 37.0812H82.108V39.7299H79.4593V37.0812ZM15.8918 39.7299H18.5404V42.3785H15.8918V39.7299ZM21.1891 39.7299H23.8377V42.3785H21.1891V39.7299ZM31.7837 39.7299H34.4323V42.3785H31.7837V39.7299ZM34.4323 39.7299H37.081V42.3785H34.4323V39.7299ZM37.081 39.7299H39.7296V42.3785H37.081V39.7299ZM39.7296 39.7299H42.3783V42.3785H39.7296V39.7299ZM42.3783 39.7299H45.0269V42.3785H42.3783V39.7299ZM47.6756 39.7299H50.3242V42.3785H47.6756V39.7299ZM55.6215 39.7299H58.2702V42.3785H55.6215V39.7299ZM60.9188 39.7299H63.5675V42.3785H60.9188V39.7299ZM63.5675 39.7299H66.2161V42.3785H63.5675V39.7299ZM71.5134 39.7299H74.1621V42.3785H71.5134V39.7299ZM74.1621 39.7299H76.8107V42.3785H74.1621V39.7299ZM84.7566 39.7299H87.4053V42.3785H84.7566V39.7299ZM13.2431 42.3785H15.8918V45.0272H13.2431V42.3785ZM15.8918 42.3785H18.5404V45.0272H15.8918V42.3785ZM18.5404 42.3785H21.1891V45.0272H18.5404V42.3785ZM26.4864 42.3785H29.135V45.0272H26.4864V42.3785ZM29.135 42.3785H31.7837V45.0272H29.135V42.3785ZM31.7837 42.3785H34.4323V45.0272H31.7837V42.3785ZM34.4323 42.3785H37.081V45.0272H34.4323V42.3785ZM37.081 42.3785H39.7296V45.0272H37.081V42.3785ZM42.3783 42.3785H45.0269V45.0272H42.3783V42.3785ZM45.0269 42.3785H47.6756V45.0272H45.0269V42.3785ZM47.6756 42.3785H50.3242V45.0272H47.6756V42.3785ZM52.9729 42.3785H55.6215V45.0272H52.9729V42.3785ZM66.2161 42.3785H68.8648V45.0272H66.2161V42.3785ZM68.8648 42.3785H71.5134V45.0272H68.8648V42.3785ZM76.8107 42.3785H79.4593V45.0272H76.8107V42.3785ZM82.108 42.3785H84.7566V45.0272H82.108V42.3785ZM13.2431 45.0272H15.8918V47.6758H13.2431V45.0272ZM15.8918 45.0272H18.5404V47.6758H15.8918V45.0272ZM18.5404 45.0272H21.1891V47.6758H18.5404V45.0272ZM23.8377 45.0272H26.4864V47.6758H23.8377V45.0272ZM29.135 45.0272H31.7837V47.6758H29.135V45.0272ZM31.7837 45.0272H34.4323V47.6758H31.7837V45.0272ZM34.4323 45.0272H37.081V47.6758H34.4323V45.0272ZM50.3242 45.0272H52.9729V47.6758H50.3242V45.0272ZM55.6215 45.0272H58.2702V47.6758H55.6215V45.0272ZM58.2702 45.0272H60.9188V47.6758H58.2702V45.0272ZM68.8648 45.0272H71.5134V47.6758H68.8648V45.0272ZM74.1621 45.0272H76.8107V47.6758H74.1621V45.0272ZM79.4593 45.0272H82.108V47.6758H79.4593V45.0272ZM84.7566 45.0272H87.4053V47.6758H84.7566V45.0272ZM10.5945 47.6758H13.2431V50.3245H10.5945V47.6758ZM13.2431 47.6758H15.8918V50.3245H13.2431V47.6758ZM18.5404 47.6758H21.1891V50.3245H18.5404V47.6758ZM21.1891 47.6758H23.8377V50.3245H21.1891V47.6758ZM26.4864 47.6758H29.135V50.3245H26.4864V47.6758ZM31.7837 47.6758H34.4323V50.3245H31.7837V47.6758ZM37.081 47.6758H39.7296V50.3245H37.081V47.6758ZM39.7296 47.6758H42.3783V50.3245H39.7296V47.6758ZM50.3242 47.6758H52.9729V50.3245H50.3242V47.6758ZM52.9729 47.6758H55.6215V50.3245H52.9729V47.6758ZM55.6215 47.6758H58.2702V50.3245H55.6215V47.6758ZM60.9188 47.6758H63.5675V50.3245H60.9188V47.6758ZM63.5675 47.6758H66.2161V50.3245H63.5675V47.6758ZM71.5134 47.6758H74.1621V50.3245H71.5134V47.6758ZM76.8107 47.6758H79.4593V50.3245H76.8107V47.6758ZM84.7566 47.6758H87.4053V50.3245H84.7566V47.6758ZM13.2431 50.3245H15.8918V52.9731H13.2431V50.3245ZM21.1891 50.3245H23.8377V52.9731H21.1891V50.3245ZM23.8377 50.3245H26.4864V52.9731H23.8377V50.3245ZM29.135 50.3245H31.7837V52.9731H29.135V50.3245ZM34.4323 50.3245H37.081V52.9731H34.4323V50.3245ZM39.7296 50.3245H42.3783V52.9731H39.7296V50.3245ZM42.3783 50.3245H45.0269V52.9731H42.3783V50.3245ZM47.6756 50.3245H50.3242V52.9731H47.6756V50.3245ZM58.2702 50.3245H60.9188V52.9731H58.2702V50.3245ZM66.2161 50.3245H68.8648V52.9731H66.2161V50.3245ZM68.8648 50.3245H71.5134V52.9731H68.8648V50.3245ZM74.1621 50.3245H76.8107V52.9731H74.1621V50.3245ZM76.8107 50.3245H79.4593V52.9731H76.8107V50.3245ZM79.4593 50.3245H82.108V52.9731H79.4593V50.3245ZM84.7566 50.3245H87.4053V52.9731H84.7566V50.3245ZM13.2431 52.9731H15.8918V55.6218H13.2431V52.9731ZM15.8918 52.9731H18.5404V55.6218H15.8918V52.9731ZM18.5404 52.9731H21.1891V55.6218H18.5404V52.9731ZM21.1891 52.9731H23.8377V55.6218H21.1891V52.9731ZM23.8377 52.9731H26.4864V55.6218H23.8377V52.9731ZM26.4864 52.9731H29.135V55.6218H26.4864V52.9731ZM29.135 52.9731H31.7837V55.6218H29.135V52.9731ZM34.4323 52.9731H37.081V55.6218H34.4323V52.9731ZM39.7296 52.9731H42.3783V55.6218H39.7296V52.9731ZM42.3783 52.9731H45.0269V55.6218H42.3783V52.9731ZM50.3242 52.9731H52.9729V55.6218H50.3242V52.9731ZM55.6215 52.9731H58.2702V55.6218H55.6215V52.9731ZM60.9188 52.9731H63.5675V55.6218H60.9188V52.9731ZM63.5675 52.9731H66.2161V55.6218H63.5675V52.9731ZM76.8107 52.9731H79.4593V55.6218H76.8107V52.9731ZM84.7566 52.9731H87.4053V55.6218H84.7566V52.9731ZM10.5945 55.6218H13.2431V58.2704H10.5945V55.6218ZM18.5404 55.6218H21.1891V58.2704H18.5404V55.6218ZM21.1891 55.6218H23.8377V58.2704H21.1891V55.6218ZM31.7837 55.6218H34.4323V58.2704H31.7837V55.6218ZM34.4323 55.6218H37.081V58.2704H34.4323V55.6218ZM39.7296 55.6218H42.3783V58.2704H39.7296V55.6218ZM47.6756 55.6218H50.3242V58.2704H47.6756V55.6218ZM50.3242 55.6218H52.9729V58.2704H50.3242V55.6218ZM52.9729 55.6218H55.6215V58.2704H52.9729V55.6218ZM55.6215 55.6218H58.2702V58.2704H55.6215V55.6218ZM63.5675 55.6218H66.2161V58.2704H63.5675V55.6218ZM68.8648 55.6218H71.5134V58.2704H68.8648V55.6218ZM74.1621 55.6218H76.8107V58.2704H74.1621V55.6218ZM76.8107 55.6218H79.4593V58.2704H76.8107V55.6218ZM79.4593 55.6218H82.108V58.2704H79.4593V55.6218ZM10.5945 58.2704H13.2431V60.9191H10.5945V58.2704ZM13.2431 58.2704H15.8918V60.9191H13.2431V58.2704ZM21.1891 58.2704H23.8377V60.9191H21.1891V58.2704ZM26.4864 58.2704H29.135V60.9191H26.4864V58.2704ZM29.135 58.2704H31.7837V60.9191H29.135V58.2704ZM42.3783 58.2704H45.0269V60.9191H42.3783V58.2704ZM45.0269 58.2704H47.6756V60.9191H45.0269V58.2704ZM47.6756 58.2704H50.3242V60.9191H47.6756V58.2704ZM52.9729 58.2704H55.6215V60.9191H52.9729V58.2704ZM55.6215 58.2704H58.2702V60.9191H55.6215V58.2704ZM58.2702 58.2704H60.9188V60.9191H58.2702V58.2704ZM60.9188 58.2704H63.5675V60.9191H60.9188V58.2704ZM71.5134 58.2704H74.1621V60.9191H71.5134V58.2704ZM84.7566 58.2704H87.4053V60.9191H84.7566V58.2704ZM10.5945 60.9191H13.2431V63.5677H10.5945V60.9191ZM13.2431 60.9191H15.8918V63.5677H13.2431V60.9191ZM23.8377 60.9191H26.4864V63.5677H23.8377V60.9191ZM31.7837 60.9191H34.4323V63.5677H31.7837V60.9191ZM42.3783 60.9191H45.0269V63.5677H42.3783V60.9191ZM47.6756 60.9191H50.3242V63.5677H47.6756V60.9191ZM52.9729 60.9191H55.6215V63.5677H52.9729V60.9191ZM58.2702 60.9191H60.9188V63.5677H58.2702V60.9191ZM60.9188 60.9191H63.5675V63.5677H60.9188V60.9191ZM63.5675 60.9191H66.2161V63.5677H63.5675V60.9191ZM66.2161 60.9191H68.8648V63.5677H66.2161V60.9191ZM68.8648 60.9191H71.5134V63.5677H68.8648V60.9191ZM76.8107 60.9191H79.4593V63.5677H76.8107V60.9191ZM79.4593 60.9191H82.108V63.5677H79.4593V60.9191ZM84.7566 60.9191H87.4053V63.5677H84.7566V60.9191ZM10.5945 63.5677H13.2431V66.2164H10.5945V63.5677ZM13.2431 63.5677H15.8918V66.2164H13.2431V63.5677ZM15.8918 63.5677H18.5404V66.2164H15.8918V63.5677ZM18.5404 63.5677H21.1891V66.2164H18.5404V63.5677ZM23.8377 63.5677H26.4864V66.2164H23.8377V63.5677ZM26.4864 63.5677H29.135V66.2164H26.4864V63.5677ZM29.135 63.5677H31.7837V66.2164H29.135V63.5677ZM31.7837 63.5677H34.4323V66.2164H31.7837V63.5677ZM37.081 63.5677H39.7296V66.2164H37.081V63.5677ZM45.0269 63.5677H47.6756V66.2164H45.0269V63.5677ZM50.3242 63.5677H52.9729V66.2164H50.3242V63.5677ZM52.9729 63.5677H55.6215V66.2164H52.9729V63.5677ZM55.6215 63.5677H58.2702V66.2164H55.6215V63.5677ZM58.2702 63.5677H60.9188V66.2164H58.2702V63.5677ZM60.9188 63.5677H63.5675V66.2164H60.9188V63.5677ZM63.5675 63.5677H66.2161V66.2164H63.5675V63.5677ZM66.2161 63.5677H68.8648V66.2164H66.2161V63.5677ZM68.8648 63.5677H71.5134V66.2164H68.8648V63.5677ZM71.5134 63.5677H74.1621V66.2164H71.5134V63.5677ZM74.1621 63.5677H76.8107V66.2164H74.1621V63.5677ZM79.4593 63.5677H82.108V66.2164H79.4593V63.5677ZM84.7566 63.5677H87.4053V66.2164H84.7566V63.5677ZM31.7837 66.2164H34.4323V68.865H31.7837V66.2164ZM47.6756 66.2164H50.3242V68.865H47.6756V66.2164ZM50.3242 66.2164H52.9729V68.865H50.3242V66.2164ZM58.2702 66.2164H60.9188V68.865H58.2702V66.2164ZM63.5675 66.2164H66.2161V68.865H63.5675V66.2164ZM74.1621 66.2164H76.8107V68.865H74.1621V66.2164ZM76.8107 66.2164H79.4593V68.865H76.8107V66.2164ZM79.4593 66.2164H82.108V68.865H79.4593V66.2164ZM10.5945 68.865H13.2431V71.5136H10.5945V68.865ZM13.2431 68.865H15.8918V71.5136H13.2431V68.865ZM15.8918 68.865H18.5404V71.5136H15.8918V68.865ZM18.5404 68.865H21.1891V71.5136H18.5404V68.865ZM21.1891 68.865H23.8377V71.5136H21.1891V68.865ZM23.8377 68.865H26.4864V71.5136H23.8377V68.865ZM26.4864 68.865H29.135V71.5136H26.4864V68.865ZM31.7837 68.865H34.4323V71.5136H31.7837V68.865ZM34.4323 68.865H37.081V71.5136H34.4323V68.865ZM37.081 68.865H39.7296V71.5136H37.081V68.865ZM47.6756 68.865H50.3242V71.5136H47.6756V68.865ZM52.9729 68.865H55.6215V71.5136H52.9729V68.865ZM60.9188 68.865H63.5675V71.5136H60.9188V68.865ZM63.5675 68.865H66.2161V71.5136H63.5675V68.865ZM68.8648 68.865H71.5134V71.5136H68.8648V68.865ZM74.1621 68.865H76.8107V71.5136H74.1621V68.865ZM79.4593 68.865H82.108V71.5136H79.4593V68.865ZM10.5945 71.5136H13.2431V74.1623H10.5945V71.5136ZM26.4864 71.5136H29.135V74.1623H26.4864V71.5136ZM42.3783 71.5136H45.0269V74.1623H42.3783V71.5136ZM50.3242 71.5136H52.9729V74.1623H50.3242V71.5136ZM58.2702 71.5136H60.9188V74.1623H58.2702V71.5136ZM60.9188 71.5136H63.5675V74.1623H60.9188V71.5136ZM63.5675 71.5136H66.2161V74.1623H63.5675V71.5136ZM74.1621 71.5136H76.8107V74.1623H74.1621V71.5136ZM76.8107 71.5136H79.4593V74.1623H76.8107V71.5136ZM10.5945 74.1623H13.2431V76.8109H10.5945V74.1623ZM15.8918 74.1623H18.5404V76.8109H15.8918V74.1623ZM18.5404 74.1623H21.1891V76.8109H18.5404V74.1623ZM21.1891 74.1623H23.8377V76.8109H21.1891V74.1623ZM26.4864 74.1623H29.135V76.8109H26.4864V74.1623ZM31.7837 74.1623H34.4323V76.8109H31.7837V74.1623ZM34.4323 74.1623H37.081V76.8109H34.4323V74.1623ZM37.081 74.1623H39.7296V76.8109H37.081V74.1623ZM39.7296 74.1623H42.3783V76.8109H39.7296V74.1623ZM52.9729 74.1623H55.6215V76.8109H52.9729V74.1623ZM55.6215 74.1623H58.2702V76.8109H55.6215V74.1623ZM60.9188 74.1623H63.5675V76.8109H60.9188V74.1623ZM63.5675 74.1623H66.2161V76.8109H63.5675V74.1623ZM66.2161 74.1623H68.8648V76.8109H66.2161V74.1623ZM68.8648 74.1623H71.5134V76.8109H68.8648V74.1623ZM71.5134 74.1623H74.1621V76.8109H71.5134V74.1623ZM74.1621 74.1623H76.8107V76.8109H74.1621V74.1623ZM10.5945 76.8109H13.2431V79.4596H10.5945V76.8109ZM15.8918 76.8109H18.5404V79.4596H15.8918V76.8109ZM18.5404 76.8109H21.1891V79.4596H18.5404V76.8109ZM21.1891 76.8109H23.8377V79.4596H21.1891V76.8109ZM26.4864 76.8109H29.135V79.4596H26.4864V76.8109ZM31.7837 76.8109H34.4323V79.4596H31.7837V76.8109ZM39.7296 76.8109H42.3783V79.4596H39.7296V76.8109ZM52.9729 76.8109H55.6215V79.4596H52.9729V76.8109ZM55.6215 76.8109H58.2702V79.4596H55.6215V76.8109ZM71.5134 76.8109H74.1621V79.4596H71.5134V76.8109ZM76.8107 76.8109H79.4593V79.4596H76.8107V76.8109ZM79.4593 76.8109H82.108V79.4596H79.4593V76.8109ZM82.108 76.8109H84.7566V79.4596H82.108V76.8109ZM10.5945 79.4596H13.2431V82.1082H10.5945V79.4596ZM15.8918 79.4596H18.5404V82.1082H15.8918V79.4596ZM18.5404 79.4596H21.1891V82.1082H18.5404V79.4596ZM21.1891 79.4596H23.8377V82.1082H21.1891V79.4596ZM26.4864 79.4596H29.135V82.1082H26.4864V79.4596ZM37.081 79.4596H39.7296V82.1082H37.081V79.4596ZM45.0269 79.4596H47.6756V82.1082H45.0269V79.4596ZM47.6756 79.4596H50.3242V82.1082H47.6756V79.4596ZM52.9729 79.4596H55.6215V82.1082H52.9729V79.4596ZM63.5675 79.4596H66.2161V82.1082H63.5675V79.4596ZM66.2161 79.4596H68.8648V82.1082H66.2161V79.4596ZM71.5134 79.4596H74.1621V82.1082H71.5134V79.4596ZM74.1621 79.4596H76.8107V82.1082H74.1621V79.4596ZM79.4593 79.4596H82.108V82.1082H79.4593V79.4596ZM82.108 79.4596H84.7566V82.1082H82.108V79.4596ZM84.7566 79.4596H87.4053V82.1082H84.7566V79.4596ZM10.5945 82.1082H13.2431V84.7569H10.5945V82.1082ZM26.4864 82.1082H29.135V84.7569H26.4864V82.1082ZM39.7296 82.1082H42.3783V84.7569H39.7296V82.1082ZM42.3783 82.1082H45.0269V84.7569H42.3783V82.1082ZM50.3242 82.1082H52.9729V84.7569H50.3242V82.1082ZM52.9729 82.1082H55.6215V84.7569H52.9729V82.1082ZM55.6215 82.1082H58.2702V84.7569H55.6215V82.1082ZM63.5675 82.1082H66.2161V84.7569H63.5675V82.1082ZM66.2161 82.1082H68.8648V84.7569H66.2161V82.1082ZM74.1621 82.1082H76.8107V84.7569H74.1621V82.1082ZM76.8107 82.1082H79.4593V84.7569H76.8107V82.1082ZM79.4593 82.1082H82.108V84.7569H79.4593V82.1082ZM84.7566 82.1082H87.4053V84.7569H84.7566V82.1082ZM10.5945 84.7569H13.2431V87.4055H10.5945V84.7569ZM13.2431 84.7569H15.8918V87.4055H13.2431V84.7569ZM15.8918 84.7569H18.5404V87.4055H15.8918V84.7569ZM18.5404 84.7569H21.1891V87.4055H18.5404V84.7569ZM21.1891 84.7569H23.8377V87.4055H21.1891V84.7569ZM23.8377 84.7569H26.4864V87.4055H23.8377V84.7569ZM26.4864 84.7569H29.135V87.4055H26.4864V84.7569ZM37.081 84.7569H39.7296V87.4055H37.081V84.7569ZM42.3783 84.7569H45.0269V87.4055H42.3783V84.7569ZM45.0269 84.7569H47.6756V87.4055H45.0269V84.7569ZM47.6756 84.7569H50.3242V87.4055H47.6756V84.7569ZM52.9729 84.7569H55.6215V87.4055H52.9729V84.7569ZM55.6215 84.7569H58.2702V87.4055H55.6215V84.7569ZM58.2702 84.7569H60.9188V87.4055H58.2702V84.7569ZM60.9188 84.7569H63.5675V87.4055H60.9188V84.7569ZM63.5675 84.7569H66.2161V87.4055H63.5675V84.7569ZM68.8648 84.7569H71.5134V87.4055H68.8648V84.7569ZM71.5134 84.7569H74.1621V87.4055H71.5134V84.7569ZM74.1621 84.7569H76.8107V87.4055H74.1621V84.7569ZM76.8107 84.7569H79.4593V87.4055H76.8107V84.7569Z" fill="black"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/mr-colorways.avif b/browser/components/newtab/data/content/assets/mr-colorways.avif
new file mode 100644
index 0000000000..5d2db17ceb
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-colorways.avif
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/mr-gratitude.svg b/browser/components/newtab/data/content/assets/mr-gratitude.svg
new file mode 100644
index 0000000000..f490d454c9
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-gratitude.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="365" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M298.245 44.383c-.198-6.014 0-12.09-.025-18.103 0-2.296-1.01-3.327-3.314-3.363-6.578-.025-13.168.036-19.771.036-8.081 0-16.174-.06-24.255-.06s-15.472-.173-23.171-.087c-8.278.062-16.543-.11-24.797 0-5.247.062-10.47.025-15.718-.024-4.41-.062-8.82-.062-13.23.049-3.93.122-7.884-.197-11.813-.221-5.457-.025-10.927.086-16.408.061-7.663 0-15.325-.147-22.987-.086-9.473.05-18.933.11-28.394.05-10.125-.062-20.423.048-30.623-.038 4.656.921 9.017 2.91 13.353 2.983 2.944.025 5.95.282 9.042-.417 1.712-.393 4.04.27 6.122.392 3.338.197 6.689.025 10.027-.282 2.131-.196 3.474.982 4.102 3.277.271 1.031 1.06 1.902 2.131 2.492 1.121.613 2.156 1.313 3.289 1.976.776.478 1.207 1.215 1.368 2.11.653 3.265 1.379 3.965 4.779 3.94 2.525-.024 5.051-.171 7.527.418 3.055.736 6.06 1.657 7.908 4.54.85 1.314 1.183 2.652.481 4.137-.641 1.375-2.021 1.46-3.289 1.546-3.302.221-6.615.221-9.904.528-7.194.724-14.376 1.375-21.57 2.074-6.984.7-13.981 1.142-20.941 1.817-.986.11-1.947.368-2.957.22-1.06-.134-1.65.369-1.761 1.768-.308-1.043-.505-1.4-1.515-1.46-3.29-.11-6.468.736-9.658 1.067-2.107.246-7.046.59-9.608 1.682.049 8.873.074 17.735.135 26.584.074 11.45.11 22.902.296 34.328 2.513-.785 9.288-2.589 11.924-2.332 3.597.393 7.021-.503 10.446-1.264 3.178-.724 5.642.651 8.08 2.16 1.27.81 2.501 1.731 3.487 2.958 1.293 1.657 3.227 1.264 4.78.565 1.872-.872 3.757-.921 5.666-.786.53 0 1.183.197 1.49.54 1.885 2.234 3.708 4.443 3.474 7.72-.221 3.253.85 4.198 4.053 4.345 3.93.135 7.798.332 11.062 3.154 1.934 1.657 1.934 3.498 1.367 5.572-.726 2.664-2.045 5.094-3.732 7.279-.813 1.067-2.181.785-3.252.92-1.294.172-2.636.258-3.819.7-1.515.564-2.045-.246-2.193-1.338-.899-6.358-6.233-8.788-11.505-7.757-1.355.282-2.279.025-3.178-.982-4.016-4.59-9.3-4.872-14.684-3.805-3.843.725-7.157.614-10.224-2.209-1.798-1.681-4.3-2.184-6.738-2.233-1.06-.037-6.184 0-6.295 2.147v.086c.012 1.031.025 2.05.025 3.081.086-1.645 4.816-1.215 5.284-2.16 1.121 1.288 2.809.81 4.189 1.374 1.995.81 3.486 2.32 5.334 3.326 3.055 1.682 6.454 1.093 9.632.896 2.895-.159 5.778.037 8.648.062 1.035 0 2.242 1.485 3.055 2.54 1.047 1.436 2.451 1.854 3.991 1.768 1.996-.086 3.88.307 5.753.699 3.4.7 4.41 3.449 4.582 6.444.111 2.405 1.602 2.516 3.289 2.455 4.127-.136 8.167-.835 12.319-.811 1.971 0 3.572 1.154 5.371.872 1.404-.197 2.217.699 3.116 1.227 1.096.7 2.378 1.51 3.388 1.768 1.687.417 1.909 1.755 2.845 2.602 1.996 1.816 1.06 7.584-1.182 8.677-1.577.785-3.376 1.313-5.002 1.288-3.252-.085-6.344.921-9.571 1.031-3.425.111-6.824.651-10.224 1.068-6.258.749-12.577.724-18.835 1.534-3.29.418-6.627.54-9.941.761-4.275.307-8.487.749-12.725 1.203-3.277.356-12.799.319-12.799.319s0 .233.05 4.185c.036 4.615-.087 9.267-.087 13.882-.025 4.651.086 9.291.037 13.942-.037 4.308.591 8.591.283 12.899l7.995-.245c1.996-.626 3.991-1.129 6.036-1.657.591-.172 2.058-3.277 2.058-3.277l11.286-3.694h36.053c-2.279 0 6.96.994 7.527 0 2.697-4.701 5.925-8.898 10.273-12.286 1.429-1.117 2.833-2.798 4.262-3.719 2.304-1.46 4.694-2.908 7.194-4.148 5.987-2.958 12.269-4.787 18.897-5.486 6.824-.7 13.649-1.448 20.584-.749 5.531.552 10.224 3.044 14.905 5.646 7.354 4.087 12.897 10.138 18.034 16.655 1.454 1.902.801 5.854 2.71 7.781l15.047-7.781h43.897l13.957 5.511s1.293-.037 1.293-.025l1.688-.049c.419-3.952-.062-7.867.135-11.819.148-2.578.111-5.143.148-7.745.074-4.197-.456-8.407-.123-12.605.283-3.129.172-6.296.172-9.426 0-4.013-.049-8.026-.074-12.027-1.712-1.363-6.183-1.805-7.649-1.89-3.314-.16-6.394-1.203-9.547-2.124-4.829-1.374-9.83-1.423-14.77-1.878-3.757-.331-7.489.234-11.259.43-3.314.196-6.652-.319-9.904-1.092-3.375-.823-6.775-1.633-10.089-2.639-6.085-1.903-7.354-7.168-5.974-12.2.246-.957.838-1.767 1.737-2.381 2.722-1.816 5.814-2.798 9.017-2.798 6.147 0 11.345-2.099 15.496-6.554 4.041-4.308 9.178-5.953 14.832-6.321 3.141-.196 5.642-1.51 7.711-3.719 3.88-4.087 8.734-6.222 14.265-6.775 1.072-.11 5.531-1.399 6.233-.454 0-7.977-.074-15.955.037-23.92.111-8.432-.037-16.852.16-25.284.111-5.142.037-10.346-.135-15.562Zm-45.381 25.835c-1.232 1.853-3.696 2.406-5.692 1.657-1.01-.393-1.995-.147-2.981 0-7.021.982-13.956 2.32-21.003 3.13-12.244 1.374-24.513 1.816-36.807 2.05-3.967.073-7.921.466-11.875.27-3.769-.16-7.527-.614-11.296-1.032-2.858-.306-4.829-2.43-4.767-5.375.246-2.455 2.377-3.805 4.681-4.922 3.621-1.792 7.563-1.792 11.493-2.16 2.772-.245 5.494-.638 8.229-1.927 1.429-.675 3.387-.982 5.026-1.73 1.65-.786 3.141-1.768 4.483-3.081 3.006-2.946 6.578-5.069 10.619-6.1 1.49-.368 3.289-.037 4.94-.086 2.87-.086 4.939-1.988 7.391-3.031 3.363-1.363 6.504-1.817 9.854.257 2.329 1.4 3.647 3.302 4.657 5.658.677 1.56 1.934 2.345 3.843 2.013 3.314-.613 6.43-.196 9.239 1.903 1.158.896 2.673 1.227 3.535 2.65.234.344.173.565.259.847.37 1.179.172 2.381.641 3.584.85 2.185 1.01 2.43 3.35 1.755 2.267-.638 3.622.197 3.56 2.05-.024 1.031-.985 1.031-1.379 1.62Z" fill="url(#b)"/><path d="M58.285 61.355v-33.77h51.378l1.209 4.222 4.836 2.412 1.813 6.03 12.089.603 6.649 4.824v7.84l-23.574 1.809-30.827 2.412-18.133 1.809-5.44 1.809ZM159.228 67.385l10.88-4.221 15.112-2.412 16.32-9.649h7.858l6.044-4.22 7.858.602 6.649 7.84 12.694 2.412 4.835 9.045 4.836 1.206.605 4.824-4.836 3.015-4.836-.603-10.275 2.412-23.574 1.809-32.641 1.81-13.902-2.413-5.44-5.427 1.813-6.03ZM58.285 176.53v-41.005l-.605-18.693 6.65-1.206 12.693-2.412 7.858.603 6.648 6.03 9.067-1.809 4.232 4.824 1.813 7.236 9.067.603 6.649 6.03v4.824l-3.627 8.443 9.067 1.809 9.067 6.03 1.208 7.236-3.022 4.824-12.693 1.206-29.014 3.015-18.738 1.809-16.32.603ZM292.208 157.234l1.209-47.638h-10.88l-12.089 9.045h-12.089l-13.903 10.854-15.716 3.015-3.022 12.06 7.254 6.031 18.133 4.221 19.343-.603 21.76 3.015ZM133.237 200.651l-9.067 12.06 7.858 1.809 19.342 3.618 16.321 5.427 23.573.603 30.827-9.648-6.044-11.457-13.298-13.267-11.485-6.03-13.902-.603-16.32 1.206-15.112 6.03-12.693 10.252ZM223.905 349.595l-24.178-20.503-.605-1.809 19.343 6.031 15.111.603 14.507 1.206 1.209-6.634 12.089-8.442 7.253-5.427 6.649-9.045v12.06l-2.418 10.854-12.693 18.694 7.858 5.427-7.858 10.854 6.913 5.815-5.704 7.523h-31.287l-21.317 7.524 5.016-20.862 10.112-13.869Z" fill="#F8F6F4"/><path d="M221.645 332.437c6.19-.745 14.145 2.02 17.349 3.496l7.737-3.496 5.861-7.225 9.846-6.525 7.737-6.525 4.923-9.788-8.205-2.097-4.455-5.127-1.406-7.924-4.455-8.855h-5.861l-7.736 4.661-5.393 9.088h-7.971l-4.923 3.03c-.391-.466-1.547-1.725-3.048-3.03-1.875-1.631-7.268-3.728-9.143-4.894-1.876-1.165-10.785-.233-11.488 1.166-.703 1.398 1.641 11.418 3.517 13.982 1.5 2.051 2.032 9.244 2.11 12.584l-7.268 10.254c4.845 2.719 16.083 7.971 22.272 7.225Z" fill="url(#c)"/><path d="m277.677 314.958-2.579 10.254-4.923 3.728v5.826l-10.315 11.652 10.315 5.36-10.315 10.021 8.158 6.046-3.208 9.586c16.039 19.173 81.981-4.307 83.669-4.679 2.11-.467 9.144-9.322 11.722-12.818 2.579-3.495 4.689-15.613 4.689-19.109 0-3.495-5.861-10.253-9.377-22.138-2.814-9.508-15.552-17.478-21.569-20.275-6.487-1.087-21.804-3.262-31.181-3.262-9.378 0-21.725 4.505-26.727 6.758l1.641 13.05Z" fill="url(#d)"/><path d="M252.144 313.715c.248.189 1.109.16.656 1.355-.714 1.879-2.29 2.84-3.865 3.598-1.765.859-2.466 1.981-2.261 3.86.058.568.131 1.413-.19 1.69-.584.481-1.036 1.471-1.998 1.195-.992-.292-.963-1.18-1.109-2.069-.744-4.545 2.859-6.031 5.616-8.041.861-.627 1.561-1.632 3.151-1.574v-.014ZM223.509 321.653c3.778 0 6.637 1.006 8.606 3.963.423.626.73 1.253 0 1.865-.729.597-1.619.801-2.13-.073-1.167-1.967-3.019-1.982-4.886-1.938-1.43.044-2.743-.422-4.099-.714-.686-.145-1.124-.597-1.109-1.369 0-.758.554-1.224 1.138-1.34.948-.204 1.882-.729 2.523-.379l-.043-.015ZM256.724 294.91c.759-.452 1.109-.583 1.342-.816.599-.612 1.167-.379 1.736 0 .657.437.35.976.117 1.515-1.036 2.462-3.647 3.744-6.054 2.943-.714-.234-1.065-.86-.933-1.515.364-1.661.204-3.366.481-5.041.204-1.267.992-1.588 1.794-1.675.788-.073 1.197.772 1.372 1.529.189.874.816 1.676.145 3.06ZM210.395 302.529c-.978-.437-1.269-1.18-1.474-1.952-.175-.641-.16-1.239.54-1.661.759-.452 1.284-.073 1.663.451 1.298 1.778 2.436 3.657 3.195 5.74.335.932-.467 1.355-1.167 1.573-.934.292-3.924-.961-4.391-1.821-.802-1.471.583-1.719 1.634-2.33Z" fill="#000"/><path d="M362.469 333.206c-.467-1.18-.832-2.433-1.401-3.54-1.867-3.613-3.238-7.444-5.266-10.969-1.765-3.147-3.413-6.235-5.849-8.959-2.232-2.506-4.843-4.589-7.309-6.847-3.267-3.016-7.425-4.079-11.451-5.259-4.799-1.37-9.759-2.083-14.748-2.375-.612-.029-.977-.043-.933-.859.437-6.439.029-12.834-.467-19.244-.394-5.332-.292-10.707-.175-16.039.35-14.757 0-29.514.175-44.271.073-5.128.438-10.285 0-15.442a26.886 26.886 0 0 1 0-4.341c.248-2.972.117-5.944.175-8.887.102-4.647-.19-9.279-.044-13.941.146-5.201.117-10.43.146-15.66.029-5.551-.175-11.072-.073-16.593.146-6.949.073-13.897.073-20.846V95.461c0-7.837 0-15.66.029-23.468 0-11.931-.029-23.833.102-35.779.044-5.055-.102-10.139.03-15.194.116-5.113-.19-10.24-.365-15.369-.102-2.753-.715-3.54-3.37-4.006-2.217-.393-4.478-.743-6.739-.786-4.406-.117-8.796-.044-13.173-.044H268.73c-5.602 0-11.218-.117-16.819.044-3.37.072-6.74-.394-10.11-.102-3.005.276-5.995-.117-9 0-4.726.218-9.467-.277-14.208.043-1.794.117-3.545-.422-5.427-.102-2.377.365-4.886-.145-7.323.044-1.327.117-2.304-.67-3.617-.583-1.999.102-4.129.889-5.879.437-2.655-.684-5.208.248-7.863-.276-1.531-.292-3.442-.394-5.193-.248-.758.073-1.283.932-1.867.583-2.232-1.326-4.726.903-6.929-.54-.146-.101-.54 0-.642.146-.496.67-1.138.496-1.765.437-2.305-.189-4.624-.072-6.987-.437-1.999-.32-4.187.248-6.287-.116-2.626-.466-5.237.393-7.936 0-2.626-.364-5.354.043-8.067 0-2.217-.044-4.449.19-6.666-.03-2.218-.218-4.377.103-6.594.03-5.091-.19-10.182-.073-15.273-.073h-35.52c-11.729 0-23.428-.03-35.156.03-2.144 0-4.303.145-6.375-.045-3.15-.291-4.916.496-5.12 3.555-.248 3.394-.219 6.832-.219 10.212.03 8.697.073 17.38.146 26.047.044 6.992.073 14 .277 20.992.19 6.73.073 13.475.073 20.205v6.366c0 2.113.51 4.415-.117 6.308-.685 1.967 2.7 3.482.19 5.274 0 0 .03.145.044.145 1.225.32-.044 1.472.758 2.156.642.51-.89.437-.904 1.282-.044 1.282.744 2.506.175 3.788-.03.029.03.146.073.146 2.334.903-1.225 2.87.715 3.86a7.113 7.113 0 0 1-.467.219c-.219.102-.496.393-.321.466 1.036.495 1.328.888.044 1.471-.292.117-.03.423.19.466 1.006.248.758.539.043.889-.394.175-.35.568-.102.67 1.109.466.671 1.399.686 2.142.043 2.899-.03 5.797.029 8.696.146 8.668-.044 17.365.175 26.018.117 4.516.423 9.091.03 13.65-.22 2.608.101 5.274.145 7.925.117 8.202-.117 16.403.219 24.605.073 1.967.117 3.977-.03 5.914-.189 2.084.424 4.079.146 6.119-.247 1.748-.102 3.511-.102 5.23.044 3.263-.029 6.555.117 9.847.044.962.321 2.04-1.284 2.011-.248 0-.67.539-.744.903-.744 3.482-1.444 6.978-.904 10.562.54 3.438.642 6.948 1.94 10.212.715 1.748-.19 1.646-1.43 1.515-5.061-.539-9.89.539-14.602 2.287-2.465.903-4.697 2.331-7.074 3.219-3.618 1.297-6.667 2.972-9.147 6.046-1.356 1.69-.977 2.622-.073 4.079 2.553 4.006 5.894 7.269 9.57 10.168 4.011 3.19 7.79 6.701 12.764 8.493 1.619.612 3.165 1.398 4.77 2.083 2.8 1.209 2.728 1.18 2.626 4.152-.103 3.365.073 6.73-.073 10.095-.278 5.769-.22 11.509-.248 17.292-.03 3.511.19 7.022-.248 10.562-.248 1.835-.175 3.758-.073 5.652.102 1.763-.423 3.482-.175 5.274.102.786.364 1.908.043 2.505-1.137 1.938-.072 3.948-.393 5.915-.175 1.209.218 2.578 0 4.02-.248 1.676-.175 3.584-.103 5.332.22 4.56-1.283 9.061-.437 13.621.146.758-.321 1.107-1.153 1.078-.89 0-1.75-.422-2.552-.422-3.793 0-7.542-.904-11.262-.641-1.678.116-4.303-.641-5.354 2.301-.495 1.355-.758 2.55-.437 3.832.467 1.762.35 3.51.365 5.302.043 3.802-1.11 7.459-.934 11.29.219 4.589 2.655 6.556 7.06 6.556 1.75 0 3.516-.437 5.266-.437 8.082-.03 16.207-.073 24.288.116 3.414.102 6.74-.539 10.124-.51 2.772.029 5.485.568 8.286.568 36.337-.102 72.704-.072 109.041-.072h35.695c6.273 0 12.516 0 18.76-.03 7.104 0 14.208.073 21.312-.189 2.772-.102 5.529.189 8.315.189 24.886.03 49.758.03 74.615.03 3.661 0 7.323-.19 10.969.043 5.062.35 7.965-1.69 8.242-6.584.219-4.414.146-8.843.102-13.286 0-1.18-.072-2.579-.831-3.511-1.298-1.602-.423-2.331.861-3.045 2.144-1.136 3.792-2.971 5.091-4.807 1.765-2.506 3.734-4.865 5.266-7.56 1.765-3.074 3.267-6.235 4.128-9.601 1.619-6.162.759-12.251-1.605-18.122h-.014ZM36.717 2.752c1.298.889 2.61.467 3.865.496 3.88.116 7.775-.03 11.656.116 2.757.102 5.528.175 8.256.044 3.414-.175 6.885.757 10.299-.466.963-.35 2.013.582 3.165.568 2.976-.102 5.996.35 8.942-.044 2.232-.32 4.493-.029 6.754-.277 1.357-.145 3.122.35 4.727.292 5.485-.175 10.984-.044 16.469-.073 6.054-.03 12.122.102 18.161.146 11.51.102 23.019.029 34.514.029 15.901 0 31.815 0 47.716.029 7.775 0 15.535.218 23.281.073a550.52 550.52 0 0 1 13.873-.03c4.303.044 8.607-.101 12.91.073 4.77.19 9.584-.102 14.383-.043 4.405.029 8.796-.073 13.202.145 2.903.146 5.82-.174 8.752-.218 2.436-.03 4.945.029 7.323.218 1.473.117 3.37-.466 4.799.743.219.19.686.175.905-.218.423.437 1.531-.35 1.531.786 0 6.454 0 12.922-.072 19.39-.073 5.813-.001 11.64-.103 17.452-.043 2.622.292 5.347.219 7.954-.044 2.754-.044 5.521-.102 8.304-.073 4.56-.044 9.134-.102 13.722-.044 6.629-.35 13.257-.117 19.856.102 2.768-.146 5.522.073 8.318.321 4.007-.219 8.071-.116 12.135.145 7.342-.117 14.655.029 21.998.175 8.784-.146 17.583-.073 26.367.029 6.017.044 12.033.029 18.05-.044 5.419-.146 10.882-.175 16.301 0 6.235-.044 12.47.073 18.69.102 6.556.102 13.082-.029 19.637-.117 4.691-.102 9.411-.117 14.087-.029 3.438 0 6.92 0 10.358 0 4.953.029 9.892-.029 14.859 0 .903-.438 1.748-.467 2.695a135.496 135.496 0 0 0 .248 16.505c.102 1.049.146 2.083.89 3.074-1.838.685-3.472-.146-5.091-.32-3.414-.321-6.813-.19-10.197-.03-.788.03-1.079-.029-1.108-.786-.219-5.58-.861-11.174-.584-16.695.292-6.118.146-12.207.219-18.311.102-11.567.044-23.148.073-34.715 0-5.347.029-10.707.029-16.054 0-5.04-.277-10.066 0-15.077.219-4.123-.102-8.202-.044-12.296.044-3.86.292-7.706.292-11.566 0-6.192-.292-12.397-.175-18.618.102-5.259-.044-10.503.044-15.733.116-7.517.102-15.005.116-22.507.102-13.941.117-27.897.102-41.838 0-4.298.219-8.595.146-12.864-.073-4.938 0-9.847-.116-14.786-.117-5.477-.03-10.955-.073-16.447-.044-2.651-1.211-3.613-4.522-3.409-6.361.394-12.735.175-19.125.219-8.708.044-17.432.102-26.155 0-6.287-.102-12.589-.044-18.876-.146-5.66-.073-11.334-.117-16.994-.044-6.127.073-12.225-.247-18.322-.029-4.479.175-8.971-.102-13.45.073-4.493.19-9 .248-13.493 0-7.863-.393-15.74-.029-23.632-.175-7.571-.145-15.171-.102-22.771-.029-7.396.073-14.806.073-22.202.102-6.987 0-13.96 0-20.977-.116-3.326-.073-6.666-.146-9.978 0-2.085.072-4.186.101-6.272.029-2.217-.073-3.91 1.5-3.589 3.758.19 1.471-.116 2.87-.175 4.268-.19 8.377.102 16.739 0 25.115-.043 4.196.044 8.42.102 12.645.044 5.405.146 10.78.175 16.185.073 7.808.073 15.645.103 23.468 0 .67-.19 1.37.466 1.938.365.32.22.888.146 1.355-.218 2.039-1.21 4.049-.029 6.089-1.225.83.54 1.908-.277 2.972-.394.51.19 1.69.19 2.578.072 8.741.145 17.511.145 26.251-.029 4.837.103 9.644.146 14.48.03 2.142.51 4.487.292 6.454-.365 3.584.102 7.124-.044 10.649-.218 6.046-.043 12.077 0 18.137.03 5.157-.073 10.314.19 15.471.175 3.088-.073 6.162.102 9.25.19 3.307.19 6.672.175 9.994-.029 2.389.394 4.807-.277 7.487-5.354-7.167-12.078-11.814-20.773-13.62.817-.904 1.08-1.69 1.08-2.681-.03-7.59.044-15.194-.102-22.784-.102-4.152-.219-8.303-.19-12.441.044-5.812.117-11.639-.029-17.452-.175-6.526-.044-13.081-.102-19.622-.044-6.061-.073-12.135-.044-18.195.03-6.978-.32-13.927-.175-20.876.044-2.622-.146-5.375-.35-8.027-.175-2.039.146-4.414.19-6.599.116-4.268.029-8.551 0-12.82-.03-1.617-.03-3.292-.175-4.836-.175-1.835-.423-3.482-.03-5.346.146-.714.19-2.215-.029-2.68-.817-1.836-.044-3.657-.291-5.478-.321-2.142.145-4.443.043-6.6-.32-6.671-.044-13.329-.19-20.015-.145-7.415-.101-14.801-.422-22.202-.073-2.01.32-3.933.145-5.914-.19-2.083-.029-4.196-.073-6.279-.029-.816-.072-1.646-.248-2.462-.218-1.078.642-2.156 1.445-1.602l.073.014ZM292.74 150.09c.029 1.224-.642 1.428-1.576 1.573-5.733.933-11.436 1.035-17.14-.32-3.559-.86-7.25-.277-11.991-.35-2.976.277-7.148.219-11.188-.291-5.675-.743-11.597-.466-16.995-3.045-2.83-1.354-5.062-3.307-6.068-6.337-1.357-4.079 1.327-8.128 5.602-9.308 3.661-1.006 7.468-1.049 11.159-1.865 4.055-.889 6.987-3.394 9.861-6.133 2.626-2.477 5.529-4.56 9.365-4.909 2.538-.219 5.135-.394 7.527-1.137 1.474-.466 3.049-1.398 4.099-2.695 2.83-3.438 6.638-5.229 10.722-6.599 1.182-.393 2.538-.349 3.807-.495.351-.029.759.116 1.036-.029 2.728-1.574 1.824.51 1.824 1.748-.03 3.409-.03 6.803-.03 10.183 0 6.06 0 12.105-.029 18.151 0 3.948-.073 7.91 0 11.858h.015Zm-.321 118.727c-.044 5.885-.321 11.756-.35 17.656-.029 2.506.189 5.04.51 7.531.102.962-.218 1.006-.933 1.21-2.115.539-4.377.83-6.244 1.835-3.005 1.617-6.608 1.821-9.292 3.861-3.267 2.476-5.587.684-7.892-1.151-1.692-1.355-3.471-2.608-4.77-4.473-.51-.757-.758-1.646-.467-2.01 1.518-2.01.321-3.875-.145-5.696-.54-2.156-.89-4.443-2.014-6.453-.743-1.37-1.75-2.579-2.217-4.152-.248-.743-1.429-.714-2.232-.568-7.541 1.296-13.624 4.88-17.826 11.392a7.812 7.812 0 0 0-1.035 2.549c-.248 1.297-1.08 1.836-2.407 1.471-2.509-.67-4.814-.815-7.25.714-1.43.903-3.02.685-4.726-.787-4.727-4.049-10.197-6.264-16.616-4.792-.831.189-1.75.437-2.582.349-1.677-.218-2.334.437-2.611 2.084-.612 3.656-.904 7.196.248 10.882.511 1.675.934 3.219 1.94 4.647 1.255 1.792 1.503 4.006 2.378 5.972.584 1.355.321 3.045-.423 4.444-.977 1.821-1.604 3.787-3.297 5.331-1.065.976-2.013 1.865-3.34 2.477-2.042.961-2.145 2.068-1.473 4.443.072.321.247.612.145 1.107-1.896-.568-3.88-.277-5.82-.51-.511-.073-1.109-.102-1.4-.437-2.218-2.607-5.208-2.214-8.111-2.185-.277 0-.54.219-.817.291-1.371.277-2.757 1.006-4.026.977-1.473 0-1.284-2.04-2.144-3.045-2.364-2.797-5.354-3.948-8.432-1.573-1.298 1.005-2.436 1.15-4.099.611-4.23-1.369-7.936.277-11.334 2.754-1.766 1.325-3.545 2.724-4.085 5.055-.117.466-.321.437-.744.291-1.05-.32-2.144-.612-3.238-.714-1.576-.145-3.093.277-4.42 1.151-1.036.714-1.576.35-2.291-.495-1.444-1.69-3.121-3.016-5.484-3.438-1.62-.277-3.078 0-4.406.641-2.48 1.209-4.668 2.84-6.812 4.545-.277.189-.35.714-.788.51-.437-.219-.423-.67-.437-1.078a13.106 13.106 0 0 0-1.941-6.701c-.831-1.326-1.794-2.55-2.698-3.803-.934-1.296-2.626-.276-3.91.175-.539.19-.963.292-1.502.146 2.976-3.657 6.447-6.658 10.546-8.886 1.605-.86 3.078-.321 4.654.437 2.83 1.354 5.587 3.001 9 2.68 2.218-.218 4.654.364 6.681-.32 3.224-1.137 6.594-2.04 9.409-4.4 1.765-1.5 3.705-2.855 5.135-4.661 1.999-2.579 3.793-5.303 5.208-8.275 1.254-2.578 2.334-5.186 2.757-8.056.146-.976-.394-1.646-1.007-1.835a45.323 45.323 0 0 0-16.863-2.113c-.277 0-.54.146-.904.073 1.05-.583 1.896-1.471 2.946-1.967 1.109-.509 2.116-1.18 3.166-1.762 2.115-1.18 4.128-2.477 5.806-4.196.612-.641 1.152-.815 1.911-.757 4.186.218 8.329-.044 12.487-.685.685-.116 1.21-.291 1.619-.889.175-.276.423-.641.715-.713 3.88-1.006 6.812-3.628 10.123-5.594 2.232-1.355 4.26-2.972 6.375-4.444 1.998-1.354 3.545-3.365 5.426-4.88.861-.714 1.941-1.325 3.122-1.602.175-.029.438 0 .496-.102.977-2.01 3.443-1.967 4.799-3.394 1.43-1.53 3.516-1.996 4.96-3.322 1.824-1.69 4.128-2.112 6.214-3.117 1.605-.743 2.859-2.069 4.625-2.623 3.792-1.179 7.147-3.467 11.057-4.399.817-.189 1.517-.641 2.29-1.005 2.932-1.428 6.214-1.748 9.263-2.826 5.266-1.836 10.839-2.113 16.221-3.336 3.881-.889 7.819-.976 11.685-1.064 3.311-.043 6.812-.218 10.124 1.064 1.998.757 4.259.51 6.316 1.325.904.35 1.575.685 1.371 1.821-.117.889.642 1.078 1.225 1.209.686.175.978-.247 1.153-.932.686-2.505.438-3.409-2.086-4.589a23.21 23.21 0 0 0-9.54-2.083c-.817-.029-1.372.495-1.503-.67-.029-.073-.364-.175-.496-.117-1.546.671-2.932-.757-4.449-.364-.423.117-1.138-.291-1.006.656.043.32-.321.422-.467.277-2.232-1.982-4.916-.904-7.309-.758-3.705.189-7.468.743-11.057 1.69-2.509.641-5.091 1.005-7.6 1.646-4.011 1.049-7.994 2.229-12.02 3.22-1.678.393-3.151 1.296-4.77 1.864-4.099 1.355-8.081 3.074-11.991 4.91-4.259 2.01-8.169 4.618-12.385 6.657-.787.393-1.21 1.209-1.692 1.69-1.225 1.209-3.019.685-4.055 1.908-.963 1.151-2.378 1.748-3.516 2.622-2.042 1.617-4.055 3.307-6.199 4.866-6.492 4.647-13.246 8.784-20.948 11.144-1.4.437-3.092.117-4.653.044-.715-.044-.35-.641-.19-.932 1.08-1.996 2.217-3.977 3.311-5.944 1.007-1.748 1.372-3.788 2.48-5.477.423-.671-2.071-2.827-3.194-2.827-4.946-.043-9.876-.072-14.821-.102-1.824 0-3.633.073-5.427.03-1.211-.044-2.115 1.078-3.369.684-.19-.073-.467.044-.613-.568 3.005-1.078 5.062-3.613 7.454-5.623 2.772-2.331 4.843-5.507 5.995-9.236 1.532-4.866 2.48-9.789 3.589-14.728.467-2.039.715-4.122 1.182-6.235 4.347 1.209 8.796 1.646 13.172 2.506 3.953.786 7.921.83 11.845.568 2.115-.146 4.26-.393 6.346-1.107 1.035-.35 2.363-.51 3.515-.495 2.801 0 5.514-.743 8.009-1.647 3.442-1.282 7.075-1.995 10.43-3.438 3.165-1.369 6.564-2.112 9.686-3.51 2.407-1.049 4.959-1.472 7.381-2.404.934-.364 1.896-.583 2.903-.758 1.284-.189 2.465-.903 3.793-1.078 1.283-.174 2.582-.291 3.792-.743 1.299-.437 2.655-.32 3.983-.539 1.21-.189 1.692-.757 2.188-2.185.189 1.18.248 1.909 1.327 1.748 5.631-.932 11.306-.582 16.965-.786 7.25-.219 14.384.83 21.59 1.078.671 0 1.4.277 1.94-.466.175-.277.671-.292.744-.03.365 1.078.934 1.049 1.371.19.365-.743.423-1.719-.642-2.04-1.05-.349-2.159-.611-3.238-.611-1.225-.03-2.407-.321-3.632-.394-.365-.029-1.299-.685-.963.641.102.292-.496.292-.54.029-.248-1.296-1.284-1.034-2.086-1.063-2.844-.175-5.82-.044-8.533-.612-3.545-.743-7.002-.277-10.503-.51-1.328-.073-2.685.364-3.954.423-2.334.102-4.653.495-6.987.67-3.982.276-7.921.932-11.845 1.821-3.837.859-7.542 2.258-11.553 2.607.539-1.151-.496-1.894-.832-2.84-.817-2.288-1.969-4.327-3.515-6.163-.861-1.048-.963-1.937.437-2.767 3.793-2.258 7.542-4.516 11.451-6.6 4.814-2.534 9.789-4.559 14.748-6.672 1.824-.757 3.589-1.762 5.485-2.476.759-.291 1.546-1.034 1.43-2.156-.044-.277-.277-.685.35-.758.613-.102.423.248.467.568.116.787.685.438 1.108.321 2.159-.714 4.202-1.719 6.2-2.841 1.036-.612 2.261-.888 3.399-1.325 3.122-1.253 6.375-2.535 9.146-4.225 2.772-1.69 6.127-2.141 8.578-4.37.904-.831 2.188-1.18 3.296-1.574 2.013-.743 3.487-2.476 5.602-2.942.744-.175.817-.889 1.138-1.37.467.117.364.466.364.714 0 9.425-.029 18.836-.029 28.262v25.041c0 5.871.029 11.742-.029 17.598-.044 5.58-.219 11.144-.248 16.724-.029 6.279.102 12.601.029 18.909l.015-.073Zm-32.778 79.773c1.211.83 2.626 1.398 3.982 1.966 1.401.539 2.334 1.865 4.099 2.069-1.429 1.719-2.611 3.409-4.026 4.793-1.371 1.325-2.29 3.001-3.836 4.181-.978.757-1.065 1.966.043 3.161 1.518 1.719 2.757 3.7 4.552 5.186.583.466.685.743.102 1.5-.978 1.253-2.465 2.186-2.611 4.152-.044.568-1.284 1.763-2.684 1.078-.642-.32-1.517-.684-2.145-.495-2.976.903-5.747-.568-8.636-.568-2.975-.029-5.922-.277-8.898-.277-6.345.029-12.268 1.894-18.249 3.729-2.844.889-5.382 2.389-8.081 3.584-.861.364-1.605 1.078-2.305 1.719-.277.218-.511.612-.861.422-.35-.174-.277-.67-.175-.961.277-.889.292-1.792.569-2.681.861-2.84 1.474-5.739 2.334-8.565 1.211-4.006 3.297-7.59 5.237-11.276 1.94-3.656 4.551-6.745 7.323-9.716 1.517-1.617 3.516-2.695 5.354-3.948 1.619-1.137 3.223-2.331 4.726-3.628 3.165-2.767 6.987-4.399 10.868-5.798 3.88-1.427 7.775-2.797 11.83-3.656 1.284-.277 2.407-.117 3.588.189 2.655.714 3.706.292 5.194-2.039.612-.976 1.502-.495 2.582-.466-2.801 4.181-5.514 8.027-8.709 11.494-.671.713-1.43 1.252-1.896 2.287-.642 1.355 0 2.083.714 2.578l.015-.014Zm-202.926 2.33c.03-.684.03-1.398.03-2.083.072-.029.174-.043.276-.073.146 2.972.394 5.973.423 8.96.073 4.588 1.153 8.857 3.837 12.644.715 1.049.613 1.37-.686 1.428-3.486.117-3.56.146-3.472-3.307.19-5.871-.583-11.683-.393-17.554l-.015-.015Zm-.496-32.529c-.03-1.981-.423-4.05-.613-6.089-.116-1.18.248-1.399 1.357-1.21 1.473.277 2.976.437 4.493 0 .963-.247 1.575.292 1.998 1.151 1.138 2.229 2.014 4.56 2.83 6.92.394 1.136.963 2.214 1.445 3.394-1.693.437-3.297-.364-4.917.219-1.137.393-2.115.714-2.946 1.821-.671.903-1.999 1.296-2.072 2.724-.043 1.355-.218 2.68-.35 4.006-.102 1.428-.218 2.826-.364 4.72-.365-.787-.686-1.136-.642-1.399.831-5.419-.146-10.853-.219-16.257ZM32.326 352.13c.044-3.686-.117-7.386.029-11.101.175-3.715.744-7.386.715-11.115-.03-5.667-.044-11.348.102-17.044.102-3.948.146-7.925.365-11.902.175-3.365-.146-6.774-.321-10.168-.03-.612.102-1.108.35-1.617 1.43.713 2.946 1.18 4.405 1.223 1.62.029 1.911.903 2.145 2.069.422 2.287.962 4.589 1.94 6.672a35.67 35.67 0 0 0 3.661 6.235c1.517 2.039 3.837 3.19 6.098 4.268 1.035.495 1.502 1.035 1.473 2.302-.146 7.298.583 14.553.496 21.808-.102 7.021-.146 14.043-.146 21.065-.03 3.54.496 7.065.584 10.634.029 1.763-.146 3.54.043 5.303.073.714-.364 1.005-1.108 1.005-6.783-.029-13.552 0-20.335 0-1.211 0-1.007-.86-.934-1.603.671-5.987.35-12.032.438-18.049v.015Zm14.179-53.595c-1.532-1.996-2.232-4.254-2.626-6.672-.175-1.034.146-1.253 1.007-1.355 3.165-.393 6.345-.816 9.423-1.748 1.225-.364 2.072.437 2.538 1.399 1.474 2.869 4.128 4.938 5.412 7.954.248.582 1.007.932 1.444 1.442 1.474 1.821 1.43 3.86.715 5.943-1.721-1.791-2.509-4.224-4.201-6.089-1.926-2.141-3.764-4.327-6.17-5.914-.76-.496-1.605-1.108-2.48-1.006-1.62.175-1.299 1.792-1.649 2.827-.32.888.613 1.136 1.299 1.5 1.72.976 3.296 2.229 4.492 3.831 1.678 2.186 3.545 4.298 4.698 7.27-1.824-.321-3.414-.743-4.945-1.37-3.91-1.646-6.492-4.734-8.943-7.997l-.014-.015Zm13.245-97.837c-.102-1.995.759-4.151-.54-6.089-.277-.35-.116-.903.35-1.209.496-.277.438-.714.19-1.034-.642-.758-.044-1.647-.175-2.215-.642-2.403 1.357-4.88-.292-7.196-.466-.641.35-1.224.248-2.083-.175-1.224-.54-2.579-.277-3.948.117-.612.102-.86.759-.976.612-.146.962-.277 1.4.437 1.371 2.141 1.4 1.996 3.69.903 2.116-.961 4.48-1.151 6.755-1.515 1.765-.32 3.56-.495 5.339-.758 1.356-.247 2.305.248 3.472.977 2.465 1.573 5.193 2.724 7.498 4.559 2.115 1.69 4.492 3.001 6.783 4.341 2.844 1.69 5.558 3.657 8.635 5.041 2.466 1.136 5.019 2.36 7.207 3.802 3.267 2.214 6.812 3.802 10.123 5.9 1.357.83 2.874 1.471 4.347 2.083 1.868.787 1.868 1.107.54 2.506-.758.816-1.473 1.937-1.619 3.015-.248 2.04-.905 2.433-2.976 1.923-1.969-.495-4.128-.277-6.214-.277-4.799-.043-9.584-.32-14.354.03-4.566.32-9.249 0-13.77 1.034-2.043.495-4.1.044-6.142.612-3.297.932-6.666 1.675-10.007 2.374-3.69.758-7.075 2.36-10.868 3.948 0-5.55.19-10.882-.102-16.199v.014Zm-.817-66.283c-.102-.568 2.072-2.01 2.364-1.617.89 1.107 2.086.364 3.077.816a34.787 34.787 0 0 1 5.412 3.074c2.364 1.646 4.814 1.835 7.542 1.69 3.662-.219 7.352-.277 11.014.029 1.137.102 2.436 1.209 3.238 2.302 1.065 1.442 2.611 1.791 4.23 1.82 2.48 0 5.048.219 7.309 1.399.977.495 1.502 1.602 1.794 2.68.277.976.613 2.04.569 3.045-.073 1.938 1.4 2.535 2.611 2.433 2.042-.146 4.084-.102 6.127-.86 1.721-.67 3.865-.349 5.805-.218.905.073 1.649.044 2.291-.612.321.423-.438 1.369.89 1.107 1.429-.291 2.83 1.355 4.376.35.831 2.039 3.545 1.282 4.551 3.044.146.219.423.539.642.539 2.903.073 2.801 2.899 3.661 4.516.438.831-.321 2.972-.831 4.414-.613 1.749-2.232 1.909-3.807 2.331-2.509.641-5.135.117-7.542.933-4.333 1.427-8.855.932-13.275 1.719-5.412.961-11.057.422-16.571.961-2.334.219-4.814-.116-7.075.962-.277.116-.89.713-1.284-.19-.219-.539-.54.248-.612.219-2.218-.277-4.274.684-6.448.743-.613 0-1.254-.175-1.896-.102-2.611.32-5.208.714-7.82.903-3.296.248-6.564.32-10.152.466 1.692-.932.54-2.36.394-3.147-.54-3.234-.19-6.482-.277-9.702-.19-6.919-.175-13.854-.22-20.773-.028-1.748.22-3.482-.043-5.259l-.044-.015Zm-.35-16.738c-.219-1.894 1.692-1.923 2.932-2.404 3.297-1.296 6.754-.932 10.182-1.107 2.188-.116 4.347-.714 6.52-1.107 2.306-.422 4.377.117 6.288 1.471 1.678 1.209 3.413 2.186 4.77 3.905 1.05 1.354 3.122 1.078 4.595.364 1.984-.933 3.983-.758 5.996-.641.394.029.86.189 1.079.466 1.721 2.083 3.764 4.079 3.268 7.138-.117.903.102 1.719.291 2.579.248 1.048.817 1.762 2.043 1.748 1.677-.029 3.326.291 5.018.276 3.297-.029 5.879 1.821 8.329 3.759 1.211.961 1.226 4.152.102 6.089-.904 1.603-1.75 3.263-2.552 4.88-.934 1.909-2.51 1.574-3.881 1.69-1.327.117-2.757.175-3.865.743-1.576.787-1.838-.349-1.999-1.136-1.036-6.556-5.995-8.493-10.62-7.634-2.071.365-3.267-.393-4.478-1.646-3.326-3.438-7.527-4.006-11.947-3.554-1.473.145-2.976.641-4.42.976-1.94.495-4.012-.466-5.806-1.544-1.298-.787-2.29-2.142-3.793-2.535-1.867-.495-3.705-1.53-5.732-.35-.278.146-.642.073-.671.539 0 .437.116 1.078-.613 1.005-.613-.072-.569-.757-.642-1.136-.19-.83-.117-1.719-.175-2.607-.03-3.409.146-6.833-.248-10.256l.03.029Zm-.248-73.232c-.102-3.088-.248-6.191-.19-9.28.044-2.403.278-4.836 0-7.269-.145-1.325.35-1.966 1.897-2.04 5.952-.247 11.903-.276 17.855-.189 2.699.044 5.426.044 8.14.102h.19c4.055-.64 8.11.437 12.165.03 1.911-.19 3.808-.03 5.733-.19.861-.073 2.042 0 2.976.423.686.32 1.371 1.048 1.109 1.791-.511 1.472.51 2.04 1.356 2.623 1.357.961 2.539 2.141 4.187 2.724.904.32.933 1.53 1.065 2.476.116 1.035.146 2.477 1.211 2.724 1.05.219 2.115.743 3.267.641 3.487-.276 7.002-.102 10.328 1.107 2.509.904 4.77 2.404 5.631 5.187.715 2.287-.788 3.977-3.487 4.093-3.121.175-6.272.146-9.365.495-3.238.365-6.535.467-9.788 1.05-3.632.67-7.381.611-11.043 1.15-3.486.51-7.03.35-10.517.787-3.34.422-6.71.495-10.08.743-1.152.102-2.261.466-3.472.248-.963-.175-1.75.247-1.823 1.573-.102-1.005-.365-1.253-1.4-1.326-3.297-.277-6.288 1.326-9.57 1.253-2.042-.03-4.085.757-6.316 1.224 0-4.152.102-8.158-.03-12.135l-.029-.015Zm.117 27.577c.03-3.19 0-6.366.03-9.557 0-2.403.364-2.928 2.683-3.627.51-.146 1.05-.117 1.328-.685.291.146 1.006-1.15.977.277 0 .35.248.291.496.19 2.159-.83 4.624-.423 6.71-1.326 1.08-.466 1.824.116 2.684.146 1.678.043 3.37.072 5.018.189.978.044 2.48-.54 3.793-.641 5.135-.393 10.255-.903 15.39-1.15 3.807-.176 7.614-.642 11.436-.962.686-.073 1.328-.248 1.999.32.423.35 1.473.889 1.356-.64-.043-.642.613-.394.978-.423 4.23-.496 8.504-.32 12.778-.437 3.633-.117 7.134-.904 10.576-1.909 1.357-.422 1.649-1.82 1.678-3 .029-1.822.51-3.76-.977-5.376-.248-.277.364-.903.072-1.574-.743-1.791-2.144-2.695-3.836-3.16-1.225-.35-2.159-.715-1.838-2.696-1.4 1.894-2.801.758-4.085.743-2.538-.043-5.047.612-7.614.175-1.999-.32-3.341-1.865-2.932-3.875.277-1.297-1.692-3.482-3.589-3.831-.758-.117-1.429-.35-1.823-.903-.467-.641-1.182-1.428-.759-2.186.277-.466 1.211-.29 1.897-.29 6.243.028 12.487-.03 18.73-.03 3.413 0 6.856.102 10.269.102.817 0 1.036.32 1.182 1.136.963 4.866 1.794 9.717 2.378 14.64a649.659 649.659 0 0 1 1.546 13.971 333.912 333.912 0 0 0 1.911 16.083c.54 3.715.35 7.488.89 11.203.423 2.898.861 5.812 1.05 8.71.394 5.406 1.605 10.65 2.159 16.011.584 5.841 1.036 11.683 1.94 17.51.467 2.928.467 5.886.861 8.814.715 5.521 1.4 11.027 2.334 16.519 1.138 6.658 2.538 13.286 3.588 19.958.365 2.389.715 4.764 1.255 7.124.219.976 1.254 2.112.642 2.826-.54.612-2.013.35-2.976.714-2.465.961-5.062 1.442-7.615 2.068-.612.146-.933.19-1.429-.539-1.97-3.044-4.231-5.9-6.215-8.915-1.91-2.899-3.792-5.813-6.141-8.391-.292-.321-.496-.743-.102-1.369 1.05-1.617.613-3.162-.715-4.487-.102-.102-.248-.321-.189-.423.831-2.797-.788-4.487-2.553-6.308-1.794-1.835-3.953-3.073-6.069-4.399-.32-.189-.539-.393-.714-.743-1.153-2.374-2.83-4.399-4.552-6.41-.291-.349-.685-.582-.583-1.151.744-3.554-.817-6.482-2.874-9.104-1.006-1.297-2.582-2.186-3.938-3.191-.613-.437-1.138-.903-1.503-1.602-1.867-3.394-3.705-6.803-5.66-10.139-1.911-3.293-3.807-6.599-6.025-9.702-1.648-2.288-2.829-4.881-4.813-6.95-.438-.494-.54-1.296-.963-1.864-1.678-2.258-3.122-4.69-4.814-6.876a398.03 398.03 0 0 1-7.79-10.314c-2.655-3.583-5.412-7.094-8.081-10.649-1.897-2.535-3.793-5.113-5.879-7.488-1.284-1.5-1.823-1.602-4.624-.961 2.232 3.074 4.011 6.133 6.243 8.96 1.97 2.505 3.414 5.477 5.514 7.88 1.503 1.72 2.553 3.686 3.954 5.449 1.94 2.476 3.792 5.04 5.85 7.415 1.823 2.083 2.946 4.69 5.134 6.584.758.67 1.298 2.142 2.159 3.016 1.75 1.821 2.378 4.341 4.186 6.118.248.248.424.568.54.889 1.138 2.84 3.414 4.982 4.654 7.764.073.146.218.365.35.394 1.823.291 1.473 2.083 2.159 3.146.831 1.282 1.254 2.841 2.552 3.832 1.08.815.934 2.301 1.795 3.263.175.189 0 .582-.438.495-.642-.146-1.284.219-1.867.189-1.211-.102-2.436.073-2.436-2.083.029-1.427-.788-3.088-1.546-4.559-1.08-2.215-2.874-3.73-4.493-5.449-.744-.816-6.317-.684-7.134.146-.641.641-1.473.612-2.115 1.078-.569.393-.86.102-1.254-.364-2.48-2.928-5.31-5.507-9.249-6.09-2.611-.393-5.31-.043-7.79.86-2.29.83-4.565.67-6.914.568-1.692-.073-3.545-.35-5.091.816-.277.218-.671.277-.963.437-1.444.787-1.94-.029-1.867-1.253.277-3.977.146-7.954-.044-11.902-.175-3.467-.277-6.92-.248-10.357.03-5.42-.029-10.897.044-16.33l-.03-.088Zm157.938-37.57c-.583 2.476-1.765 4.865-1.502 7.531.102.787-.861 1.18-1.62 1.282-1.05.146-1.75.685-2.304 1.603-.832 1.369-1.97 2.04-3.808 1.675-3.807-.743-7.541.218-10.897 1.865-2.304 1.15-4.128 3.234-6.287 4.69-1.21.816-2.582 1.326-3.296 2.724-2.378-.35-4.377 1.035-6.521 1.647-5.704 1.602-11.801.816-17.359 2.87-2.655.976-4.654 2.797-5.996 5.52-1.371 2.798-.831 5.187.438 7.663.248.496.248 1.005.277 1.53.102 1.209.686 1.82 1.897 1.865.277.029.612 0 .831.145 5.383 3.482 11.583 2.972 17.534 3.73 2.334.32 4.551.611 6.856.218 4.449-.714 8.928-1.005 13.406-1.37 1.867-.145 3.764-.028 5.675-.028-1.649 2.301-1.007 5.23-1.474 7.954-.714 3.904-1.692 7.677-2.903 11.464-.933 2.928-1.575 5.973-2.071 8.989-.248 1.675-1.05 3.088-1.357 4.763-.51 3.118-1.298 6.206-2.261 9.236-1.517 4.808-2.232 9.819-3.632 14.655-1.254 4.327-1.911 8.814-3.238 13.111-1.547 5.113-2.261 10.416-4.202 15.413-1.648 4.297-2.902 8.711-4.303 13.082-.219.713-.496.976-1.327 1.034-1.765.044-3.56.291-5.339.539-2.655.393-3.326 0-3.764-2.753-.423-2.535-.583-5.084-1.036-7.59-.423-2.404-1.225-4.735-1.502-7.138-.219-1.836-.861-3.628-.584-5.58.117-.961-.583-1.995-.787-3.044-1.503-7.983-2.013-16.112-3.093-24.154-.423-3.161-.394-6.453-.933-9.629-.365-2.185-.54-4.472-1.153-6.584-.831-2.943-.117-5.915-.613-8.843-.35-2.069-.583-4.123-.889-6.191-.073-.496.073-1.078-.715-1.18-.438-.073-.423-.583-.248-.86.583-.83.788-1.515.321-2.258-1.08-1.69-.467-3.7-1.05-5.506-.321-.933.977-.175 1.254-.933-1.605-.102-1.648-1.223-1.721-2.462-.19-3.146-.686-6.264-.642-9.396.029-1.602-.365-3.22-.044-4.764.35-1.646-.175-2.971-.904-4.253-.423-.787 0-1.472-.102-2.215-.496-4.02-1.693-7.924-1.941-11.974-.277-4.181-.889-8.304-1.444-12.427-.423-3.073-1.035-6.133-1.692-9.177-.321-1.399-.685-2.724-1.298-4.006-.423-.933-.248-1.136.831-1.136 6.36 0 12.706.029 19.052.029 13.449.029 26.899.029 40.348.029h12.123c-1.445 2.753-2.232 5.667-2.947 8.566l-.044.029Zm8.286 13.577c2.728 1.442 3.515 3.904 4.741 6.133.715 1.253 1.692 1.442 2.684 1.282 2.655-.51 5.266-.35 7.717.568 1.823.67 3.734 1.719 4.084 4.02.321 2.142 1.678 3.876 2.334 5.871.19.569.832.219 1.255.248 1.356.073 2.684 0 3.836.903.963.787.963 1.603.248 2.506-1.254 1.646-3.939 2.185-5.922 1.355-.569-.248-1.328-.219-1.897-.073-4.595 1.326-9.321 1.646-14.018 2.33-2.407.35-4.887.321-7.25.89-4.814 1.18-9.716 1.048-14.602 1.398-5.923.422-11.875.568-17.826.67-4.406.073-8.826.51-13.231.51-2.947-.03-5.923-.51-8.869-.816-2.159-.218-4.274-.714-5.996-2.185-2.698-2.331-2.261-5.871.978-7.459 3.369-1.646 6.914-2.768 10.692-2.87 3.706-.029 7.455-.611 10.795-1.995 2.757-1.108 5.631-2.302 7.863-4.735 1.794-1.908 4.026-3.656 6.71-4.516 1.036-.32 2.071-.67 2.932-1.37.321-.247.817-.364 1.327-.276 2.378.422 4.887.35 7.032-.54 1.619-.684 3.326-1.529 4.872-2.578 2.582-1.748 6.856-.64 9.511.743v-.014Zm-21.663 141.423c2.437 1.136 4.377 2.724 5.908 4.909 1.765 2.506 3.545 5.012 4.916 7.736.394.757 1.051 1.326 1.62 1.763 2.217 1.864 2.932 4.647 4.551 6.846.321.423-.117.248-.19.35-.54.758-1.4 1.005-2.217 1.209-4.42 1.049-8.402 3.467-12.779 4.545-3.807.933-7.396 2.506-11.29 3.191-2.013.349-4.099.713-6.127 1.282-2.465.67-5.281.757-7.921.64-2.772-.116-5.66.248-8.286-.393-4.055-.976-8.212-1.5-12.166-2.797-1.035-.349-1.648-1.136-1.823-2.185-.365-2.302-1.648-3.365-3.88-2.928-1.941.393-3.939.189-5.821.787-.394.102-1.138-.423-1.721-.641-2.728-1.049-5.485-1.996-8.461-1.836-.364.029-.394-.32-.583-.495-.248-.219-.759-.583-.817-.51-1.43 1.282-2.159-.932-3.589-.641-1.444.277-3.092-.364-4.945-.67 3.953-5.055 7.396-10.27 12.706-13.679 6.535-4.181 12.953-8.624 20.524-10.824.292-.102.569-.219.861-.189 6.17.364 12.122-1.472 18.249-1.865 1.896-.117 3.807-.117 5.704-.292 3.369-.291 6.345.933 9.146 2.535 2.728 1.574 5.587 2.87 8.431 4.181v-.029Zm-.641-5.507c2.479-2.112 4.668-4.472 6.418-7.24 1.138-1.762 2.611-3.307 3.982-4.88 1.445-1.646 3.122-3.117 4.406-4.865.977-1.282 2.334-2.084 3.326-3.366 1.108-1.398 2.611-2.476 3.807-3.802 2.538-2.797 5.485-5.273 7.133-8.77.321-.67.715-.422 1.138-.247 4.347 1.908 9.117 2.185 13.596 3.481 2.582.743 5.12.816 7.571.438 3.515-.51 7.031-.831 10.517-.496 5.923.539 11.874 1.049 17.607 2.841 1.182.364 2.407.437 3.618.568.744.073 1.4.219 1.765.86-7.936 4.006-15.784 7.837-23.778 11.421-5.339 2.374-10.444 5.229-15.594 7.997-4.653 2.506-9.102 5.405-13.799 7.809-5.31 2.695-10.591 5.419-15.813 8.318-1.138.612-2.072 2.768-3.793 1.282-1.079-.962-2.261-1.909-3.165-3.045-2.334-2.928-5.339-4.909-8.636-6.483-1.211-.582-1.284-1.034-.321-1.835l.015.014ZM141.25 299.613c-2.757.903-5.776.539-8.388 1.617-3.092 1.282-6.564 1.646-9.248 3.933-1.138.962-2.582 1.501-4.187 2.375.642-3.088 2.291-5.186 4.202-7.065 4.011-3.905 8.241-7.445 13.945-8.639 2.29-.495 4.551-.743 6.856-.714 3.005.073 5.996-.029 8.972-.175 2.159-.116 2.538.219 2.013 2.229-1.211 4.545-2.772 8.814-6.419 12.135-3.472 3.161-7.454 5.084-11.947 6.162-4.187 1.005-7.892-.422-11.947-1.966 3.793-2.375 7.279-4.662 11.582-5.259 1.838-.277 3.662-.51 5.514-.758 1.036-.116 2.043-.248 1.824-1.69-.19-1.223-1.692-2.535-2.772-2.185ZM95.665 321.29c.174 1.573-.103 2.622-1.999 2.068-1.765.656-1.794.044-1.823-1.602-.044-2.185.029-4.37.029-6.556.029-1.937.364-3.977.744-5.943.496-2.797.831-5.594 1.327-8.377.613-3.481 1.225-7.021 2.976-10.241.613-1.136.715-2.549 1.225-3.787 1.255-3.016 2.305-6.192 4.026-8.916 1.751-2.768 3.224-5.739 5.339-8.303.351-.423.642-.86 1.299-.641 1.429.437 2.859.961 4.303 1.325 1.751.423.963 1.647.394 2.04-1.794 1.282-2.188 3.336-3.093 5.055-2.188 4.079-3.165 8.522-3.048 13.184.029.684-.219 1.296-.642 1.791a29.138 29.138 0 0 0-5.048 8.129c-1.429 3.482-3.02 6.905-3.705 10.751-.496 2.724-1.181 5.58-2.144 8.275a3.817 3.817 0 0 0-.175 1.719l.014.029Zm-9.176.175c0 2.36-1.532 3.336-3.618 2.301-.35-.175-.291-.437-.364-.743-.817-3.321-1.474-6.672-2.232-10.022-.496-2.113-.642-4.269-1.226-6.41 1.984 2.287 4.406 3.86 6.842 5.448 1.284.831.933 2.622.788 3.686-.292 1.937-.146 3.802-.175 5.725l-.015.015ZM68.94 263.966c1.08-.044 2.072-.86 3.02.641 1.43 2.214 2.553 4.545 4.201 6.657 1.867 2.36 3.793 4.691 5.704 6.993.248.291.423.757.744.859 2.086.714 2.071 2.462 2.013 4.123-.044 1.719.365 3.438-.073 5.448-2.232-2.928-4.654-5.273-7.425-7.211-1.298-.888-2.553-1.821-4.128-2.258-1.211-.32-1.795.117-1.765 1.297 0 .743-.175 1.398-.496 2.156-1.08-2.185-2.043-4.254-3.093-6.264-.86-1.646-.146-3.234.073-4.793.292-2.01.438-4.006.32-6.046-.028-.67-.393-1.573.905-1.617v.015Zm4.916 18.413c7.382 4.487 11.7 10.737 11.626 19.521-1.006-2.156-2.013-4.326-3.048-6.453-.496-.976-1.182-1.909-2.407-1.282-1.284.67-.584 1.646-.175 2.549a675.073 675.073 0 0 1 4.274 9.353c.19.466.146 1.034.248 1.617-6.842-4.618-11.51-17.234-10.518-25.319v.014Zm12.954-10.561c-.394-1.603-.277-3.22-.978-4.837-.466-1.078-.51-2.505-.364-3.904.248-2.462-2.013-4.152-2.655-6.41-.102-.393-.569-.83-.744-1.325-.496-1.326-1.298-2.229-2.83-2.011-.715.102-1.473 2.754-1.109 3.803.613 1.689 1.372 3.365 1.897 5.084 1.035 3.438 2.48 6.73 3.092 10.255.073.365.146.685-.116 1.326-5.427-5.521-8.432-12.149-10.737-19.302-3.953-12.135-1.502-23.687 1.94-35.531 3.866 3.191 7.717 5.769 10.824 9.09 3.735 4.007 6.273 8.785 6.783 14.554.51 5.696 1.678 11.348 1.299 17.088A48.439 48.439 0 0 1 91.04 270.9c-.788 2.506-2.042 4.691-3.734 7.065-.51-2.258-.03-4.253-.496-6.162v.015Zm22.844-23.891c-.438 3.146-.365 6.308-.832 9.425-.073.437-.146.962-.029 1.399.861 2.68-.933 4.341-2.29 6.191-.248.35-.584.583-1.05.248-2.539-1.836-5.733-1.647-8.534-2.623-.788-.276-.977-.437-.977-1.209.043-3.787.218-7.59-.044-11.363-.394-5.506-.86-11.071-2.874-16.199-1.75-4.443-4.23-8.624-7.79-11.974-2.144-2.04-4.449-3.861-7.133-5.187-.467-.218-.933-.539-.758-1.223.175-.583.51-.787 1.138-.889 5.31-.83 10.575-1.471 15.973-.787 3.69.467 7.454.321 11.159.539 3.793.248 7.542-.393 11.378.292 1.255.218 3.02-.394 4.552-.583 3.661-.51 7.104.86 10.59 1.69 1.43.32 2.801.787 4.376 1.224-3.048 1.252-6.024 2.214-8.781 3.627-4.26 2.214-8.082 5.011-11.087 8.93-4.201 5.507-6.068 11.683-6.987 18.457v.015Zm3.326 16.592c2.363-.276 4.726-.043 7.6-.102-1.649 1.297-2.874 2.258-3.735 3.555-.437.67-1.137.422-1.575.146-1.532-.962-3.297-1.049-4.96-1.748.219-1.617 1.357-1.749 2.684-1.865l-.014.014ZM88.517 280.85c4.2-4.094 5.733-9.411 6.914-14.859 2.378.714 4.624 2.083 7.279 2.141 1.007.029 1.138.641.584 1.501-2.086 3.481-4.347 6.876-6.142 10.503-2.217 4.487-4.42 9.061-5.703 13.941-.496 1.909-1.138 3.788-1.182 6.06-1.08-1.369-.89-2.84-1.152-4.18-.89-4.05-1.284-8.158-1.62-12.281-.102-1.18.292-2.141 1.036-2.841l-.014.015Zm11.013 39.974c1.284-5.725 2.334-11.509 5.208-16.797 2.086-3.86 4.566-7.444 7.206-10.897.394-.509.832-.903 1.619-.903 3.866-.029 7.717-.218 11.583-.582 1.517-.146 2.873-1.282 4.814-.685-1.153.757-2.086 1.427-3.122 1.966-.963.496-2.042.816-2.334 2.069-.044.189-.248.393-.438.51-3.69 2.287-5.383 5.987-7.25 9.673a59.47 59.47 0 0 0-2.903 6.628c-.116.364-.437.714-.758.933-3.589 2.301-6.069 5.666-8.563 9.032-.496.611-.934 1.005-1.721.961a8.419 8.419 0 0 0-1.605.029c-2.159.146-2.217.146-1.75-1.923l.014-.014Zm37.592-36.973c-1.284.116-2.538.495-3.691 1.049-2.334 1.136-4.872 1.005-7.323 1.427-2.902.466-5.805 1.049-8.708 1.603-.394.073-.788.102-1.547.189 2.218-2.506 4.129-4.764 6.711-6.512 2.232-1.5 4.77-2.258 7.031-3.627 1.006-.612 1.356-1.428.977-2.302-.437-1.005-1.356-.641-2.261-.364-3.793 1.034-6.856 3.365-10.08 5.376-1.619 1.005-3.194 2.287-4.42 3.729-.671.787-1.298 1.296-2.261 1.865 2.217-5.405 4.493-10.504 8.111-14.903 2.407-2.899 4.741-5.915 8.461-7.415 1.75-.714 3.559-.67 5.339-.962 3.88-.641 7.789-1.282 11.728-1.602a37.358 37.358 0 0 1 8.067.218c2.8.365 5.66.277 8.708.816-1.371 1.967-2.727 3.832-3.982 5.74-1.998 3.045-4.055 5.987-6.666 8.551-3.954 3.904-8.563 6.512-14.179 7.124h-.015Zm-6.2-26.732c-3.865 1.53-7.716 3.161-11.947 3.584-1.531.145-3.049.349-4.697 1.034.19-1.034.569-1.602 1.109-2.039 2.83-2.433 5.032-5.42 7.862-7.882 2.407-2.083 4.566-4.443 7.207-6.307 2.465-1.749 4.726-3.759 7.104-5.624 1.108-.859 1.473-2.112 1.765-3.321.364-1.471-.584-2.156-2.043-1.617-1.444.539-2.552 1.69-3.763 2.549-3.472 2.462-6.681 5.23-10.036 7.852-4.026 3.147-7.454 6.905-10.897 11.363-.102-4.836-.321-9.163 1.225-13.475 1.547-4.341 3.866-8.231 6.346-12.004.685-1.063 1.838-2.068 2.903-2.695 3.048-1.835 5.528-4.443 8.752-6.016 1.605-.787 3.195-1.603 5.047-1.501 2.218.117 4.304-.641 6.288-1.325 2.975-1.035 5.557.043 8.329.495 2.013.35 1.867 1.355 1.896 3.088.175 7.299-2.115 13.927-5.353 20.206-1.517 2.942-3.91 5.521-6.39 7.925-3.048 2.971-6.929 4.224-10.721 5.695l.014.015Zm-14.645-64.841c-4.1-2.039-7.892-4.545-11.875-6.73-2.552-1.428-4.653-3.7-7.323-4.953-2.538-1.18-4.74-2.826-7.177-4.123-.393-.218-1.4-.51-.831-1.151.365-.422 1.109-1.136 1.97-.684.189.102.422.393.51.145.612-1.646 2.188-.888 3.15-.976a353.67 353.67 0 0 1 6.988-.611c3.37-.248 6.681-.86 10.051-.889 2.436 0 4.843-.423 7.352-.117 2.305.248 4.814-.276 7.206-1.078 2.188-.743 4.566-1.063 6.885-1.282 1.051-.102 2.232-.189 3.02-.582 1.721-.889 2.159.276 2.772 1.223 1.254 1.836 2.217 3.875 3.661 5.551 2.086 2.403 2.903 5.521 4.96 7.881.35.422.321 1.223 1.371.976-2.465 1.529-5.12 2.01-6.929 4.021-.248.276-.613.466-.977.67-2.582 1.325-4.727 3.161-6.813 5.2-1.473 1.442-3.238 2.55-4.347 4.414-.394.641-1.327.539-2.071.073-3.793-2.462-7.527-4.982-11.553-6.978Zm8.708-45.611c-1.283.32-2.305-.496-3.442-.029-.394.145-.511-.365-.351-.743.351-.816.54-2.04 1.138-2.302.817-.35 1.065.976 1.62 1.5.393.394.641.962 1.035 1.574ZM60.99 225.828c-.102-2.229 1.867-2.87 3.268-3.701 1.867-1.078 3.982-1.689 5.995-2.534-2.874 6.511-4.332 13.154-4.653 20.059-.321 6.803 1.517 13.257 3.588 19.696-2.071-.029-2.8-1.136-2.946-2.87-.175-1.865-1.182-3.482-2.232-4.866-1.05-1.354-1.605-2.942-2.611-4.326-.861-1.18-1.357-2.477-1.284-4.254.219-5.74 1.108-11.436.86-17.204h.015Zm2.013 47.971c.817 1.326 1.4 2.797 2.218 4.123 1.867 3.015 2.48 6.599 4.478 9.629.977 1.5 1.371 3.409 2.013 5.186a289.267 289.267 0 0 1 2.363 6.483c1.284 3.7 1.721 7.604 2.699 11.392.364 1.398-.22 2.971.685 4.326.146.219-.19.641-.583.685-1.007-4.298-3.02-8.158-5.193-11.931-.89-1.544-2.013-2.943-2.903-4.472-.832-1.37-1.43-2.841-1.97-4.414-1.546-4.371-2.552-9.061-6.14-12.529-1.824-1.762-2.539-4.18-2.539-6.744.03-.976-.044-1.967-.423-2.841.613-.437 1.007.073 1.371.189 1.284.423 2.976-.641 3.91.933l.014-.015Zm9.832 49.589c-2.305.466-1.838-1.574-1.998-2.535-.438-2.899-1.868-5.303-3.195-7.779-.642-1.253-.423-2.87-1.62-3.875 1.051-.671.686-2.011 1.357-2.797.321-.423.613.043.788.509 1.109 2.87 2.684 5.551 3.983 8.319.977 2.112 1.37 4.297 2.144 6.439.467 1.252.102 2.083-1.444 1.719h-.015ZM60.86 288.673c-1.153-1.297-2.772-1.967-2.305-4.443.584 1.821 2.655 2.258 2.305 4.443Zm-.642 62.306c-.248-2.462-.467-4.88-.277-7.707-.277-2.68.102-5.666.19-8.696.043-1.938.51-3.905.904-5.842.175-.86.788-1.442 1.823-1.034 4.873 1.835 9.963 2.228 15.127 2.432 4.129.175 8.257.583 12.37-.043 4.377-.714 8.797-1.18 13.129-2.258 1.824-.437 3.735-.758 5.587-1.209 1.08-.277 1.576-.073 1.911 1.18 1.94 7.138 3.516 14.363 3.37 21.851-.102 5.346-1.648 10.387-3.443 15.398-1.21 3.394-3.194 6.279-5.426 9.018-1.824 2.258-4.201 3.394-7.236 3.875-6.097.976-12.122.349-18.16.218-1.08-.029-2.16-.146-3.24-.116-3.413.116-4.915-2.579-6.68-4.662-1.75-2.04-2.932-4.56-4.654-6.599-3.91-4.589-4.726-10.11-5.28-15.792l-.015-.014Zm56.293 11.785c1.05-3.336 1.211-6.832 1.692-10.256.686-4.865.904-9.745.832-14.655 0-.67-.176-1.835 1.254-1.282.292.117.292 0 .438-.218 1.648-2.579 4.303-3.861 6.958-5.055.54-.248 1.211-.248 1.721.073 1.911 1.136 4.085 1.966 5.135 4.224.584 1.253 3.078 1.501 4.274.976 1.517-.612 2.48-1.995 3.953-2.651 1.474-.656 2.655-.146 3.691.641 1.692 1.296 1.867 1.398 3.224-.189.787-.904 1.298-1.996 1.911-3.016 1.108-1.923 2.436-3.788 4.332-4.982 2.086-1.297 4.479-1.005 6.754-.437.715.175 1.284.568 1.824 1.049.904.903 1.94 1.034 3.092.364 2.144-1.253 3.02-.932 4.624 1.078.963 1.224 1.649 2.608 2.539 3.86.51.743 1.327.714 2.086.19 1.4-.903 2.727-1.792 4.478-2.142 1.838-.349 3.268-.073 4.653 1.151 1.211 1.049 2.626 1.297 4.201.831 3.02-.86 5.879-.19 8.651 1.048.219.102.437.277.642.248 2.611-.248 3.792 1.821 5.485 3.147 2.975 2.287 5.484 5.084 8.781 7.05 2.261 1.355 4.624 2.55 6.885 3.948 1.678 1.049 1.678 1.748.438 3.234-2.801 3.438-5.353 7.051-7.542 10.955-1.575 2.856-3.398 5.551-4.989 8.391-.977 1.763-2.698 1.515-4.347 1.515-5.951-.043-11.903-.043-17.855-.073-.393 0-.787-.102-1.035.437-.686 1.443-2.436 1.617-3.239.248-.394-.714-.86-.685-1.4-.685h-8.855c-.35 0-.962.044-.977.146-.467 2.287-1.007 1.18-1.765.146-.394-.539-1.225-.277-1.838-.277-17.33-.029-34.66-.029-52.004-.029h-1.97c1.153-3.19 2.334-6.089 3.268-9.032v.029Zm91.697-54.265c-.861-3.729-2.334-7.298-3.662-10.882-.583-1.544-.671-3.19-.758-4.836-.073-1.005.51-.962 1.05-.816 4.522 1.151 8.402 3.263 10.97 7.386a53.102 53.102 0 0 0 2.217 3.365c.583.787 1.298 1.763 2.407.932.977-.743.437-1.792-.073-2.549-2.553-3.802-4.945-7.779-9.365-9.79-.19-.072-.365-.247-.788-.568 3.195-.189 5.66 1.603 8.432 2.156 1.181.219 2.538 1.37 3.296 2.724.219.423.511.787.817 1.151 1.328 1.617 1.999 1.836 4.099.641 3.151-1.821 6.608-2.083 10.08-2.258 1.299-.073 1.94-.291 2.728-1.617 2.232-3.758 4.478-7.633 8.067-10.357 1.225-.904 2.859-1.209 3.953-2.404.744.932-.073 1.369-.496 1.865-1.867 2.083-3.019 4.545-3.836 7.167-.292.932-.963 1.719-1.444 2.549-.511.962-.496 1.894-.686 2.841-.175.714.35.962.758 1.209.423.248.817.073 1.284-.189 1.619-.962 2.072-2.652 2.509-4.196 1.138-3.977 3.516-7.167 6.098-10.255.715-.831 1.108-.321 1.429.291 1.824 3.336 3.268 6.92 3.078 10.722-.219 3.977.934 6.73 4.26 9.017 2.655 1.836 5.558 3.016 8.431 4.516-2.698 4.618-6.36 8.377-10.765 11.494-3.195 2.229-6.346 4.487-9.686 6.483-2.159 1.282-3.662 3.409-5.193 5.448-1.445 2.01-2.845 4.196-5.514 4.953-.351.102-.511.437-1.007.175-2.845-1.617-6.025-2.287-9.19-2.622-3.705-.394-7.498-.146-11.232-.685-1.722-.218-3.443-.466-5.121-1.005-2.479-.831-5.12-.962-7.614-1.792-1.838-.583-3.297-1.69-4.8-2.797-.641-.495-.364-.83.044-1.253 2.042-1.937 3.122-4.443 4.479-6.847 1.794-3.161 1.473-6.205.758-9.352l-.014-.015Zm28.956 27.723c-.102.247-.117.495-.248.568-1.138.568-1.328 1.923-2.261 2.651a1013.96 1013.96 0 0 0-9.511 7.532c-.278.189-.292.51-.788.189-5.135-3.365-9.89-7.24-14.267-11.567a20.603 20.603 0 0 0-3.807-3.015c-.35-.219-.613-.539-.963-.787-.612-.437-.787-1.034-.394-1.675.438-.743 1.153-.495 1.693-.175 1.575.903 3.048 1.908 4.813 2.477 2.218.684 4.42 1.296 6.711 1.5 1.327.102 2.231 1.151 3.588 1.18 1.503 0 3.151-1.078 4.478.437 1.226-1.428 2.874-.758 4.333-.83 1.692-.102 3.399-.117 5.062.291.787.219 1.138.714 1.546 1.209l.015.015Zm31.319-8.522c-2.115 0-4.26-.467-6.346.582-1.531.758-3.442.496-5.091 1.151-.977.393-.685-1.209-1.181-.859-.438.291-.511 1.107-1.226 1.354-.612.219-1.254.467-1.721.86-.831.714-1.532.277-1.94-.291-.496-.685.029-1.137.613-1.69 1.4-1.399 2.771-2.797 4.449-3.934 2.334-1.544 4.697-3.044 7.352-4.093 4.726-1.836 8.11-5.303 10.722-9.571.116-.175.189-.393.321-.568.189-.292.423-.539.86-1.078-.583 3.831-1.254 7.342-1.969 10.853-.511 2.607-1.896 4.516-3.151 6.628-.423.656-.89.656-1.692.656Zm24.361-222.668c-1.576-.116-3.005-.932-4.522-.714-6.054.831-11.262 3.395-15.39 7.911-1.298 1.427-2.772 2.258-4.697 2.331-2.188.101-4.376.247-6.929.364 3.195-4.181 6.2-8.129 9.219-12.033 5.135-6.658 11.218-12.528 16.251-19.23 1.619-2.156 3.661-4.05 4.813-6.584.175-.394.54-.743.934-.612.423.146.438.64.467 1.078.116 2.84-.029 5.725-.029 8.595 0 3.627-.073 7.27-.073 10.897.029 2.622-.365 5.258-.044 7.983v.014Zm-2.903-31.918c-.788.714-1.298 1.72-1.94 2.579-.584.889-1.109 1.835-1.794 2.651-1.838 2.142-3.326 4.56-5.135 6.672-1.532 1.763-2.728 3.831-4.595 5.346-1.371 1.108-2.334 2.696-3.443 4.08-1.896 2.36-3.982 4.545-5.849 6.919-1.357 1.748-2.947 3.482-4.377 5.201-1.473 1.792-3.151 3.482-4.376 5.521-1.823 3.001-4.741 4.938-7.425 7.065a110.297 110.297 0 0 0-5.587 4.808c-1.152 1.107-2.465 1.602-3.982 1.937-2.932.67-5.923.539-8.855 1.355-5.018 1.398-7.965 4.88-8.242 9.702-.219 3.394-.073 7.371 3.02 10.095.715.641 1.225 1.297.248 2.288-3.224 3.161-6.141 6.628-9.074 10.066-.51.612-1.502 1.078-1.765 1.617-1.4 2.826-4.055 4.472-5.922 6.847-1.109 1.427-2.305 2.84-3.691 3.977-3.049 2.534-5.164 5.841-7.746 8.769-.539.612-.35 2.215-1.298 2.258-1.036.03-2.261-.568-3.151-1.223-1.211-.903-2.582-1.107-3.938-1.399-2.757-.612-5.558-1.005-8.403-1.049-1.356-.029-.715-1.005-.54-1.5.496-1.369.905-2.797 1.474-4.123 1.152-2.68 1.444-5.55 2.363-8.245 1.357-3.904 2.071-7.998 3.311-11.931 1.036-3.219 1.547-6.555 2.655-9.717.277-.743.117-1.5.394-2.229 1.678-4.472 2.042-9.25 3.472-13.781 1.138-3.54 1.721-7.211 3.122-10.634 2.042-4.953 2.29-10.343 3.938-15.34 1.255-3.802 1.765-7.735 2.874-11.567.934-3.19 2.071-6.41 2.363-9.789.073-.889.35-1.398 1.473-1.398 2.772-.044 5.529-.467 8.286-.496 4.624-.073 9.146-1.034 13.712-1.471 3.297-.291 6.667-.67 9.905-1.471 1.007-.248 2.159-.044 3.224.029 3.589.247 6.521-1.37 9.19-3.41 2.29-1.718 2.538-5.87.438-7.764-.978-.903-2.378-1.573-3.91-1.5-1.138.043-1.867-.146-2.086-1.646-.364-2.652-1.473-5.332-3.005-7.372-2.115-2.797-5.514-3.933-9.146-3.438-.89.117-1.911-.102-2.757.816-.365.393-1.284.393-1.824-.568-1.283-2.258-3.238-4.02-4.492-6.366-.496-.889-2.014-1.53-3.122-1.602-.788-.044-1.474-1.108-2.305-.292-.394-.67-1.473-.393-1.502-1.763-.03-3.19 1.75-5.87 2.188-8.886.218-1.5.291-3.044 1.254-4.341.613-.83 1.182-1.53 2.407-1.53 3.953.073 7.936.03 11.918.03v-.03c4.566 0 9.176-.189 13.741.044 4.406.248 8.782.102 13.158.073 5.456-.03 10.912.175 16.367-.044 3.443-.116 6.915.393 10.357-.043.686-.102 1.138.247 1.138 1.005 0 1.005.277 1.995.277 2.942-.102 7.852.19 15.719-.073 23.57-.145 4.27-.247 8.567.19 12.82.321 3.147-1.05 5.012-3.122 6.876h.015ZM35.214 232.37c.117-1.763 1.576-.889 2.261-.612 3.69 1.369 7.148 3.263 10.62 5.113 1.065.568 1.998 1.471 2.757 2.389 3.165 3.729 5.98 7.634 7.935 12.222 1.11 2.652 1.97 5.347 2.772 8.071.54 1.763.788 3.554.496 5.594a531.131 531.131 0 0 1-5.66-8.1c-1.794-2.607-3.88-5.04-6.39-7.051-.83-.67-3.909.117-4.346 1.078-.292.612.044 1.297.496 1.501 3.37 1.442 5.28 4.472 7.702 6.949 3.02 3.117 5.237 6.876 7.775 10.824-2.757-.714-4.872-1.617-6.914-3.118-2.583-1.865-5.354-3.511-7.994-5.332-2.51-1.748-4.158-4.181-5.923-6.584-1.97-2.652-3.049-5.798-4.989-8.45-.933-1.296-.831-2.855-.904-4.224-.117-3.438.073-6.876.32-10.285l-.014.015Zm-8.636 48.83c-.466-.742-1.181-.437-1.75-.815-2.16-1.472-4.055-3.293-6.2-4.808-1.765-1.252-4.011-2.156-5.207-4.253-.248-.467-.934-.743-1.474-1.049-2.465-1.472-4.186-3.73-6.2-5.696-1.108-1.049-.291-1.326.511-2.011 2.611-2.185 5.98-2.971 8.723-4.88 1.328-.903 3.093-1.209 4.727-1.675 3.194-.903 6.2-2.549 9.686-2.258 1.502.146 3.02.189 4.551.393a3.39 3.39 0 0 1 2.582 1.792c3.02 5.885 7.717 10.095 13.406 13.33.146.101.292.247.467.276 4.2.365 4.566 3.467 4.989 6.745.32 2.229.102 4.472.364 7.197-3.194-2.754-5.98-5.157-8.942-7.343-2.903-2.112-5.514-4.617-8.606-6.453-2.83-1.69-5.558-3.555-8.753-4.647-1.109-.364-1.94-1.369-3.238-1.369-1.62 0-2.655.786-2.553 2.083.044.83 1.896 2.068 2.903 1.908.175-.029.102-.539.437-.189 2.305 2.301 5.675 2.768 8.286 4.618 3.15 2.214 6.564 4.049 9.613 6.439 2.013 1.602 3.808 3.438 5.82 5.011.642.51 1.182 1.136 1.503 1.996-1.444-.044-2.699.582-4.011.961-5.412 1.573-10.62 1.326-15.682-1.005-2.232-1.034-4.566-2.069-5.952-4.268v-.03Zm318.94 100.27c.044 3.554-.365 7.124-.189 10.707a4.45 4.45 0 0 1-2.043 4.05c-.831.51-2.377.393-3.238.175-2.976-.816-5.981-.641-8.942-.758-4.522-.174-9.044-.32-13.552.029-4.405.321-8.825-.174-13.231.641-2.844.51-5.893.219-8.825.044-4.522-.291-9.044-.277-13.552-.073-4.814.19-9.657.685-14.412.117-4.479-.51-8.928-.831-13.406-.903-5.456-.073-10.912-.423-16.324-.146-3.238.146-6.491.218-9.715.102-5.091-.219-10.182-.568-15.273-.903-3.238-.219-6.593-.029-9.89.116-4.085.146-8.14.437-12.195.612-6.74.291-13.494-.116-20.204.35-4.697.32-9.292-.146-13.945-.423-1.941-.116-3.91.029-5.675 1.035-.248.145-.569.276-.831.247-6.215-.51-12.414.35-18.629.029-6.287-.349-12.618-.713-18.934-.568-6.127.146-12.297.146-18.41.394-3.34.116-6.68.713-10.036.713-2.392 0-4.77-.029-7.147-.029-4.056.029-8.111.175-12.166.117-2.684 0-5.266-.641-7.936-.67-7.279-.102-14.558.349-21.837-.044-3.793-.219-7.542-.539-11.335-.685-2.363-.102-4.697-.189-7.075.248-.904.175-2.144 0-3.224-.175-.933-.175-.962-1.107-1.035-1.763-.467-4.559-.146-9.163-.219-13.722v-2.652c0-3.554.248-3.554 3.866-2.942 2.217.349 4.522-.146 6.783-.19 3.078-.073 6.141-.247 9.19-.145 3.953.116 7.892.116 11.845.189 4.45.117 8.927-.102 13.406.219 1.677.116 3.544.145 5.28-.321.584-.175 1.153-.117 1.678.219 2.29 1.573 4.45 3.292 6.2 5.506.831 1.049 2.334 1.282 3.588 1.675 5.12 1.647 10.328 1.355 15.565.962 2.772-.219 5.529-.495 8.183-1.224 3.224-.888 6.667-1.325 9.322-3.685.642-.583 1.357-.816 2.232-.86 3.297-.248 6.608-.583 9.905-.903.466-.044.962-.117 1.4-.073 1.619.175 3.166.029 4.799-.175 2.261-.277 4.625.248 6.929.292 3.808.116 7.615.116 11.451.174 1.678.03 3.516.539 5.019.175 4.478-1.151 8.854.437 13.347.029 6.812-.582 13.741.029 20.627.19 3.559.102 7.148.175 10.722.116 4.303-.043 8.65.117 12.953-.175 1.298-.072 1.138.641 1.007 1.399a55.364 55.364 0 0 0-.642 10.314c.029 1.063.277 1.967 1.211 2.287 1.006.32 2.013.67 3.121-.422 4.566-4.371 10.255-6.774 16.178-8.625 5.558-1.689 11.29-2.476 17.082-2.461 4.23.043 8.402.903 12.618 1.281 1.108.117 1.896.977 2.626 1.53 2.115 1.544 4.595 1.515 6.856 1.908 4.259.758 8.358 2.156 12.691 2.462.831.073 1.677.423 2.538 0 .117-.043.292-.174.423-.116 4.274 1.646 8.825 1.617 13.318 1.937 2.83.19 5.631-.072 8.432 0 3.807.102 7.498-.349 11.261-.713 6.915-.641 13.596-2.186 20.189-4.152 3.02-.903 6.025-2.185 8.505-4.269.467-.364.715-.976 1.079-1.5 1.036 1.18.642 2.608.642 3.904v-.029Zm15.565-30.694c-1.532 5.521-4.333 10.43-8.169 14.713-1.225 1.37-1.911 3.234-3.705 4.123-.496.248-.715 1.355-1.517.248-.102-.117-1.153.189-1.153.961 0 .889.044.961-.744.932-1.677-.043-2.304 1.472-3.399 2.287-1.721 1.282-3.515 2.142-5.747 2.506.686.758 1.444.291 2.071.743-.758.859-1.838.86-2.8 1.151-3.341 1.107-6.638 2.476-10.08 3.088-1.765.321-3.399 1.297-5.383 1.035-1.255-.146-2.626.786-4.099.815-3.939.073-7.863.117-11.758.539-1.4.175-3.048-.51-4.347.787-.423.422-.218-.83-1.298-.787-3.34.19-6.739-.043-10.08-.422-3.078-.35-6.127-.86-9.175-1.37-2.976-.495-5.952-1.063-8.942-1.427-1.62-.19-3.545-.321-5.062-1.18-.715-.393-1.182.422-2.072-.175-1.079-.757-.612-1.355-.321-1.748 1.649-2.214 2.699-4.88 5.062-6.599.467-.35.511-.743.102-1.399-.787-1.325-2.115-1.995-3.121-3.015-.934-.962-2.159-1.792-2.655-2.943-.642-1.442 1.283-1.865 1.94-2.768 1.969-2.724 4.201-5.23 6.418-7.764 1.007-1.151 1.036-1.865-.364-2.477-1.036-.495-2.145-.888-3.268-1.107-1.721-.35-2.932-1.646-4.522-2.258-1.05-.422-.467-1.18.146-1.894 2.728-3.263 6.374-5.885 8.14-9.775 1.356-2.972 3.005-4.02 6.024-3.365.934.19 1.43-.291 1.678-1.107.787.437-.044.903.219 1.326 4.449.116 8.898.364 13.318 1.107 1.794.291 3.472.757 5.164 1.398 1.838.685 3.807 1.137 5.747 1.399 3.02.393 5.777 1.602 8.607 2.578.175.044.292.219.467.248 3.092.35 5.893 1.69 8.781 2.68 3.545 1.224 7.134 2.229 10.664 3.395 3.311 1.078 6.958 1.049 10.371.218 1.109-.277 2.291-1.078 3.341-1.763.744-.495 1.079-1.398.642-2.359-.175-.35-.438-.831-.759-.044-.044.102-.219.247-.292.247-1.91-.976-1.896-.976-3.617.175-1.649 1.078-6.244.933-7.819-.277-.146-.101-.248-.291-.365-.32-4.376-.758-8.315-2.753-12.457-4.152-2.291-.757-4.8-.976-6.959-1.966-3.413-1.574-7.25-1.297-10.576-2.827-5.163-2.36-10.75-2.84-16.177-3.977-1.867-.364-3.661-.67-5.529-.539-.977.044-.539-.888-.685-.932-.788-.248-1.722-.35-2.378.117-.584.422-1.211.757-1.678.364-.437-.35.117-.976.292-1.442 1.765-4.72 1.867-9.557 1.109-14.466-.365-2.36.189-4.807-.744-7.124-.248-.641.35-.888.89-1.049 1.867-.582 3.559-1.573 5.455-2.156 2.947-.888 5.806-2.185 8.753-3.146 1.298-.423 2.728-.568 4.128-.568 4.799.029 9.613.043 14.412.32 3.443.19 6.988.364 10.328.962 3.866.684 7.819 1.15 11.554 2.432 4.449 1.545 8.315 4.094 11.524 7.561 1.181 1.282 2.655 2.229 3.734 3.686 1.401 1.923 2.582 3.904 3.705 5.987 1.911 3.467 3.589 7.022 5.412 10.503 3.56 6.978 5.748 14.218 3.633 22.07l-.015-.014Z" fill="#000"/></g><defs><linearGradient id="b" x1="52.665" y1="22.57" x2="298.433" y2="22.57" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="c" x1="206.875" y1="325.678" x2="382.708" y2="325.678" gradientUnits="userSpaceOnUse"><stop stop-color="#FF7139"/><stop offset="1" stop-color="#FFEA7F"/></linearGradient><linearGradient id="d" x1="206.875" y1="325.678" x2="382.708" y2="325.678" gradientUnits="userSpaceOnUse"><stop stop-color="#FF7139"/><stop offset="1" stop-color="#FFEA7F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h364.89v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-import.svg b/browser/components/newtab/data/content/assets/mr-import.svg
new file mode 100644
index 0000000000..93034912ec
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-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 width="337" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="m75.246 347.009 9.833-3.423 4.623-2.282 21.396 9.716 41.052 6.281h81.515l54.919-6.281 10.987-13.704h9.257l5.787 6.282-5.787 19.42-25.443 6.857h-63.024l-91.925 3.423-43.357-15.997-9.833-10.28v-.012Z" fill="url(#b)"/><path d="m246.803 42.957-6.351-14.103 7.622-7.046 11.433-5.129h8.257l5.717-10.257 12.716-6.41 8.892 15.385 6.352-4.481 15.256-4.494 10.798 7.058 5.082 13.468-3.812 12.175-12.08 9.621 5.082 14.75-5.082 17.315 5.082 5.776 1.27 7.692-3.176 8.328-71.811 3.2-1.27-7.693-2.541-11.54 6.352-7.057c-2.964-2.776-8.893-9.104-8.893-12.174 0-3.846-1.27-12.186 0-15.385 1.012-2.565 3.812-7.046 5.082-8.975l.023-.024Z" fill="url(#c)"/><path d="M227.348 73.034c.071-.776-.141-1.576-.917-1.682-4.505-.6-6.434-3.94-8.269-7.434-.918-.706-1.73-1.552-2.706-2.117-.106-.07-.164-.106-.235-.165-.341-.27-.341-.506-.165-.776.071-.106.141-.235.236-.341-1.518-1.141-3.282-.776-4.811-.235-3.929 1.376-5.658 5.281-8.599 7.834-1.258 1.07-1.894 2.728-1.658 4.575.2 1.376-.683 2.459-1.894 2.659-1.188.2-2.576-.071-3.317-1.318-2.27-3.905-5.352-2.152-7.046.306-2.541 3.67.341 8.54 5.081 8.88 2.341.165 2.918.942 2.129 2.753-2.305 5.376-1.693 7.128 3.588 9.822.576-.2 5.423 1.317 5.481 1.412 1.494.305 2.976.635 4.47.87 7.728 1.282 11.316-.435 14.492-6.822.27-.541.647-1.07.164-1.518-.541-.47-.882.2-1.352.4-2.365 1.047-4.776 1.718-7.211.035-.682-.505-1.494-1.011-1.223-1.811.306-.976 1.423-1.517 2.364-1.141 1.047.4 2.07.2 3.082.435 1.894.4 3.011-1.317 4.646-1.682 1.012-.27.341-1.788.271-2.588-.2-2.658.847-4.81 2.27-6.857.718-1.082 1.012-2.259 1.082-3.494h.047Zm-11.586.812c-.47.365-.953.706-1.423 1.047-.236.13-.471.306-.706.435a3.812 3.812 0 0 1-.741.4c-.2.106-.435.2-.682.27-.165.071-.377.106-.541.13-.741.2-1.588.2-2.506-.07-1.223-.342-1.658-1.071-1.658-1.989.035-1.211 1.258-1.211 2.305-1.482 1.765 1.376 2.847-.34 4.07-1.14.106-.071.235-.13.341-.2.165-.071.341-.13.506-.2.682-.165 1.282.035 1.694.54.07.106.141.2.164.342.142.4.036.835-.164 1.211-.141.27-.377.506-.647.706h-.012ZM198.189 98.488c5.528 1.612 11.056 1.871 16.503 2.506 1.023.117 1.505.258 1.023 1.152-2.012 3.588-1.741 7.434-1.306 11.21.2 1.612-.082 2.023-1.858 2.694-4.152 1.529-8.058.976-12.163.294-2.564-.412-5.175-4.152-4.575-6.611.905-3.658 2.764-7.093 2.328-11.21l.036-.035h.012ZM312.509 157.853v.059h.165l-.165-.059Zm9.434-14.103c-1.059 0-2.505-.035-2.788 1.682-.741 4.564-3.27 7.669-7.575 9.222-1.482.518-3.211 2.294-4.552.741-1.482-1.717.541-3.329 1.317-4.858.483-.941 1.318-1.717 1.447-2.846.13-1.33-.317-2.012-1.67-1.2-1.6.905-2.988 2.141-3.976 3.587-3.305 4.882-7.893 7.505-13.574 7.834-8.822.483-17.585 1.976-26.513 1.329-7.446-.517-14.95.036-22.396.389-1.576.058-3.176.188-4.752.317-.576.035-1.247-.188-1.447.741-1.129 5.176-4.14 9.316-7.634 13.104-.741.835-.482 1.352.059 2.105 2.67 3.823 6.481 3.694 10.233 2.659 8.799-2.459 17.656-4.6 26.255-7.799 4.105-1.553 8.41-2.529 12.644-3.752 4.047-1.2 8.317-1.424 12.292-2.976 1.953-.777 4.082-.388 6.035-.682 5.552-.812 11.139-1.518 16.491-3.27 2.211-.741 4.458-1.294 6.446-2.753 3.976-2.917 3.599-7.469 4.493-11.515-.388-.742.518-2.071-.835-2.071v.012Zm-12.68 14.821c-.294.071-.577.165-.871.259-1.352.423-2.658.976-4.105 1a4.862 4.862 0 0 1 1.094-.518c.224-.094.447-.165.671-.223 1.058-.295 2.152-.353 3.246-.553h-.035v.035ZM206.257 323.038c.718 1.105-.541 1.799-.576 2.776-.306.67-1.635.706-1.294 1.705.447 1.365.071 2.576-.682 3.612-.682.941.2.999.541 1.399 0 2.106-.717 4.211.447 6.246.341.635.106 1.306-1.165 1.471-6.457.87-12.821-.2-19.184-.706-2.423-.2-4.858-.235-7.693-.33 3.693-4.305 5.27-9.48 8.375-13.891 1.647-2.341 1.705-5.705 2.458-8.61.518-2 .988-4.012 1.576-5.976.377-1.306 1.271-1.941 2.741-1.741 5.505.706 11.116.871 16.48 2.435-.177 1.941.235 3.87-.953 5.811-.788 1.305-1.47 3.035-.612 4.74-.929 0-.412.706-.517 1.106l.07-.035-.012-.012ZM37.029 235.218c-1.8-2.847-4.34-4.729-7.834-5.329-1.6-.27-2.117-.694-1.87-2.587.411-3.647 1.8-6.987 2.776-10.457.553-1.918 5.822-5.493 7.904-5.493.659 0 1.106.235 1.494.658 6.281 6.823 15.056 9.234 23.549 12.08 1.976.659 2.258 1.165 1.317 2.847-1.352 2.517-3.058 4.764-4.61 7.116-1.871 2.847-3.718 5.694-5.823 8.375-1.07-.094-2.153 0-3.117-.623-4.305-2.752-9.187-4.434-13.81-6.622l.036.035h-.012Z" fill="#DB9646"/><path d="M57.602 363.584c-8.422 0-16.833-.164-25.22.094-2.893.059-5.916-.458-8.645.353-1.235.353-3.058-1.423-3.74.847-1.165-2.046-.753 0-1.071.388-.776.906-1.235.095-1.588-.458-.647-.977-1.306-1.53-2.27-.33-.294.388-.647.294-1.035.094-2.141-1.07-4.482-.258-6.693-.647-1.859-.329-3.611.941-5.458.33-.682-.224-1.859.164-1.859-.906 0-.941.353-1.788 1.659-2.141 2.635-.717 5.364-.611 7.999-1.105 3.446-.624 6.928-.2 10.374-.553 1.494-.165 3.282-.388 4.94-.294 3.506.2 7.023-.259 10.528-.165 7.634.259 15.315-.353 22.914.623.811.095 1.494.165 2.117.741.588.553 1.07 1.165.847 2.012-.259 1.035-1.165.812-1.918.847h-1.858v.259l-.023.011ZM301.182 24.783c-.611 1.165-.423 2.047-.388 2.929.035 1.106-.588 2.011-1.694 2.117-1.176.094-1.364-.94-1.458-1.882v-.223c-.588-6.2.258-7.117 6.469-7.023 1.165 0 2.341 0 3.482.13 1.035.094 1.717.682 1.658 1.847-.035 1.164-.882 1.329-1.752 1.4-.977.035-1.953 0-2.988 0 .388 2.305 2.529 3.575 3.282 5.622.164.482.553.588 1.27.553 2.529-.165 5.07-.353 7.634-.718.059-.682-.459-1.07-.847-1.529-.611-.717-.353-1.27.2-1.823.647-.647 1.306-.812 2.012-.094.294.259.611.482.882.753 1.141 1.2 3.799 1.493 3.54 3.317-.353 2.6-1.717 5.034-3.152 7.304-.388.647-1.2.718-1.882.388-.753-.329-.718-1.07-.553-1.623.329-1.105.424-2.47 2.141-2.529-1.165-1.2-2.4-.882-3.611-.717-2.141.294-4.258.517-6.399.776-2.012.259-3.223-.776-4.094-2.505-1.105-2.118-2.34-4.153-3.669-6.493l-.071.035-.012-.012ZM40.593 374.827c-2.635.553-7.482-.259-12.187.717-.811.165-2.081.165-2.27-1.035-.13-.941.165-1.529 1.459-2.011 2.823-1.106 5.422-2.141 8.48-1.071.46.165 1.142-.258 1.694-.588 1.4-.776 2.212-.482 3.353.847.13.165 1.035.718 1.035.071 0-1.365.976-1.271 1.717-1.365 4.482-.423 8.94-.647 13.421.059.906.165 2.012.13 1.988 1.659 0 1.694-1.494 1.305-2.176 1.364-4.81.518-9.622.812-16.514 1.365v-.012ZM210.339 76.95c-.459-.036-.906-.13-1.364-.095-1.235.036-1.694-.882-1.694-1.752 0-1.165 1.305-1.694 2.011-1.4 1.718.718 2.8-.224 3.905-1.106.906-.717 1.824-.752 2.435.07.718.883.13 1.624-.682 2.306-1.623 1.33-3.223 2.082-4.611 2.012v-.035ZM281.621 74.094c-.553.13-.906.26-1.27.33-4.388.482-4.741.164-4.741-4.294 0-3.61 1.835-5.67 5.493-6.175-1.011-1.2-1.846-2.34-2.823-3.376-1.035-1.164-.905-2.117.165-3.211 1.623-1.694 3.964-2.247 5.717-3.835 1.458-1.294 4.317 3.188 4.74 4.482.259-2.247.482-3.894.647-5.552.259-2.73.941-3.282 3.67-3.247 1.329 0 2.541.588 3.905.46 1.012-.095 1.459.776 1.329 1.787-.164 1.294-.423 2.6-.552 3.893-.071.553-.777 1.2 0 1.659.717.423 1.399.259 2.14-.2 1.306-.812 2.282-2.082 3.8-2.635.623-.223 1.199-.553 1.729-.13 1.329 1.142 1.623 2.93 2.599 4.294 1.235 1.788.518 3.153-1.27 4.294 3.835.329 4.646 1.364 4.035 4.94-.071.459-.295.882-.353 1.329-.436 2.682-2.024 4.093-4.776 4.223-.094.423.259.517.494.647 2.553 1.705 2.788 3.658.682 5.846-.553.553-1.07 1.14-1.588 1.717-1.305 1.459-2.693 1.459-4.034-.07a250.166 250.166 0 0 1-2.894-3.47c0 1.788-.329 3.246.071 4.481.717 2.376-.424 3.317-2.341 3.894-1.588.482-3.247 1.035-4.882 1.105-1.329.035-2.34-.906-2.246-2.564.059-1.294 0-2.6 0-4.188-1.823.941-2.6 2.53-3.705 3.741-.753.776-1.494.941-2.177.459a43.673 43.673 0 0 1-4.352-3.706c-1.623-1.623-1.235-3.058 1.329-5.551.459-.424.942-.753 1.33-1.436l.129.071v-.012Zm15.997-6.01c-.035-1.788-2.635-4.647-4.034-4.576-.33 0-1.024 0-1.788.553-1.471 1.282-1.247 1.27-1.553 1.847-1.658 2.082-.565 4.293 1.094 5.399 1.329.905 2.694.882 4.093.129 1.459-.776 1.882-2.117 2.176-3.34l.012-.012ZM285.973 14.291a4.729 4.729 0 0 0-.224.647c-1.917-.753-1.846 1.53-3.023 1.953-2.67.976-3.999 3.376-5.434 5.587-.647 1.012-1.27.776-2.117.482-1.106-.388-.977-1.035-.553-1.823 1.988-3.61 4.94-6.199 8.575-8.057 1.305-.647 2.211-.07 2.764 1.2l.012.011ZM279.962 29.559c-1.623-.094-1.788-1.165-1.564-2.176.776-3.188 6.304-7.081 9.692-7.21 1.459-.036.129 1.846 1.435 1.623.094.752-.353 1.364-.941 1.458-3.646.588-6.269 2.4-7.799 5.846-.129.259-.646.353-.846.459h.035-.012ZM265.036 35.475c-2.4.07-5.164.459-7.54 2.247-.847.647-2.012 1.435-2.8.223-.776-1.164.165-2.211 1.177-2.823 2.505-1.53 5.069-2.823 8.128-2.952 1.235-.07 2.27.258 3.281.752.624.295 1.365.718 1.012 1.788-.353.977-1.047.977-1.859.906-.294-.035-.623-.07-1.399-.13v-.011ZM262.601 26.348c.741.035 1.235-.036 1.458.517-1.27.459.683 2.376-1.035 2.47-3.282.165-6.175 1.659-9.233 2.53-.13.035-.353-.095-.424 0-.482.458-.682 2.046-1.623.776-.353-.483.294-1.882.941-2.659 1.694-2.082 4.187-2.47 6.563-3.117 1.165-.33 2.471.07 3.353-.482v-.035Z" fill="#010101"/><path d="m60.06 69 10.045-11.246 4.07-7.892 9.81-2.635 18.42 3.823 14.115-2.635h20.573l22.49 4.07 15.798-4.07 18.667-6.458 14.115 2.87 9.575 8.857v7.658h-3.353l-11.727 3.588-4.305 10.527-6.458-2.635-3.834 2.635v5.74l6.94 4.788 1.435 10.292 1.917 3.588v9.327l-11.245 6.705-19.385-3.352h-24.878l-24.89-6.223-28.477 15.068-22.725 4.305-16.515-4.305-9.093-8.857-3.105-17.232 9.328-15.315 12.68-11.01.012.023Z" fill="#010101"/><path d="M197.812 234.713c-1.399-.623-2.693.329-4.093.294-6.434 0-12.739-.882-18.95-2.435-1.623-.388-2.434-.223-3.611 1.071-6.269 7.128-13.268 13.562-20.149 20.102-5.199 4.94-10.528 9.657-16.421 13.856-4.74 3.388-9.586 4.094-14.821 2.835-6.857-1.658-13.915-2.376-20.737-4.105-9.14-2.306-18.362-4.235-27.337-7.316-5.787-1.988-11.762-3.388-17.679-4.976-1.917-.518-3.74-1.623-5.975-1.012-.588.165-2.012-1.011-.718-2.305.553-.553 1.012-1.176 1.53-1.753 2.046-2.14 1.858-3.223-.624-4.552-3.282-1.752-6.528-3.811-10.34-3.776-2.54 0-5.434.165-6.892 3.153-.388.776-1.588.905-2.306 1.658-4.681 4.811-8.422 10.316-11.633 16.139-1.2 2.14-2.952 3.117-5.164 3.317-3.999.353-7.246-1.494-10.304-3.811-.623-.459-1.011-1.236-1.011-2.047.035-4.623-.424-9.21 1.658-13.692 1.988-4.258 1.917-9.081 2.694-13.668.294-1.729.459-3.352 2.305-4.552 1.106-.682 1.07-3.094.624-3.999-.777-1.659-.26-2.894.329-4.094 3.117-6.634 5.234-13.762 9.293-19.937 1.564-2.377 4.163-3.518 6.892-2.729 2.341.647 4.458 1.729 6.246 3.352 2.047 1.882 4.164 3.67 6.729 4.811 3.317 1.458 5.105 4.658 7.61 7.022 4.458 4.199 10.304 5.658 15.762 7.846 1.435.588 3.023 2.282 4.258 1.435.941-.647.906-2.8 1.2-4.294.094-.588.458-1.011.482-1.729.13-2.305 1.717-2.764 3.835-1.658 4.128 2.176 8.257 4.387 12.644 6.081 4.388 1.694 8.846 3.023 13.292 4.493 4.188 1.4 8.481 1.824 12.845 1.141 1.917-.294 3.835-.329 5.752-.552 2.082-.259 3.246-1.435 4.587-2.706 3.964-3.834 6.529-8.622 9.458-13.209 2.599-4.105 5.105-8.293 7.41-12.527.612-1.141.588-2.671.741-4.035.647-5.364 2.635-10.245 5.27-14.903 1.141-1.988 2.117-4.035 3.799-5.693.718-.718-.459-1.459-1.106-2.118-3.246-3.258-6.857-6.21-9.421-10.116-2.247-3.411-2.012-3.54 1.435-5.728 4.775-2.988 8.998-6.669 13.268-10.339 5.105-4.388 9.657-9.34 14.433-14.08 3.705-3.67 6.857-7.846 10.892-11.222 1.035-.882-.13-1.176-.647-1.399-3.353-1.565-6.893-2.6-10.469-3.517-3.282-.847-6.375 0-9.528.846-5.881 1.494-11.539.33-17.161-1.599-4.223-1.435-8.446-2.894-12.775-3.964-4.74-1.177-9.421-.588-13.785 1.729-8.164 4.328-16.81 7.646-25.125 11.586-7.834 3.67-16.127 4.329-24.702 3.741-5.622-.353-10.433-2.282-14.656-5.529-4.223-3.223-7.375-7.775-8.975-12.692-2.729-8.422-.941-16.491 3.611-24.172 2.34-3.964 5.011-7.516 8.646-10.186 2.635-1.918 5.164-3.94 7.74-5.894 4.646-3.517 7.763-8.163 10.468-13.138 1.4-2.541 3.058-4.847 5.14-6.764 2.118-1.917 4.906-2.34 7.74-2.376 5.529-.07 10.822 1.176 16.127 2.47 4.517 1.07 9.139.753 13.586.07 6.21-.94 12.292-3.152 18.691-2.434 2.987.33 6.081.882 8.939.776 6.011-.258 11.151 2.635 16.774 3.517 4.058.624 7.892.294 11.833-.811 7.704-2.118 15.021-5.494 22.819-7.317 4.647-1.07 9.163-1.658 13.786.753 1.494.776 3.376 1.53 5.329 1.564 1.693 0 3.023 1.436 3.964 2.635 2.246 2.835 4.881 5.47 5.881 9.105.553 1.987 1.106 3.964 1.364 6.022.294 2.117 1.235 3.905 2.141 5.764.647 1.306 1.659 1.882 3.153 1.917 2.729.07 4.975 3.023 4.422 5.787-.423 1.953-.976 3.905-2.399 5.435-.977 1.047-1.4 2.34-1.071 3.646 1.659 6.705-2.046 14.927-9.292 17.373-.812.259-.906.883-1.071 1.6-.846 3.941-1.587 7.74.165 11.739 1.753 3.964 2.694 8.293 4.352 12.328.683 1.658 2.247.882 3.188 1.858 2.247 2.376 5.164 3.682 8.481 3.905.388 0 .811 0 1.164.13 2.435 1.07 3.929.682 3.153-2.306-.33-1.306 1.917-.906 1.011-2.141-1.07-1.47-1.494-3.117-1.399-4.916 0-.647-.589-.553-1.012-.683-5.658-1.623-8.74-6.116-11.669-10.704-.846-1.305.389-2.246 1.494-2.599 4.647-1.529 8.775-3.941 11.834-7.705 2.011-2.54 3.775-1.823 5.846-.553.352.224.682.624 1.141-.2.458-.846 1.364-.776 2.211-.094.459.353 1.035 1.141 1.788.389.588-.589.776-1.4.482-2.153a30.272 30.272 0 0 0-1.364-3.188c-1.918-3.905-1.659-7.975-.847-12.033.223-1.07.847-1.988 1.729-2.705 2.635-2.212 2.599-2.93.423-5.529-6.269-7.48-7.022-15.88-3.928-24.819.517-1.529 1.399-3.223 2.599-4.234 1.882-1.6 1.106-2.706.129-4.258-1.917-3.094-3.058-6.576-4.222-9.952-.388-1.07-.459-2.434.776-3.681 3.999-4.07 8.422-7 14.009-8.552 3.188-.882 6.176-1.564 9.422-1.2 1.106.13 1.529-.352 1.988-1.4 2.894-6.892 7.869-11.291 15.28-13.115 2.67-.647 3.446-.035 4.458 2.282 1.329 3.094 3.446 5.823 5.011 8.787.882 1.623 1.717 1.2 2.693.423 3.964-3.117 8.481-4.975 13.398-5.857 2.694-.483 5.199-.424 7.869 1.27 1.882 1.2 3.741 2.34 5.458 3.811 3.999 3.352 5.27 7.905 6.117 12.692 1.399 7.904-1.494 14.186-7.446 19.29-1.071.906-2.27 1.565-3.482 2.247-1.07.624-1.976.13-2.399-.517-.553-.882-.071-1.623 1.011-2.153 2.6-1.27 4.352-3.576 6.528-5.399 1.953-1.6 2.047-4.07 2.412-6.175.882-4.94.717-10.187-1.918-14.35-2.505-3.965-5.881-7.611-11.609-7.576-8.164.07-14.468 3.811-18.785 10.116-3.647 5.364-4.905 11.74-2.212 18.256.389.976.906 1.27 1.918 1.235 6.01-.294 11.762 1.105 17.161 3.576 2.176 1.011 3.929 2.564 5.07 5.234.906 2.176 2.047 4.458 2.952 6.705 2.341 5.893.624 11.586-1.587 17.079-.718 1.823-.883 2.705 1.035 3.94 3.799 2.47 4.775 7.81 2.964 12.692-.165.389.553.847.459 1.494-.259 1.788-1.141 3.13-3.118 4.294.353.717.906.647 1.588.482 3.447-.718 4.223.165 5.846 3.388 1.953 3.869 3.741 7.869 6.505 11.35 1.271 1.6 2.117 3.517 3.611 4.976 1.141 1.106 0 2.8-1.858 2.858-2.47.071-4.976.094-7.446 0-1.435-.035-1.952.459-1.917 1.882.035 3.153-.647 6.305-.682 9.399-.036 2.211.164 4.493-.095 6.728-.129 1.012.718.941 1.141 1.176 1.53.906 1.953 2.047 1.753 3.87-.294 2.694-.459 5.364-1.047 8.034-1.27 5.658-5.199 8.551-10.374 10.151-7.082 2.176-14.398 3.67-21.679 4.552-14.397 1.729-27.819 6.729-41.546 10.869-3.517 1.035-7.022 2.211-10.633 2.858-2.894.553-5.752 1.4-8.775 1.235-2.505-.164-4.387-.941-5.917-2.929-1.952-2.54-2.67-2.67-4.646-.094-1.106 1.435-1.952 1.365-3.317.683-3.282-1.694-5.822-4.329-8.516-6.764-2.541-2.305-2.823-2.435-4.293.718-.812 1.729-1.847 3.281-2.823 4.811-1.271 1.952-1.918 4.199-2.435 6.21-.553 2.153-1.035 4.552-.718 7.022.33 2.306 1.494 3.482 3.223 4.682 4.623 3.258 9.751 5.564 14.468 8.528 6.47 4.07 13.068 7.975 19.02 12.845 2.635 2.152 5.364 4.199 7.281 6.928 3.247 4.623 4.059 9.916 2.565 15.327-1.788 6.469-3.376 13.044-6.117 19.22-1.106 2.54-2.435 4.975-3.67 7.481-4.458 9.104-8.128 18.573-12.315 27.783-1.565 3.411-3.541 6.669-5.787 9.692-.353.483-.777 1.012-.906 1.6-.518 2.082-.718 4.035-2.988 5.399-1.4.847-1.953 3.059-2.858 4.658-1.271 2.212-1.753 4.752-3.376 6.799-.753.941-1.176 2.176-1.27 3.411-.095.977-.683 1.953 1.293 2.176 2.506.33 3.647 2.964 5.27 4.623 3.541 3.611 7.963 4.682 12.704 5.27 4.717.553 9.422.905 13.491 3.905 5.423 3.999 6.505 9.763 2.341 15.221 6.14-.13 12.163-.094 18.138-.624 2.823-.258 5.693-.517 8.516-.353 4.423.259 8.446-1.035 12.516-2.376 2.27-.752 4.611-1.27 6.728-2.564 2.858-1.753 4.093-4.787 5.881-7.316 2.012-2.894 4.2-5.399 7.705-6.576 3.905-1.305 9.163.906 10.821 4.682 1.271 2.835 1.435 5.764 1.106 8.751-.941 9.011-6.528 14.539-14.397 17.538-4.776 1.788-9.657 3.741-14.915 4.458.2 1.365 1.329 2.177 1.823 3.388 2.929 7.152-1.788 15.974-9.328 18.609-3.776 1.329-7.41 1.141-10.986.611-2.929-.423-5.787-1.882-7.317-4.975-.905-1.824-2.211-3.447-3.117-5.341-1.752-3.575-.976-6.74 1.4-9.657.294-.353.624-.682.906-1.07.07-.094 0-.294-.035-.388-5.788.294-11.504 1.011-17.327.611-7.081-.458-14.209-.682-21.325-.294-7.152.389-14.304 0-21.456.624-5.363.459-10.762.553-16.091.976-3.611.294-7.187 1.2-10.798.976-4.223-.223-8.351 1.235-12.609.589-.718-.13-1.882.094-1.071 1.623.847 1.588 1.294 3.387 1.847 5.105 1.694 5.305-1.235 8.657-5.07 11.551-2.176 1.623-4.74 2.634-6.951 4.293-2.6 1.917-9.105.518-11.869-2.153-.329-.329-.623-.776-1.012-.941-4.258-1.823-5.269-5.728-5.752-9.633-.494-3.905.165-7.705 3.153-10.739.094-.095.07-.295.094-.459-6.175-1.788-12.292-3.705-18.303-6.081-3.928-1.565-8.186-2.282-12.186-3.812-4.681-1.788-9.551-3.446-13.103-7.022-2.176-2.176-4.611-4.034-6.693-6.281-2.541-2.764-1.988-4.94.258-7.222 4.553-4.658 10.081-5.823 16.056-3.741 2.671.906 5.588 1.917 7.317 4.623.353.588.906-.33 1.435 0 1.823 1.011 3.799 1.694 5.564 2.964 1.011.718 2.634 1.329 3.999 1.564 4.587.812 8.94 2.435 13.586 3.059 5.587.776 11.045 2.376 16.644 3.317 1.858.294 3.87-.424 5.822-.588 4.388-.424 8.775-.2 13.104.482 1.847.294 3.446.2 5.27-.294-3.023-2.764-2.953-6.023-1.788-9.398 1.717-4.976 4.646-9.269 7.41-13.692 3.153-5.105 5.987-10.375 7.022-16.456.389-2.176 1.106-4.364 2.047-6.375.882-1.953-.294-2.412-1.588-2.565-2.952-.353-5.846-1.07-8.81-1.658-1.2-.224-2.211-.812-3.058-1.459-1.2-.882-1.918-2.141-.718-3.776 5.623-7.422 10.14-15.42 14.009-23.878 3.929-8.622 7.317-17.408 10.363-26.348 1.459-4.329 1.918-8.916 2.141-13.504a47.19 47.19 0 0 1 .165-2.246h.129l-.059-.059Zm20.15-176.192c-1.035-1.177-1.718-2.212-2.012-3.388-.882-3.811-3.705-6.246-6.634-7.999-6.893-4.093-14.362-5.27-22.172-2.47-5.493 1.988-11.022 3.905-16.55 5.858-6.34 2.282-12.869 3.317-19.315 1.012-12.292-4.459-24.666-4.423-37.217-1.659-5.716 1.27-11.468 1.753-17.197.165-4.716-1.306-9.492-1.823-14.303-1.306-3.964.423-8.128.459-10.469 4.976-3.67 7.151-8.81 13.174-15.28 18.02-6.669 4.976-11.15 11.68-14.985 18.867-3.188 6.023-1.952 12.069.624 17.891 2.27 5.176 5.787 9.304 11.15 11.716 3.741 1.658 7.67 2.211 11.61 1.988 3.023-.165 6.081-.424 9.14-1.33 3.776-1.105 7.704-1.599 11.445-2.987 2.694-1.012 5.164-2.412 7.763-3.541 4.905-2.211 10.045-3.834 14.856-6.375 9.422-4.94 19.021-4.623 28.572-.224 3.67 1.694 7.481 2.765 11.539 2.8 2.247 0 4.517.423 6.669-.482 1.753-.753 3.517 0 5.329-.424 5.787-1.4 10.692 1.953 15.926 3.353 3.482.941 6.952 1.364 10.399.646 5.14-1.046 9.821-6.469 10.245-11.774.165-1.882 1.07-4.293-1.823-5.305-.389-.13-.683-.847-.847-1.364-.882-2.8-1.659-5.658-.777-8.622.389-1.306-.164-1.624-1.176-1.953-2.541-.882-4.717-2.082-5.458-5.07-1.105-4.458-.517-7.057 2.565-8.398 2.082-.906 4.328-1.07 6.528-.07.482.223 1.141 1.034 1.588.223.588-1.012.753-2.176 1.588-3.153.905-1.035-.294-3.834 2.729-3.187.258.07.482-.165.329-.424-.812-1.458.682-1.564 1.27-1.917 1.718-1.035 3.647-1.788 5.399-2.8 2.694-1.564 5.623-1.364 8.905-1.329l.035.07.012-.034Zm-77.951 139.422c-.224 4.976 2.929 9.504 6.505 13.692 3.446 4.034 7.61 7.187 12.221 9.986 6.211 3.741 12.257 7.446 19.573 8.622 6.505 1.035 12.974 2.247 19.596 1.271 1.365-.2 2.271.458 2.6 2.14.647 3.412 0 6.764-.388 10.081-1.035 8.916-5.011 16.95-8.058 25.243-1.493 4.034-3.317 7.904-5.105 11.809-3.246 7.152-7.116 13.892-11.962 20.067-.906 1.177-.553 1.565.588 1.859 4.258 1.035 8.481 2.246 12.845 2.541 6.14.388 12.221.976 18.232 2.246 2.599.553 4.905-.388 7.246-.976 1.235-.294 1.07-2.341 1.693-3.541a28.256 28.256 0 0 1 1.624-2.799c2.411-3.67 4.422-7.552 6.175-11.551 3.411-7.81 6.47-15.809 10.434-23.325 4.222-8.034 7.022-16.492 9.527-25.114 2.141-7.422.294-13.797-5.422-18.808-6.799-5.952-14.562-10.539-22.232-15.221-4.587-2.799-9.422-5.14-13.974-8.104-3.352-2.176-4.975-4.882-4.646-8.681.2-2.012-.482-1.659-1.917-1.4-3.776.682-7.575 1.494-11.445 1.012-5.917-.753-11.61-2.376-17.197-4.423-5.846-2.117-11.245-4.94-15.668-9.398-1.341-1.341-2.533-1.243-3.576.294-.223.329-.459.588-.682.905-4.093 6.246-6.599 13.01-6.564 21.573h-.023Zm75.481-64.283c1.235-5.858 1.399-11.257-1.165-16.491-.459-.941-.811-.588-1.294-.294-2.046 1.27-4.328 1.882-6.728 1.988-4.129.165-7.481-1.565-10.339-4.423-.459-.459-.753-1.529-1.824-.753-3.928 2.929-8.48 3.447-13.197 3.388-.612 0-1.165-.165-1.753.682-3.246 4.682-7.669 8.328-11.374 12.586-5.952 6.834-12.645 12.857-19.597 18.644-3.317 2.764-6.857 5.199-10.469 7.646 2.671 3.74 6.176 6.54 9.105 9.892 4.199 4.811 8.516 9.563 14.268 12.527 1.105.588 1.952 2.247 2.376 2.118 2.564-.777 4.481.846 6.528 1.529 7.152 2.411 14.339 3.834 21.879 2.764 3.023-.424 5.916-.906 6.951-4.788.424-1.529.753-3.387 1.953-4.716 1.494-1.624 1.717-4.035 3.023-5.635 2.247-2.729 1.106-4.128-.906-6.151-3.705-3.647-6.399-8.164-9.234-12.492-2.987-4.553-4.905-9.563-5.363-15.068-.094-1.306.094-2.435 1.529-2.576 1.494-.13 1.623 1.176 1.658 2.282.094 3.74 1.4 7.151 3.059 10.374 5.787 11.292 14.432 20.173 24.113 28.172.612.517 1.07.882 2.141.2 3.576-2.212 5.881-5.493 8.187-8.822 2.27-3.259 3.411-6.928 4.352-10.763.388-1.6.2-2.211-.812-3.188-4.164-3.964-8.998-7.022-13.621-10.41-3.058-2.246-5.423-5.046-7.34-8.257-.682-1.141-.329-2.247.518-2.835 1.141-.776 1.846-.035 2.211 1.2.165.518.647.941 1.165 1.623v.047Zm-78.304 67.894c-4.423 6.34-7.611 13.468-12.61 19.42-1.917 2.282-3.705 5.176-6.563 5.917-5.235 1.329-10.657 1.752-16.092 1.106-4.716-.553-9.233-1.918-13.68-3.612-5.563-2.082-11.315-3.74-16.444-6.763-2.27-1.329-2.246-1.365-2.764 1.27-.753 3.647-1.623 7.293-3.446 10.54-2.435 4.364-5.07 8.622-7.999 12.656-1.53 2.117-2.082 4.752-4.352 6.47-1.788 1.399-1.365 1.658 1.07 2.434 4.129 1.33 8.352 2.082 12.48 3.353 7.505 2.282 14.95 4.658 22.597 6.505 10.986 2.67 22.137 4.658 33.182 6.998 2.376.518 4.846.718 6.893-.623 2.987-1.917 6.246-3.447 8.845-5.858 8.481-7.81 16.962-15.644 25.031-23.913 1.294-1.33 2.341-3.259 4.199-3.811 1.2-.353 1.035-1.141 1.294-1.824.33-.976-.553-1.141-1.105-1.435-4.035-2.082-7.964-4.364-11.834-6.704-8.775-5.305-15.244-12.457-18.655-22.185l-.035.036-.012.023Zm175.557-52.085c2.67-.459 3.541-2.282 4.129-4.328.588-2.141.905-4.423 3.282-5.529.846-.388.482-1.235.482-1.882.129-4.846.094-9.692.329-14.539.13-2.834.165-2.987-2.729-2.564-9.692 1.494-19.443 1.988-29.218 2.412-5.14.2-10.269 0-15.409.094-5.293.129-10.598-.518-15.892-.388-1.917.07-3.023-.389-3.964-1.953-1.364-2.282-2.987-4.458-4.352-6.728-1.988-3.353-5.14-5.788-6.893-9.269-.388-.753-1.035-1.071-1.693-.977-.777.095-.718.941-.624 1.565.459 3.611-.329 7.222-.294 10.833.035 6.152.682 12.292.329 18.479-.058 1.235.071 1.271-1.141 1.788-.517.224-.329.882-.2.941 1.659 1.012 1.165 2.376 1.365 3.964.482 4 .294 7.975.388 11.939.035 1.882.647 2.118 2.341 2.082 5.399-.2 10.786-.847 16.221-.847 6.269 0 12.55.847 18.82.059 4.811-.588 9.622-1.176 14.433-1.564 3.058-.224 5.622-.847 7.633-3.153.647-.752 1.271-1.529 1.918-2.282 1.788-2.082 3.705-4.034 6.14-5.469 1.717-1.012 3.152-.624 4.517.329 1.305.918 1.564 2.412 1.235 3.905-.224 1.012-.682 1.953-1.141 3.153l-.035-.071h.023Zm-1.953 199.318c0-2.047-.611-3.964-1.07-5.893-.329-1.435-1.823-1.917-2.823-2.8-.882 1.047-1.694.353-2.694.2-2.305-.353-4.422 0-6.081 2.176-1.329 1.73-2.564 3.612-3.446 5.435-2.212 4.493-6.246 6.046-10.34 7.516-2.858 1.047-6.175 1.07-8.845 2.411-7.246 3.612-14.95 2.377-22.49 2.929-3.906.294-7.87-.094-11.704 1.047-2.117.624-3.247-.2-3.411-2.341-.094-1.105-.459-1.305-1.529-1.399-2.823-.259-5.623.094-8.446-.224-2.4-.259-4.882-.259-7.246.071-7.634 1.105-15.279 1.658-22.984 1.564-1.976 0-4.035-.329-5.952-.2-6.469.494-12.939.094-19.408-.164-1.365-.059-.259-1.659-1.459-1.53-1.164.13-.517 1.859-1.752 1.882-2.471.036-4.682 1.365-7.281.977-2.212-.33-4.517-.165-6.764-.036-7.869.459-15.574-.494-23.243-2.046-3.776-.777-7.481-1.918-11.28-2.564-5.011-.847-9.657-2.706-13.88-5.305-4.482-2.765-8.81-5.635-14.268-5.729-2.012-.035-4.035.353-6.082.459-1.329.059-2.693 1.329-2.987 2.894-.33 1.658 1.105 2.564 2.117 3.517 3.505 3.352 8.222 4.552 12.48 6.504 1.717.777 3.447 1.788 5.293 2.153 5.27 1.011 10.01 3.411 14.915 5.364 3.906 1.529 7.634 3.411 11.834 4.069.423.059.976-.223.846.612-.07.518.389.812.647.388 1.036-1.882 2.376-.517 3.353-.2 1.305.459 3.023-.164 3.905 1.435 1.106-1.494 2.764-.682 3.929-.588 5.199.424 10.374.094 15.538.094 1.694 0 3.376.2 5.105.094 10.304-.458 20.538-1.917 30.853-2.411 1.494-.071 2.988.059 4.517-.07 4.352-.33 8.716-.13 13.069-.483 2.564-.223 5.105.094 7.634-.129 2.893-.259 5.846-.13 8.739-.2 5.846-.094 11.61 1.011 17.456.588 1.917-.129 3.929-.423 5.752-.035 1.329.294 2.399 1.235 3.446-.353 0-.035.294.094.424.094 5.693-.094 11.374-.259 17.067-.329 4.776-.071 9.493-.036 14.233-1.141 4.905-1.141 9.716-2.506 14.268-4.517 6.528-2.894 9.822-7.352 10.081-13.857l-.036.059v.012Zm20.479-231.489c-2.011-3.352-3.646-6.046-5.269-8.751-.2-.329-.483-.623-.812-.776-1.788-.977-3.317-3.094-3.317-4.388-.071-3.776-2.635-2.505-4.223-2.505s-3.246.094-4.87.2c-4.352.259-8.68.682-13.033.811-5.14.13-10.245.718-15.338.883-5.493.164-11.081.164-16.55.588-4.94.388-9.845.164-14.762.482-2.341.165-4.717 0-7.223 0 .647 1.658 1.859 2.435 2.729 3.482 2.694 3.281 5.141 6.728 7.117 10.48.517.977 1.176 1.494 2.47 1.623 7.316.683 14.633.812 21.973.777 5.01 0 10.01-.682 15.02-.682 7.611 0 15.115-.906 22.596-1.988 1.2-.165 2.694.482 3.576-.459.977-1.07 2.412-.882 2.929-.553 2.176 1.459 4.352-.094 7.023.753l-.036.035v-.012Zm-7.246 26.902c-.458-.589.483-1.988-.976-1.859-.976.071-2.411-.094-2.67 1.564-.882 5.788-4.846 8.622-9.975 10.34-.905.294-1.823.717-2.54-.165-.718-.847-.259-1.752.2-2.599.776-1.4 1.658-2.765 2.434-4.2.459-.776.683-1.858-.035-2.34-.647-.459-1.623.07-2.247.647-1.164 1.105-2.47 2.117-3.375 3.387-3.059 4.458-7.281 6.928-12.551 7.517-5.752.646-11.504 1.235-17.291 1.529-8.293.423-16.574-.624-24.866.094-4.353.353-8.74.329-13.104.494-.682 0-1.364-.13-1.588.905-1.106 4.882-3.799 8.881-7.187 12.457-1.106 1.176-1.27 2.047.071 3.188 1.435 1.235 2.435 3.223 4.846 2.505 1.658-.517 3.223.459 5.07-.164 8.774-2.894 17.843-4.788 26.524-7.999 4.164-1.529 8.552-2.541 12.845-3.776 4.129-1.2 8.481-1.529 12.551-3.023 1.917-.717 3.929-.423 5.822-.647 5.952-.776 11.963-1.588 17.68-3.517 1.917-.647 3.928-1.2 5.657-2.47 4.129-2.999 3.741-7.646 4.647-11.904l.07.036h-.012ZM212.08 97.902c5.105.482 8.552-1.047 11.081-7.023.2-.458.388-.94 0-1.27-.424-.33-.776 0-1.2.259-2.141 1.106-4.352 1.859-6.669.388-.777-.482-1.882-.906-1.494-1.988.353-1.011 1.4-1.305 2.541-.976.882.259 1.823.259 2.728.388 1.788.224 2.894-1.306 4.458-1.729.777-.2.259-1.753.165-2.54-.259-2.541.812-4.518 2.117-6.447.718-1.035.977-2.176 1.106-3.387.094-.847-.259-1.659-1.035-1.788-4.517-.718-6.469-3.94-7.869-7.775-.647-1.788-2.047-2.506-3.799-2.435-2.565.07-5.07.647-6.952 2.435-2.929 2.729-6.634 4.916-6.505 9.822.035 1.752-2.082 2.599-3.705 1.729-.941-.518-1.823-1.2-2.729-1.788-1.27-.812-2.6-.33-3.705.094-1.106.423-1.141 1.752-1.012 2.893.2 1.824.623 3.482 2.435 4.423 3.517 1.823 5.564 4.129 4.329 8.657-.777 2.835 1.199 5.176 4.164 6.211 3.705 1.306 7.634 1.459 11.48 1.917l.094-.094-.024.024Zm77.234-7.093c2.694.2 5.564-.07 8.351-.753 4.258-1.047 7.775-3.446 10.528-6.728 6.34-7.481 10.469-15.75 7.116-25.866-1.27-3.811-2.764-7.705-7.057-9.434-5.917-2.376-11.998-3.575-18.303-2.082-7.999 1.882-13.809 6.576-16.903 14.35-.259.648-.306.306-.706 2.342-.47 1.929-.317 1.387-.517 2.822-.294 1.859-.341 3.259-.341 4.894 0 1.635.223 3.223.494 4.81 1.529 8.658 6.634 16.821 17.326 15.68v-.035h.012ZM28.948 227.291c-.388 1.788 1.165 1.435 2.047 1.623 4.458 1.106 6.599 3.223 7.116 7.446.094.776.424 1.2 1.035 1.27 4.717.612 8.516 3.352 12.61 5.399.976.494 1.105.259 1.588-.611 1.858-3.223 4.187-6.117 6.046-9.34 1.364-2.376 3.023-4.587 4.258-7.058.906-1.788.517-2.176-1.27-2.834-7.905-2.835-16.092-5.176-21.914-11.81-.424-.494-.941-.882-1.624-.682-3.023.847-5.975 2.376-7.116 5.175-1.459 3.576-2.8 7.387-2.823 11.457l.035-.035h.012ZM176.746 337.93c2.693.2 5.199.482 7.704.588 5.787.224 11.504 1.365 17.362.518 1.564-.224 1.694-.753 1.27-1.859-.553-1.4-.647-2.764-.459-4.258.294-2.152 1.953-3.834 1.753-6.152-.259-2.67.717-5.046 2.082-7.351 1.658-2.835 2.952-5.858 4.517-8.975-2.694.517-5.105.553-7.481-.388-1.035-.424-2.176-.812-3.282-.906-2.858-.259-5.787-.165-8.646-.518-2.046-.258-2.764.33-3.411 2.306-1.823 5.728-2.211 11.845-5.787 17.079-2.117 3.058-3.576 6.599-5.658 9.928h.036v-.012ZM287.197 32.666c-1.459.977-1.624 2.67-3.117 3.153-.906.294-1.624.223-1.918-.647-.294-.812 2.47-5.14 3.317-5.046 1.823.164 2.306-1.07 2.67-2.341.847-2.988 2.376-5.623 4.035-8.199.482-.753.459-1.105.035-1.788-1.752-2.893-3.67-5.728-5.069-8.786-1.071-2.376-2.376-2.306-4.388-1.565-6.505 2.376-9.622 7.575-11.704 13.727-.094.294-.258.459 0 .941 3.282 6.47 6.399 13.045 9.693 19.55 1.717 3.481 1.952 3.481 5.422 1.988.494-.2 1.012-.424 1.529-.483 1.33-.13 1.624-.482 1.071-1.882-1.071-2.6-1.882-5.34-1.529-8.586l-.036-.036h-.011Zm-6.729 14.092c-.258-.482-.423-.941-.717-1.27-1.106-1.27-1.847-2.706-2.6-4.2-3.093-6.21-6.399-12.292-9.139-18.667-.2-.482-.259-1.047-1.012-1.047-2.305 0-4.587-.223-6.893.353-4.552 1.141-8.316 3.835-12.386 5.952-.623.33-2.341 1.623-1.658 3.317 1.364 3.411 2.693 6.87 4.058 10.28.294.718.647.883 1.435.46 3.152-1.824 6.246-3.483 10.269-3.13 1.717.165 3.87 1.036 5.716-.223.13-.094.588.13.812.33 3.317 2.67 7.375 4.551 9.363 8.68.259.518.753.976 1.235.259.388-.588 1.529-.07 1.529-1.012l-.035-.094.023.012Zm-11.927 28.948c.459-1.177.094-2.176.129-3.153 0-.588-.294-6.022-.776-.623-1.894 1.835-3.093.847-3.352-1.73-.259-.975-.753-.752-1.529-.776-3.059-.2-4.905 2.082-7.281 3.282-.612.294-1.071 1.047-1.824.518-.611-.459-.717-1.2-.588-1.918.13-.588.259-1.234.588-1.752 1.141-1.753 0-3.388-.164-5.07-.059-.517-.483-.905-1.165-.388-1.529 1.141-3.058.388-3.67-.847-.811-1.6.812-2.211 2.047-2.729.941-.388 1.529-.847 1.494-2.011 0-1.141-.482-1.6-1.529-1.917-1.071-.33-2.412-.812-1.753-2.412.553-1.4 1.659-1.364 2.929-.812.517.224 1.235 1.106 1.694 0 .353-.882 2.046-1.493.647-2.834-.553-.518-.553-1.235-.683-1.918-.164-.882.259-1.364.906-1.623.588-.223 1.165-.2 1.494.624.224.552.718.976 1.07 1.494.389.552.718 1.4 1.588.94.741-.388 1.977-.164 2.047-1.529 0-.458.224-.882.353-1.305.294-.883.482-1.953 1.788-1.624 1.235.294 1.529 1.177 1.2 2.341-.2.682-.33 1.435.588 1.753.776.259 1.329-.165 1.788-.753.2-.259.388-.482.553-.753.494-.811 1.105-1.788 2.117-1.105.882.588 1.306 1.693.647 2.834-.588 1.035-1.435 1.953-.353 3.317 1.011 1.306 2.047.26 3.023.33 1.4.094 3.376-3.023 2.729-4.035-2.859-4.328-6.728-7.057-12.022-7.74-7.634-1.011-15.891 6.576-17.102 13.269-.553 3.152-.353 6.245.223 9.233 1.659 8.622 7.669 13.14 16.444 11.94 1.882-.26 3.705-1.177 5.752-.33l-.07-.2.023.012Zm-31.594 279.056c1.141.036 2.246.13 3.246-.647 2.506-1.952 2.635-6.34.259-8.586-.682-.647-.882.07-1.27.329-2.565 1.6-5.164 2.858-8.223 3.517-5.493 1.141-11.056 1.6-16.608 2.211-1.694.2-3.647 1.753-5.105-.552 0-.036-.518.07-.588.2-.883 1.823-2.506.905-3.612.752-3.246-.482-6.469-.329-9.692-.352-7.61 0-15.209.552-22.725-1.047-1.718-.353-1.435.458-1.2 1.364.553 2.282 3.446 4.517 5.787 4.493 13.621-.258 27.278.553 40.828-1.529 6.305-.941 12.61-.07 18.914-.094l-.035-.035.024-.024Zm23.337-258.625c.258-1.658-1.106-.776-1.694-1.07-1.4-.623-2.858.2-4.293-.165-.777-.2-1.588-.353-1.824-1.235-.2-.847.33-1.435 1.035-1.917 1.141-.776 2.212-1.73 3.412-2.376 1.235-.682 1.364-1.6.882-2.635-.33-.682-.2-1.364-.388-2.011-.389-1.141-.389-2.306.647-2.894 1.07-.623 1.787.482 2.47 1.141 1.399 1.306 2.67 1.953 4.164.094.517-.647 1.294-1.07 1.976-1.6.753-.552 1.435-.623 2.305-.094.883.518.847 1.106.753 1.953a4.99 4.99 0 0 1-1.106 2.705c-1.846 2.247-.458 3.682 1.036 5.176.882.847 2.082 1.459 2.305 2.835.259 1.729-1.176 1.917-2.247 2.411-.129.07-1.693.224-1.435-.259-2.317-.388-3.905.47-4.752 2.564-.129.295-.259.553-.388.847-.423.883-.717 1.306.812 1.4 3.246.259 6.375-.2 9.551-.647 1.529-.2 2.541-.647 3.152-1.882.977-1.952 1.624-4 1.588-6.21 0-.553-.035-1.012-.611-1.365-5.164-3.388-7.834-8.293-8.646-14.574-1.07 2.835-3.646 2.082-5.493 2.835-3.188 1.27-6.564-.847-9.951.623-2.859 1.27-4.482 2.965-3.929 6.023.329 1.823 1.07 3.576 1.165 5.399.164 2.8 2.764 4.917 2.011 7.87-.094.329.165.752.459.681 2.599-.682 4.846 1.729 7.704.847-1.529-.847-.906-3.117-.717-4.422l.047-.048Zm51.167 1.73c.906.07 1.882.458 2.729-.294 3.67-3.259 4.776-8.681 2.67-13.116-.294-.623-.588-1.27-.882-1.882-.329-.682-.647-1.658-1.435-1.623-.459 0-.976.847-1.364 1.4-1.883 2.6-4.223 4.681-6.693 6.763-2.859 2.435-6.117 3.835-9.622 4.364-2.6.388-5.293 1.141-8.058-.035-1.493-.647-3.352-.977-5.105-.682-1.141.2-2.764.329-2.693 1.658.094 1.953-1.071 3.87-.188 5.787.423.883 1.235.33 1.846.094 4.646-1.529 9.493-1.4 14.304-1.529 1.035 0 1.788 1.012 2.764.624 3.799-1.6 7.893-.647 11.762-1.53h-.035Zm-105.746 17.632c1.329-.624 3.023-.094 4.611-.718 1.659-.623 2.506-1.035 1.988-3.187-.647-2.765-.329-5.858.612-8.423.776-2.152-.259-1.882-1.365-2.046-2.988-.424-6.046-.553-8.998-1.2-1.624-.353-2.082.07-2.118 1.494-.094 2.599-1.105 4.881-2.399 7.093-.459.776-1.365 1.599-1.071 2.564.494 1.564 2.118 2.435 3.247 3.317 1.27 1.012 3.505.753 5.493 1.07v.036Zm13.68 14.115c-.882 1.823-.2 3.834-.882 5.305-.976 2.117.223 2.858 1.4 3.776 3.246 2.564 6.563 5.105 10.268 7.057.518.259 1.2.353 1.365 1.106.482 2.176 2.47 2.894 3.999 4.07 1.529 1.176 1.753 0 1.788-1.012.035-3.54-.035-7.093-.129-10.669 0-.364-.036-1.105-.624-1.07-1.235.094-1.2-.623-1.105-1.458.094-.883-.847-1.33-1.106-1.2-.753.388-1.823-.753-2.082.129-.847 2.635-2.141.388-3.188.353-.353 0-.753-.647-1.305-.847-3.153-1.141-5.846-2.988-8.422-5.634v.094h.023ZM23.349 199.613c-2.211-.223-6.34 4-6.14 6.599.2 2.764-.682 5.14-1.988 7.387-1.364 2.376-2.6 4.811-3.094 7.446-1.305 7.516-4.034 14.644-5.493 22.125-.905 4.717-1.882 9.363-1.752 14.186.035 1.882.717 3.023 2.764 3.352-.294-1.858-.623-3.575-.459-5.434.353-3.87 1.07-7.681 1.106-11.586.035-2.47.223-5.011 1.458-7.222 2.67-4.917 3.706-10.375 5.564-15.586 1.07-2.964 1.012-6.211 2.564-8.975 1.27-2.211 1.883-4.681 2.435-7.093.483-2.117 1.459-3.775 3.023-5.175v-.035l.012.011Zm214.374-81.432c-1.729-.459-1.364-1.882-1.27-3.023.258-2.859-1.012-5.952 1.141-8.587.329-.424.423-1.176-.294-1.623-.483 1.141-2.212.423-2.506 1.399-.459 1.494-1.788 1.788-2.729 2.635-1.305 1.177-4.07.977-4.164 2.835-.094 1.882 2.306 2.929 3.517 4.423 1.165 1.458 2.929 2.435 4.941 2.635.552.07 1.105 0 1.364-.718v.035-.011Zm31.3 259.236c-.552.647-1.141 1.235-1.588 1.882-1.987 2.764-1.293 4.494 1.882 5.599 1.659.588 3.153-.329 4.741-.035 2.011.353 2.564-.882 2.635-2.564.07-1.306-.612-2.341-1.33-3.388-.882-1.235-1.823-1.494-2.693-.165-.777 1.141-1.4.589-2.082.036-.553-.459-1.035-.941-1.529-1.4l-.036.035Zm-120.955 6.54c0-2.411-3.799-4.846-5.975-3.811-.294.165-.624.424-.388.682 1.988 2.118-.389 2.506-1.365 3.447-1.2 1.176-1.141 3.352.2 4.129 3.023 1.729 7.505-.906 7.505-4.459h.035l-.012.012Zm2.859-7.61c3.117 3.999 1.564 8.234 1.105 12.456 4.258-5.469 3.835-11.162-1.105-12.456Zm113.556-316.65c0-1.106-1.717-3.223-2.529-2.858-1.012.458-2.435.811-2.635 2.281-.094.753 2.729 3.682 3.376 3.447 1.2-.482 1.753-1.53 1.788-2.858v-.012Zm16.679 319.59c.589-2.47 1.012-4.752-.129-6.41-.847-1.2-2.635-.259-4.093.482 1.752 1.694 3.317 3.317 4.222 5.917v.011Z" fill="#010101"/></g><defs><linearGradient id="b" x1="75.246" y1="337.316" x2="314.615" y2="337.316" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="c" x1="240.452" y1=".012" x2="332.577" y2=".012" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h336.411v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-mobilecrosspromo.svg b/browser/components/newtab/data/content/assets/mr-mobilecrosspromo.svg
new file mode 100644
index 0000000000..d613d4bdca
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-mobilecrosspromo.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="329" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="m23.505 208.196-4.355-6.762 4.355-3.862 9.18 1.936 9.67 4.344-2.899-8.698-.963-4.836h7.736l6.28 4.836 2.899-1.444.481-5.318 2.418-3.862 3.381 3.862 5.799 4.836 3.862-5.798 3.38-3.863 7.254-2.899 2.418 2.899 3.862 2.9 2.418-3.863 8.217-1.936 1.444 1.936-1.444 7.736-2.418 7.242 7.254-4.343 10.634-.963-.963 8.217-3.862 7.735-11.597 11.597 9.179 10.624.963 9.66-13.534-2.417v-2.418h-3.862l-6.28-2.9-.963 12.561-3.862 10.623-9.672-7.735v-8.698l-9.671 7.243-2.9-11.116-7.253 4.836-15.952 6.28 4.354-14.015 5.8-10.634-5.8-1.937-6.761-5.799.963-2.417-9.18-3.381-.01.011Z" fill="url(#b)"/><path d="m139.79 298.2 4.632-6.173 5.146-1.027 8.228 4.632 16.465 2.568 16.979 2.054 16.465 4.633 9.254 8.227 6.173 7.714 1.027 9.254 2.568-3.092 5.659-2.054 2.568 2.054 1.027 6.687-3.595 6.173-2.054 10.292-9.254 11.833-6.173 1.027v-5.66l-11.833 6.687v-6.687l5.66-4.632-1.027-2.568 2.567-4.633-8.227-5.659-3.081 11.833-4.633 5.659-18.005 12.346-2.054-2.054 2.054-5.659-11.319 2.054-7.201-1.027-1.027-3.606 3.606-2.054 10.805-3.081-3.594-4.119 3.594-3.595 12.347 1.541 5.659-8.227-8.741 2.567-9.254-2.567-10.806-6.174 4.633 9.779-4.633 3.092-8.227-1.027-15.941 7.2-3.081-2.568 3.081-3.594-1.54-4.119H128l6.687-2.568 13.373-1.541 8.741-6.686-7.2-8.741-18.006-14.4v-5.66l8.227-4.632-.032-.022Z" fill="url(#c)"/><path d="m183.01 41.256-1.54-3.766 4.868-3.135 3.134 4.333-1.112 2.654-5.35-.086Z" fill="url(#d)"/><path d="m186.477 25.795-3.702-2.739-1.07-.021 3.274-3.691 4.814.075 1.519 5.37-4.835.995v.011Z" fill="url(#e)"/><path d="m170.515 20.178-3.681-3.809h-.535l4.355-4.215 6.43-.963-.129 7.49-6.44 1.497Z" fill="url(#f)"/><path d="m163.796 38.796 2.567 6.462-6.462 2.567-.941-8.034 1.658-3.178 3.178 2.194v-.011Z" fill="url(#g)"/><path d="m150.893 42.335 4.184 5.948-3.777 2.076-3.199-.589.096-5.884 2.696-1.562v.01Z" fill="url(#h)"/><path d="m287.012 235.914-9.212-4.034v-2.3l3.456-1.722-2.3-7.489 10.934 4.033 1.722-9.789 5.756 9.789 4.023-5.756 5.178-6.334h3.456l-7.479 10.945h7.479l5.755 3.456-9.211 8.056-9.212 1.155h-10.356l.011-.01Z" fill="#F37783"/><path d="M292.265 220.002c.62-2.824.374-5.628 2.621-7.992 2.354 1.551 2.6 4.461 4.44 6.644 3.156-3.691 6.045-7.66 10.474-9.886 1.69-.845 3.595-2.428 5.36-.813 1.669 1.53-.235 3.253-.663 4.868-.225.835-.642 1.701-1.209 2.354-2.643 3.06-1.905 3.969 1.925 5.349 4.13 1.487 7.639 4.708 11.598 6.954 3.616 2.065 2.343 7.874-2.054 10.603-6.131 3.808-13.031 5.467-20.082 6.504-3.487.514-6.997.803-11.041 1.263 3.274 4.279 7.885 6.697 9.79 11.779 4.279 11.405 1.829 21.804-7.875 29.122-12.72 9.586-27.27 12.217-42.762 10.837-7.478-.663-14.646-2.599-21.258-6.301-4.922-2.75-8.805-6.473-11.287-11.651-1.637-3.423-1.466-5.67 2.45-7.564 8.387-4.044 16.54-8.559 24.681-12.838-5.948 0-11.886.15-17.813-.075-2.632-.096-6.43.899-7.264-2.632-.738-3.145 1.048-6.045 3.905-8.099 9.104-6.547 19.643-8.666 30.416-10.078 1.391-.182 2.814-.182 4.247-.267-1.904-8.121-1.262-9.33 6.88-11.459 3.915-1.027 7.97-1.519 11.95-2.332 1.241-.257 3.434 0 2.803-2.161-1.969-6.815 2.6-3.852 5.221-3.552 1.38.161 2.696.813 4.525 1.402l.022.021Zm-68.161 36.365c10.752-.728 21.504-1.488 32.267-2.14 1.615-.096 4.098-1.209 4.633 1.059.492 2.054-2.097 2.557-3.574 3.306-9.939 5.039-19.996 9.821-29.838 15.031-2.119 1.124-6.484.129-6.013 4.087.321 2.686 2.696 4.868 4.996 6.666 3.242 2.535 6.698 4.707 10.571 6.034 15.598 5.349 31.079 4.782 46.025-2.14 8.687-4.023 16.048-9.736 19.3-19.45.589-1.755 1.316-3.21.268-4.975-3.755-6.323-8.163-11.843-14.903-15.438-12.443-6.633-25.431-6.665-38.794-4.322-9.361 1.647-17.877 5.06-24.949 12.26l.011.022Zm64.202-13.438c8.966-1.102 17.332-1.262 25.367-3.595 4.076-1.187 8.067-2.664 11.351-5.477 1.134-.974 2.803-2.151.653-3.766-2.204-1.659-5.221-3.221-7.297-1.562-5.67 4.525-12.132 5.627-18.968 6.783-7.04 1.187-13.994.941-19.215-3.392-4.74-3.937-8.859-3.231-13.534-1.733-1.958.631-5.478.385-5.018 3.541.439 3.028 3.221 4.472 6.355 4.537 6.077.139 11.887 1.54 17.525 3.733 1.145.45 2.332.781 2.771.931h.01Zm14.914-19.086c1.733-4.419 6.591-6.505 7.521-11.865-3.958 2.653-5.841 6.184-8.558 8.912-2.001 2.001-3.713 2.921-4.569-.963-.192-.888-.417-2.075-1.605-2.493-.802 2.268-1.604 4.526-2.417 6.794-2.889-1.412-5.125-3.68-8.121-2.867-1.198 3.487 6.633 5.285 1.188 9.029 6.408 4.012 13.17 2.964 19.931.963 3.017-.898 6.302-1.369 8.645-3.755 1.07-1.091 2.632-2.504 1.958-3.959-.407-.877-2.45-1.134-3.809-1.39-3.381-.621-6.441 1.39-10.164 1.583v.011ZM89.858 183.125v-4.953c1.85 2.589 3.423 2.503 5.67 1.562 7.628-3.21 9.575-1.519 8.43 6.783-.235 1.712-.502 3.413-.802 5.445 3.702-.888 6.911-1.69 10.271-1.733 2.557-.032 5.017-.481 5.681 3.103.374 2.054 2.589 1.444 3.98 1.947 7.585 2.717 13.245 7.446 15.812 15.278 2.119 6.429 1.423 7.435-5.06 8.109-1.562.161-3.135.214-5.232.353 2.29 2.108 4.868 1.798 6.976 2.696 1.369.578 3.573-.385 4.065 1.755.524 2.3-1.305 3.509-2.824 4.718-6.944 5.531-13.759 6.933-24.158 4.996-1.187 1.091-.759 2.579.075 3.242 3.413 2.707 2.974 6.291 2.257 9.725-.609 2.921.268 3.798 3.071 3.916 3.028.117 5.852.898 8.377 2.888 4.344 3.424 4.365 5.285-.332 8.292-1.016.652-2.065 1.241-3.562 2.139 1.23.332 1.872.514 2.514.696 3.669 1.038 7.842 2.161 7.296 6.911-.503 4.419-4.675 5.456-8.441 5.874-9.211 1.027-18.177.941-24.617-7.393-1.081-1.402-2.397-2.011-4.173-1.551-6.12 1.583-12.25 3.145-19.011 4.878 10.623 2.75 19.664 6.74 22.06 18.145 1.67 7.949-3.402 12.56-8.901 17.332-9.65 8.366-18.444 5.552-27.25-1.07-1.294 1.637.022 2.514.407 3.498 1.423 3.681 3.145 7.5-.085 10.934-3.338 3.563-6.869 6.034-12.635 4.365-4.783-1.39-10.186-.353-15.053-2.396-7.265-3.06-13.256-7.607-16.605-14.903-3.413-7.447-.16-16.69 7.586-22.339 6.9-5.028 14.485-8.837 22.51-12.111-6.987-1.048-13.93-1.573-20.724-3.06-5.905-1.294-11.618-2.995-16.722-6.451-3.316-2.247-5.05-5.552-6.173-9.072-.952-2.985.428-6.441 3.22-7.072 4.986-1.123 7.04-5.617 12.261-8.099-6.451-1.605-11.672-3.092-16.979-4.172-3.819-.771-3.52-2.568-1.99-5.2 4.89-8.452 12.315-14.507 19.632-20.595 1.99-1.658 3.938-2.289 1.017-4.868-1.68-1.487-3.381-3.669-2.054-6.119 1.401-2.579 4.097-3.103 6.911-3.092 5.21.021 9.907 2.225 14.807 3.616.792-4.183-3.852-9.233 1.626-12.047 4.322-2.225 10.581.064 12.004 3.37 2.503-7.325 7.446-7.963 14.828-1.915 9.468-11.404 14.336-13.212 20.028-6.376l.01.021Zm-27.153 34.257c-3.381-.567-6.355-2.172-9.255-3.819-5.167-2.942-10.11-2.14-15.406.364 5.018 5.456 10.827 7.499 17.781 5.788 2.386-.589 4.665-1.584 6.997-2.397-.17 2.118 2.686 3.146 1.316 6.12-2.9 6.269-2.61 12.999-.749 19.664 6.74-2.632 11.705-10.838 10.838-17.728-.556-4.354-1.894-7.842-7.371-7.253-1.38.149-2.857.139-4.162-.739h.01Zm-4.451 21.761c-5.734 2.568-10.688 6.131-16.487 7.735-2.054.567-4.193 2.782-6.333.61-2.193-2.225-.556-4.75.235-6.986 2.13-6.002 5.05-11.64 8.987-16.754-4.9-2.889-9.746-5.135-12.496-10.581-1.241-2.471-5.585-3.466-7.617-.192-1.83 2.931-4.408 4.375-7.008 6.13-3.584 2.418-6.29 5.488-8.003 9.639-1.337 3.231-.342 4.504 2.536 5.467a45.476 45.476 0 0 0 9.319 2.076c1.68.192 3.733.406 4.311 2.514.6 2.161-1.06 3.145-2.546 4.172-3.948 2.739-7.586 5.853-10.956 9.276-1.176 1.198-1.465 2.065-1.22 4.226.61 5.456 4.505 7.04 8.175 8.163 24.756 7.628 49.534 6.398 74.227-.631 1.326-.375 2.29-.824 2.524-2.29.942-6.055 5.606-8.312 10.571-9.949 4.418-1.455 4.814-5.35 4.579-8.559-.257-3.563-3.659-.771-5.564-1.327-.663-.192-1.401-.139-2.107-.235-2.6-.375-6.815-.535-6.387-3.253.502-3.177 4.087-.449 6.323-.502 1.861-.043 5.253 1.102 4.472-2.354-1.338-5.938-4.023-11.373-10.079-14.101 1.338 2.471 3.178 4.59 4.622 6.954 2.921 4.772 1.723 7.339-3.84 7.757-3.103.235-6.27-.418-9.565-.685-.364 3.017-.589 6.184-1.177 9.265-.6 3.124-1.433 6.227-2.418 9.254-1.166 3.574-3.306 4.408-6.344 1.755-2.696-2.354-5.606-4.761-6.601-8.195-1.124-3.873-2.472-3.167-5.018-1.412-4.771 3.273-6.815 2.428-8.27-3.06-.31-1.166-.492-2.365-.813-3.927h-.032Zm-9.137 82.433c1.06-.085 2.108-.235 3.167-.257 7.553-.149 9.169-2.621 6.312-9.65-1.765-4.343-4.846-7.831-7.414-11.651-.824-1.23-2.717-2.332-1.187-4.086 1.626-1.862 2.856.096 4.076.834 6.044 3.67 11.266 8.623 18.006 11.212 8.676 3.338 21.097-4.162 22.156-13.491.803-7.029-4.044-13.234-13.758-15.802-20.338-5.37-38.686-.577-54.552 12.903-7.307 6.205-6.805 15.395.289 21.879 6.472 5.916 14.058 8.783 22.895 8.088l.01.021Zm83.642-95.999c-3.905-1.508-7.35-2.45-10.164-4.664-1.144-.899-2.289-1.798-1.936-3.488.364-1.765 1.958-2.033 3.295-2.193 2.996-.342 6.013-.503 9.03-.567 2.043-.043 3.167-.589 2.204-2.803-2.664-6.163-7.115-10.485-13.448-12.71-1.488-.524-3.392-.888-3.873 1.38-1.498 7.05-6.409 11.704-11.212 16.454-.888.878-1.381 1.402-.45 3.017 6.74 11.555 14.294 13.406 26.554 5.564v.01Zm-7.179 31.508c-3.862-2.803-7.564-4.023-11.65-2.279-1.445.621-2.675.631-4.055.3-5.136-1.231-10.849 4.386-9.586 9.372 1.262 4.985 4.868 6.89 9.522 7.681 5.927 1.006 11.971 2.579 17.535-.759 2.278-1.37-.075-2.311-1.252-2.643-2.707-.759-5.488-1.241-8.238-1.861-1.252-.279-2.45-.771-2.696-2.172-.257-1.445.824-2.311 1.883-2.921 2.696-1.573 5.456-3.017 8.548-4.707l-.011-.011Zm-64.148-69.584c-3.499 2.739.802 7.2-2.515 9.747 1.338 1.69 3.66 1.219 5.232 2.364 1.573 1.134 3.477 2.065 4.536 3.573 1.883 2.686 2.686 2.172 4.986.097 6.301-5.649 13.587-9.34 22.542-8.559 3.049.267 2.546-3.049 2.867-4.59.481-2.332 2.375-4.975.182-7.297-.321-.342-1.937.396-2.878.792-3.017 1.273-4.14 4.194-5.83 6.655-1.007 1.476-1.99 4.065-4.398 2.642-1.894-1.123-.407-2.92.45-4.151 1.486-2.118-.407-3.199-1.199-4.589-.995-1.755-2.46-.942-3.712-.407-4.034 1.744-6.27 4.397-4.248 9.522 1.284-1.808 2.3-3.402 3.499-4.857.535-.653 1.433-1.188 2.364-.749.364.171.824.941.717 1.219-1.134 2.728-1.209 5.799-4.857 7.372-2.086.898-5.713-1.498-6.505 2.706-.128.674-1.594.182-2.065-.716-2.236-4.269-7.253-6.088-9.158-10.763l-.01-.011Zm-2.44 35.616c-4.76 1.84-10.42.053-13.512 6.002-2.332 4.482-5.2 8.591-6.056 14.817 8.88-5.456 21.344-5.809 19.568-20.83v.011Zm22.542 28.993c4.804-12.763 4.044-19.161-2.76-23.173-.717 2.182-1.252 4.408-2.172 6.462-3.177 7.146-2.129 11.094 4.932 16.7v.011Zm14.08-47.898c3.23.428 5.755-1.187 8.516-1.54 5.36-.685 2.942 3.926 4.247 6.397 3.071-2.086 4.183-5.22 5.242-8.355.664-1.958 1.958-4.59.706-5.906-1.583-1.669-4.3-.171-6.547.129-3.22.428-4.868 4.482-7.585 4.3-4.044-.267-4.387 1.68-4.58 4.965v.01Zm-15.32 19.258c5.092 6.023 10.666 9.19 18.465 8.002-1.22-4.985-5.403-7.617-8.174-10.966-.856-1.027-6.258 1.723-10.292 2.964Zm-27.475-22.478c1.573 6.13 5.467 9.276 9.971 11.854 1.455.835 3.178 2.45 4.772.877 1.647-1.615.61-3.883-.246-5.477-2.846-5.318-8.1-6.377-14.508-7.254h.011Zm-28.533-.128c2.91 7.638 13.726 10.506 21.376 5.467-7.05-2.878-13.566-6.323-21.376-5.467Zm68.61 17.759c3.787-1.102 6.141-3.231 8.302-5.52 1.295-1.37 3.231-3.156 2.161-5.028-1.059-1.851-3.156-.075-4.803.074-1.402.129-2.814.482-4.183-.203-.75-.374-1.37-.128-1.809.535-.577.845.129 1.348.675 1.68 4.108 2.546 1.208 5.103-.343 8.473v-.011Zm-12.303-15.62c-4.74 2.632-7.265 5.938-7.917 11.095 6.73-2.418 8.462-4.836 7.917-11.095Zm-31.572.995c-.78-3.819-1.091-7.457 5.028-7.649-3.359-2.375-6.333-5.339-8.666-3.713-2.236 1.562.354 5.146 1.028 7.778.31 1.22.513 2.835 2.61 3.584Zm40.997 9.779c-4.226 2.311-9.982-.214-14.229 4.718 6.27 1.434 10.634-.428 14.23-4.718Zm2.172-14.861c-7.318 1.477-8.41 3.317-5.841 9.501 3.477-2.236 5.317-5.307 5.841-9.501Z" fill="#000"/><path d="M242.078 349.834c-1.551-4.6-4.515-8.366-7.896-11.747-.545-.588-.492-.974-.16-1.444 4.707-6.452.973-18.22-8.431-13.866-1.626.792-2.075.653-1.915-1.144.182-1.937-1.102-3.36-1.851-4.579-17.791-24.244-32.406-17.685-57.259-22.756-3.177-1.552-6.74-3.927-10.345-5.232-4.419-.631-10.624-1.123-12.272 4.312-2.321 2.91-6.74 2.546-9.179 5.456.16 1.038-.289 1.551-1.327 1.626-.182.043-.31.118-.224.342.717.878-.835 2.183.513 2.868.407.203.717.406.952-.289.139-.546.546-.043.674.139.428.545.696.182.995-.118 1.466-2.482 3.852-3.702 6.43-4.483 3.884-.813 4.258-5.114 7.532-6.536.342 1.08 1.444 1.529 2.215 2.321 1.102-.524.717.61 1.037.974 1.916 1.851 5.029 2.589 7.147 3.969 2.279.385 4.558.749 6.837 1.145-.065.064-.14.139-.204.182 12.881 4.557 30.01-1.669 39.061 11.501 2.546 2.91 5.499 4.643 9.468 4.033 2.91-.856 3.445 2.642 5.146 4.194.064-.118.064-.268.064-.428.428 0 .289.567.632.652-.043.792-1.102.856-.92-.021-2.996-1.583-8.57 3.252-6.634 6.901.589-.546 1.177-.065 1.755-.043 1.466.385 1.305-.856 1.626-1.626.771-1.584 2.707-1.348 3.723-2.589.225.363.182.77.343 1.059.042-.161.064-.343.085-.492.428 1.957-1.754 4.258.546 5.552 1.808 1.198 3.498-1.177 4.868-2.097 1.423-1.102 3.049-1.262 4.664-1.423 3.766-1.016 2.343 9.897-.813 8.046-.246-.204-.428-.225-.492.203-.182 1.262-.877 2.386-.813 3.745-1.712 3.926-7.96 6.74-12.218 5.231-2.46-1.016-1.936-4.354-2.439-6.515-.043-2.75-4.087-2.643-4.055.064.043 1.038.118 2.075.182 3.135.246.042.514-.043.792 0-.022-.139.064-.065.064.021.118.021.203.086.321.225-2.011.385-3.83-1.53-5.884-1.648-1.648-.289-1.263-1.305-.995-2.215 1.401-5.146-.696-11.115-5.093-13.983-.77.567-.995.225-.952-.567l-.064.022c-.471-.246-1.017-.428-1.284-.952-6.762-2.643-13.983.877-20.413-1.284.407 1.444-.385 1.262-1.262.92-2.162.289-5.211-.631-6.987.267-.117.974-.77.974-1.326.835-1.53-.343-3.071.139-4.622-.118-4.579-.856-8.752-2.867-12.967-4.622-.717-.16-1.305-.952-2.182-.385-.182.086-.139-.342-.161-.513-2.418-3.702-6.761-5.211-9.714-8.367.203 1.017-1.327 0-.364-.406-.877-.589-.877-2.119-2.279-2.161-.588.406-1.305-.45-1.872.203-.92 1.423-.877 3.092.021 4.483 3.766 3.947 8.431 6.74 12.924 9.896.546-.107 1.06-.107 1.263.545.77.792 2.503 1.124 2.236 2.59 1.102.973.813 3.198 2.931 3.22.161 0 .321.021.268.246-.246 1.102.791 1.444 1.326 1.958.567.513.749.952.182 1.38-1.284.973-1.936 2.461-3.049 3.584.086.321.064.567-.321.652-.16.589-1.102.878-1.016.043-.118-.021-.204-.043-.268-.117-.749.16-1.262.855-1.979.77-4.686.31-9.447.043-13.962 1.551-4.536 2.996-9.382 5.82-12.881 10.175-5.659 6.633-9.361 14.657-12.378 22.713-2.236 6.291 6.815 5.702 10.666 5.82.45-.225.878-.717 1.348-.022 3.017-.181 6.088.204 9.062-.385 11.234.268 23.633-2.46 35.381-1.979 3.423-.588-8.367 16.369-9.693 18.059-.995 1.22-.589 3.253.834 3.788 25.891 17.321 100.706-6.965 87.312-44.475l-.011.011Zm-99.647-54.049c-.696-.632-.161-1.124.203-.204-.085.086-.139.161-.203.204Zm14.775.449-.065.064c.204.45-.16.653-.181.139-.065.064-.14.065-.204.065.064-.065.107-.14.161-.204.085.022.16-.021.203-.117.021 0 .064 0 .086.021v.032Zm5.681 2.568c.042-.086.139-.139.246.064-.065-.021-.161-.043-.246-.064Zm45.907 53.15c.204-1.176 2.119.311 2.097-1.176.043-.653.385-1.488-.545-2.012-.471-.246-1.487-.717-.995-1.241.749-.791 1.401-2.3 3.092-1.348.877.61 1.262 1.38 2.546.407.321 1.915 1.754 1.219 2.931 1.284 3.092.267 5.318-.995 8.121-2.418-2.386 5.21-5.232 9.917-10.603 12.335 1.712-2.033 1.102-5.884-1.893-4.536-3.296 2.161-6.045 3.766-10.079 4.536 1.081-2.054 2.707-2.91 4.012-4.055.61-.492 1.605-.588 1.306-1.786l.01.01Zm-24.425-27.762c10.036-2.076 18.306 3.765 14.347 14.346-.289 2.183-3.07 4.355-.813 6.387-2.364-.855-1.551 1.755-1.936 3.338.021.567-.289.653-.567.717-7.65 3.627-10.849 12.625-19.301 15.588.61-2.867 4.194-3.969 2.75-6.986-.631 0-.77-.492-.995-.952-6.387.588-13.234 4.985-19.397 1.348l-.021.021s-.043 0-.064-.021c-.343.289-.653.652-1.038.856-.342.182.225.749-.342.631-1.53-.952.321-2.011 1.423-1.509.021 0 .021.022.042.022 2.707-2.953 20.028-1.787 16.305-7.981-1.669-.022-2.707-1.348-4.108-1.915-.385-.182-.631-.386-.653-.835 2.504-2.3 13.288 3.745 15.224-.182 6.58-11.255 11.437-13.106-1.829-22.306-.31 0-.61-.065-.835-.567h1.808Zm-20.477 36.439c-.117.182-.267.31-.513.61-.043-.364-.118-.546-.118-.749-.021-.546.952-.364.631.139Zm-1.123-34.032c3.316-.182 8.837 2.097 10.688-1.605.182-.631.545-.589 1.08-.203 2.343 1.99 15.492 7.211 12.561 10.666-7.842 4.579-17.3-.471-24.126-4.707-1.123-.492-.513-1.915-2.14-1.851-2.343-.813-3.808-2.461-5.777-4.108 2.728.652 5.189 1.444 7.714 1.808Zm-22.799 13.78c-.652-.311-1.348-.546-1.979-1.177.952-.246 1.733-.525 2.568-.45.363-.567.674-.117 1.016.022 2.953-.631 6.836.588 9.265-1.327-.77-.021-1.348-.139-.61-1.038.118-.856.567-.674 1.059-.321.813.407-.085.878.022 1.327 1.219-.246 1.915-1.262 2.685-2.054 1.583-1.648 3.648-1.509 5.595-1.808 1.284-.043.674 1.733.792 2.546.407.717.835 1.444.546 2.322.449.385.567.995.995 1.423.406.428 1.262.973.652 1.69-.545.631-1.305 1.102-2.257.834-3.52-.92-7.19-2.642-10.239.118-3.519 2.076-8.098 5.114-12.089 4.579-.289-.567.182-.995.546-1.145 2.3-.92 4.397-3.969 1.444-5.552l-.011.011Zm34.214 56.328c-.085-.471.92-.771.856-.204.043.514-.791.835-.856.204Zm62.716-27.506c-13.737 20.434-56.468 34.385-78.207 22.049 3.584-5.948 7.649-12.335 10.688-18.711 2.642-5.574-6.27-4.291-9.383-4.291-16.101-.021-32.085 3.296-48.187 2.012-2.524-.471 2.771-6.858 2.996-8.677 3.563-6.633 8.077-16.593 15.984-18.016.545-.546.973-.043 1.444.139.952-.813 2.118-.717 3.295-.77-6.654 8.976 3.178 9.607 9.875 6.494-.043-.471-.749-.814-.225-1.348.835-.386.567.674.567 1.123 3.274-.589 5.521-4.033 8.688-4.173 3.584 1.038 8.099 2.814 10.827-.834 3.52-1.936 1.198-5.435-.771-7.575 6.045 2.91 12.111 5.553 19.119 4.44-.343.974-1.177 1.733-1.059 2.846-5.114 1.284-11.073-3.252-15.941.385-2.14 1.38-1.263 4.986.631 6.312.267.268 1.059-.117.899.61-3.135 1.445-17.546 1.894-13.17 8.003.545.492-.653.695.021 1.348.974.952 2.14 1.466 3.295 1.787 4.986 1.872 9.715.288 14.657-.428-1.037 1.102-.695 2.503-.631 3.701 1.423 5.66 8.548.717 11.683-.952-.086-.856.118-1.262.995-.653.182-.524 1.102-.609.792-1.401-.204-.514.117-.567.449-.407.364.161.546.14.792-.181 1.262-1.627 3.156-2.643 4.194-4.462-.546.118-1.017.064-.953-.631.204-.877 1.306-.225 1.851-.064.856-1.808 2.953-2.568 3.948-4.13.182-.567.492-.674.974-.364 4.033-.716 2.589-6.676 4.44-9.607.203-.631.492-.546.952-.407 1.53.022 2.813 1.851 4.279 1.199.118-.61.589-.92.974-.492.363.385-.343.588-.61.877-1.648 1.605-2.91 3.359-1.979 5.841-.878 2.161-4.109 3.445-5.189 5.885-3.381 5.188 1.284 6.986 5.659 5.798 9.287-3.83 8.388 6.387 18.242-5.092 3.402-4.173 7.061-9.287 7.67-14.369.61-.385 1.124.086 1.402.407 6.291 7.168 9.468 18.22 4.033 26.789l-.01-.01Z" fill="#030303"/><path d="M160.715 301.445c-.535-.685-1.551-.792-1.894-1.605-.043-.043-.064-.107-.085-.16-.289.021-.557-.022-.792-.182h-.021a2.176 2.176 0 0 1-.407-.364c-2.675-.642-4.13.61-6.473 1.402-2.599.823-3.124 4.012-3.177 6.312-.118 4.108 6.387 7.692 10.099 5.82 3.691-2.151 5.339-7.821 2.75-11.234v.011Zm-5.232 7.575c-2.129-.011-4.044-.953-3.199-3.606.803.524 1.231 1.68 2.279 1.605.182 1.155.856.899 1.584.588 1.743-.235.395 1.594-.653 1.423l-.011-.01Zm-.92-6.184c1.487.16 2.568.513 3.402 1.958-1.551-.204-2.525-.717-3.402-1.958Z" fill="#030303"/><path d="m82 39.585 9.094-6.42-6.42-2.674 1.605-2.675 15.513-1.604 9.629 3.21h9.094l12.303 5.348 6.42-3.744-22.467-12.303-9.094 1.604-14.443-1.07-2.14-2.674 5.884-2.675-3.21-4.28 1.07-2.139h7.489l-3.21-4.28L100.724 0l10.698 7.489 10.164 2.14 6.954 2.674 15.513 8.024 6.954-1.07h6.419l12.304-6.954h13.908l11.768 4.28 12.839 11.768 13.908 1.605 9.629 13.373-2.14 4.815 3.744 9.094h9.629l1.07 2.674-4.279 3.745 6.419 9.629-9.629-5.35-1.605 6.42-5.349-6.955-3.21-6.419-5.349-5.884-5.349 3.21H201.29l2.139 8.558 7.489 4.28 10.164 1.07 10.164 7.489-6.954 2.674 1.604 6.954-10.163-4.814-17.118-5.884-3.21-6.42-4.814-17.117-18.723-3.21-9.628-5.884-21.398 1.07h-9.093l-18.188-7.49-12.838-3.744-9.63 10.699-1.604-4.814H82v-2.14Z" fill="#F8F6F4"/><path d="m183.909 42.065-1.54-3.766 4.868-3.135 3.134 4.333-1.112 2.653-5.35-.085Z" fill="url(#i)"/><path d="m187.376 26.604-3.702-2.74-1.07-.02 3.274-3.692 4.814.075 1.519 5.37-4.835.996v.01Z" fill="url(#j)"/><path d="m171.414 20.987-3.681-3.809h-.535l4.355-4.215 6.429-.963-.128 7.489-6.44 1.498Z" fill="url(#k)"/><path d="m164.695 39.604 2.567 6.462-6.462 2.568-.941-8.035 1.658-3.177 3.178 2.193v-.01Z" fill="url(#l)"/><path d="m151.792 43.144 4.184 5.948-3.777 2.075L149 50.58l.096-5.884 2.696-1.562v.01Z" fill="url(#m)"/><path d="M204.879 36.256c-3.028-.332-5.21 1.37-5.371 4.258-.021.385.086.792.139 1.198.514.396.524.417-.289.77 0 1.509.632 2.803 1.359 4.098 1.712 3.156 5.018 3.68 7.543 1.091-.674-.834.609-.417.545-.856.032-.235-.192-.534.118-.727 0-.46-.182-1.027.567-1.113.899-.78.749-2.022.781-2.899.107-3.285-2.065-5.456-5.392-5.81v-.01Zm.096 4.611c-.503-.107-1.38-.31-1.786.481v.065h-.022c.15.428.417.813.096 1.284h.032l-.021.02c.118.514.696.846.471 1.456.139.064.267.128.385.203.3.16.588.343.578.75 0 .063-.118.17-.171.192-.471.117-.493-.386-.749-.557-.118-.096-.161-.32-.225-.503 0-.535-1.423-.834-.278-1.55v-.022c-.375-.407-.942-.803-.107-1.284v-.022s0-.032.021-.053c-.139-2.6 1.851-1.123 2.985-1.498-.096.792-.171 1.263-1.198 1.027l-.011.011ZM191.088 39.057c-1.22-2.322-3.081-3.809-5.841-3.937-1.562-.075-4.751 1.412-5.221 2.6-.749 1.84.866 6.547 2.642 7.489 2.108 1.123 4.333 1.316 6.837.524.845-.503 1.947-1.113 2.321-2.247.503-1.53-.043-3.081-.738-4.429Zm-3.648 3.445c-1.551.642-2.472-.332-3.381-1.145-.61-.524-.524-1.305-.107-2.011.139-.246.214-.546.578-.578.845-.053 3.359 1.37 3.616 2.193.257.728.417 1.541-.706 1.541ZM187.9 18.859c-2.118.043-3.231 1.187-4.29 2.653.235.428.118.76-.257 1.027.139.706-1.401 1.134-.353 2.012-.374.513.375.438.46.855.257 1.616 1.273 2.782 2.771 3.51 1.166 1.101 5.028 2.01 5.981.93.856-.92 2.46-1.358 2.535-2.696.097-1.433.064-2.974-.513-4.397-.995-2.514-3.638-3.937-6.334-3.905v.01Zm3.06 7.767c-.203.556-.161 1.252-.974.257-.503-.6-1.669-.631-2.546-.92a.929.929 0 0 1-.257.16c-.107.15-.139.364-.214.524 0-.181.097-.342.086-.513-.064 0-.128-.043-.193-.107a.258.258 0 0 0-.053-.16.355.355 0 0 0 .139-.097c.31-.246-.054-.652-.107-.695-.439-.16-.449-.396-.375-.62.054-.172.172-.354.193-.514.984-1.798 2.332-1.894 3.359-.182.525.856 1.413 1.658.953 2.889l-.011-.022Z" fill="#000"/><path d="M243.715 56.41c-1.915-.46-3.862-.299-5.788-.02-1.198.181-2.065-.3-2.429-1.349-.545-1.605-1.102-3.167-2.022-4.6-.385-.578-.567-1.156-.128-1.798.471-.674.92-1.433 1.305-2.107.802-1.327.428-2.333.075-3.434-.92-2.964-2.643-5.467-4.633-7.821-.684-.803-2.054-1.67-1.829-2.472.556-1.882-.214-3.188-1.156-4.46-1.476-2.034-4.129-3.328-6.344-2.611-1.091.363-2.279.92-2.899 2.064-.193.407-.332.653-.867.578-.984-.139-1.936.236-2.888.439-1.188.289-2.525.043-3.274-.696-2.568-2.428-5.563-4.354-7.992-6.964-1.605-1.723-3.413-3.285-5.114-4.911-.374-.556-1.327-.353-1.519-1.156-1.209-.577-2.418-1.166-3.638-1.743-1.551-.739-3.231-1.156-4.825-1.744-1.145-.396-2.493-.321-3.755-.739-.685-.224-1.819-.492-2.343-.331-1.188.353-2.439.214-3.509.192-2.343-.085-4.536.386-6.601 1.284-2.675 1.166-5.232 2.632-7.81 4.002-.674.374-1.487.834-1.755 1.444-.353.813-.984.727-1.444.642-1.53-.3-3.113-.236-4.665-.375-.834-.085-1.54.364-2.332.246-2.589-.331-5.092-.117-7.446 1.092-.278.15-.492.62-.995.192-.685-.61-1.519-1.016-2.247-1.562-2.097-1.637-4.376-2.995-6.729-4.183-1.701-.845-3.456-1.54-5.146-2.364-4.248-2.076-8.688-3.178-13.438-3.167-1.016 0-2.043-.321-3.049-.706-2.375-.877-3.884-3.006-6.12-4.173-1.166-.588-2.385-1.455-3.562-2.16-2.375-1.456-4.183-1.21-6.023.192-.856.663-.247 1.626-.878 2.29-.353.374.428.331.738.449-.32.738.685 1.251.364 1.915-.246.513-.91.214-1.337.32-1.37.397-2.92.3-4.034 1.424 0 .513.835 1.283-.449 1.38-.867 1.776.46 2.813 1.327 4.022.139.193.684.118.46.6-.118.246-.332.32-.6.374-2.182.3-3.337 1.755-4.022 3.712.064.065.107.16.182.246.086.054.139.086.246.14.064 0 .118.02.171.053v.043c.407-.075.375-.503.588-.781.343.396.482.802 0 1.134-.395.267-.438-.107-.567-.353h-.042a.43.43 0 0 1-.257-.075h-.021c-.182.075-.3.246-.46.332.888 2.203 2.824 3.091 4.889 3.498 3.284.663 6.601 1.006 9.885 1.487.236-.353.46-.16.696-.043.064 0 .128.043.192.043 3.007.075 5.949-.278 8.923-.866 1.872-.375 3.755-1.659 5.927.042 1.84 1.423 4.098 2.397 6.12 3.67 1.487.941 3.102 1.733 4.664 2.578 1.819.985 3.67 1.84 5.606 2.536.278.096.845.3.61.856-.364.866-4.269 2.268-5.039 1.669-1.209-.952-2.482-1.808-3.83-2.514-1.444-.739-2.824-1.562-4.386-2.033-2.622-.813-5.296-.77-7.992-.824-.632-.021-1.156.321-1.766.225-2.246-.364-4.354-1.113-6.376-2.13h-.021c-.236.086-.214.664-.653.354-.514-.375.31-.375.225-.631 0-.022-.011-.043-.043-.075-.835.288-1.391-.418-2.097-.589-2.065-.556-4.119-.01-6.184-.246-1.83-.203-3.702-.096-5.542-.021-2.257.085-4.504.481-6.75.845-1.36.235-2.579.888-3.306 1.99-1.498 2.247.128 5.531 2.867 5.841.503.043.856.225.941.45.193.492-.203.738-.663.963-1.562.791-3.028 1.829-4.215 3.113-.62.685-1.113 1.508-1.498 2.44-.396 1.005.289 1.561.406 2.342.257 1.69.739 2.204 2.365 2.407 1.722.214 3.349.043 4.868-.834.31-.182.663-.257.995-.396.139.439.374.802.214 1.37-.3 1.22-.14 2.45.63 3.54.92 1.274 3.189 1.349 4.056.15 2.064-2.845 3.712-5.98 6.023-8.644 1.166-1.348 3.049-2.257 4.686-1.904 2.396.492 4.793 1.358 7.04 2.471.224-.546.567-.332.909-.203.075.021.128.042.203.064.589.107 1.188.203 1.776.31-.075-.396-.096-.77.407-1.123.15.503.471.877.075 1.348.032.075.064.246.107.246 3.092.514 5.852 1.958 8.548 3.36 2.707 1.422 5.392 2.877 8.152 4.236.31-.021.61-.032.899-.032.075-.096.182-.171.267-.246-.599-1.06.332-1.52.867-2.13.032-.235.053-.48.096-.727-1.294-.256-2.129-1.744-3.637-1.294-1.584-2.268-4.323-2.61-6.505-3.884a10.014 10.014 0 0 0-3.916-1.39c-1.059-.161-1.979-.942-3.134-1.252-1.306-.364-2.686-.567-3.97-1.113-.599-.236-1.198-.514-1.808-.76-.353.706-.513.246-.727-.096-3.552-1.241-7.104-2.536-10.784-.374-.097.053-.364-.022-.396.032-.75 1.669-2.675 2.257-3.445 3.905-.321.717-.674 1.615-1.637 1.85-.022 0-.01.033-.01.033-.022 0-.033.032-.022.053.246.385.32.728-.182.995-.01.022-.043.064-.054.086-.117.288.065.866-.502.642-.375-.118.021-.428.17-.642-.181-.578-.277-1.102.546-1.156h.043c-.652-.92.171-1.915.503-2.3 1.284-1.583-.15-2.193-.802-3.092-.493-.203-.91.524-1.445.129.3-.546.717-.739 1.327-.535.46-.514.728-1.145 1.733-.9.781.193 2.011-1.294 1.99-2.128-.032-1.21-1.08-1.98-2.46-2.108-2.697-.267-5.457-.075-8.228-.76.952-.63 1.947-.78 2.889-1.09 1.626-.557 3.295-.364 4.942-.504 1.734-.128 3.52.14 5.232-.117 1.327-.203 2.579.117 3.852.15 1.615.032 2.974 1.059 4.333 1.808 1.765.973 3.637.802 5.488 1.059 3.113.439 6.28.16 9.404 1.123 2.225.706 4.066 2.011 6.12 2.974.064-.513.492-.62.791-.395.268.235-.042.502-.31.642 2.129 2.385 5.852 2.022 8.292-.129 2.557-2.215 4.75-4.814 7.842-6.505 2.492-1.37 4.632-3.509 7.414-4.397 1.38-.417 2.856-.791 4.397-.663 1.787.15 3.627-.236 5.435.15.909.192 1.808.449 2.685.674.471-.546 1.209-.867 1.305-1.723.054-.481-.278-.214-.449-.267-.182.107-.449.289-.567-.022-.053-.139-.021-.235.032-.3.118-.106.3-.149.428-.235v-.866c-1.166-.385-2.332-.803-3.616-1.23 1.498-.664 2.493-2.012 4.044-2.654.695-.31.931-.085 1.252.332.289.364.535.813.727 1.187 1.199 2.204 3.467 2.311 5.424 2.825 2.932.738 6.826-2.632 6.976-5.756 0-.225.193-.45.3-.663-.674-.407-.086-.856-.033-1.284 4.002.235 7.596 1.744 11.148 3.466 3.959 1.958 6.569 5.446 9.747 8.28 2.535 2.27 4.868 5.019 8.409 5.928 1.508.374 3.113.567 4.547.289 1.433-.289 2.739-.107 4.087-.022 1.797.118 3.145 1.605 4.943 1.851.064 0 .62 1.113 1.048 1.701 1.348 1.723 2.75 3.392 3.948 5.21 1.626 2.515 1.273 4.483-1.059 6.377-1.509 1.262-3.092 2.45-4.686 3.616-1.766 1.295-3.306 1.455-5.499.877-1.488-.385-2.804-1.39-4.43-1.262-.214 0-.46-.3-.695-.46-.268-.128-.535-.257-.813-.353-.022 0-.075-.022-.096-.01a.909.909 0 0 0-.257-.086c-.086-.043-.171-.054-.257-.086a5.4 5.4 0 0 0-.728-.118h-.021s-.053-.042-.075-.032l-.16-.075s-.054-.021-.075-.021a.954.954 0 0 0-.236-.032c-.128.085-.31.128-.363.289h-.022c-.01-.097 0-.172.032-.225h.022c.021-.086.053-.118.107-.15-.214-.032-.407-.075-.61-.096v-.021c-.235 0-.439-.022-.653.053-.01.096 0 .182-.01.267-.065 0-.118 0-.182-.02-.064 0-.161 0-.236-.033h-.075c-.021 0-.021-.01-.042 0 .128.171.107.321.021.439a.575.575 0 0 1-.203.182l-.182.064c.032.096.032.16-.032.214-.182.93.374 1.444.941 1.958.086.053.182.139.246.203 2.589 1.423 5.403 2.182 8.228 2.835.363.075.556.203.609.524.065.556-.353.257-.588.3-1.648.31-3.413.428-4.911.888-2.717.802-5.488-.353-8.077.738-.781.32-.589-.588-.674-.845-.931-2.247-2.044-4.397-3.263-6.473-.268-.439-.45-.439-.792-.278-.214.792-.674 1.102-1.466.813-.77-.3-.716.118-.695.674 0 1.263.781 2.215 1.209 3.306 1.006 2.6 2.322 5.05 2.931 7.863.343 1.594-.021 3.028.043 4.526.032 1.412.76 2.14 1.851 2.396 1.209.29 2.247.9 3.317 1.413 1.893.888 3.605 2.15 5.456 3.166.578.332.984 1.145 1.851.835.503-.396 1.038-1.284 1.391.107 1.679.16 3.038-.781 4.579-1.263-.065.578-.129 1.156-.204 1.744.407-.032.674.204.846.706a.507.507 0 0 0 .299.279c1.402.331 2.814.674 4.237.93 1.626.321 3.081.91 4.568 2.097-1.07.353-1.947.225-2.717.054-.664-.171-1.338-.193-1.905-.043-.545.15-.684.203-1.07-.31-.428-.578-2.086.513-2.482 1.605.064.246.257.481-.021.695.299 1.048 1.241 1.68 1.915 2.397.653.706.888 1.572 1.487 2.257.364.406.086.941-.193 1.22-.32.342-.567-.225-.834-.29-2.685-.802-4.547-3.06-7.157-4.033-.707-.235-1.37-.16-2.055-.278-2.225-.374-4.397-.941-6.472-1.83-.631-.288-1.209-.352-1.947-.096-.439.15-.557-.962-1.199-.995-.748-.042-.898-1.102-1.754-.941-.032.096-.032.214-.064.31-.332-.128-.632-.267-.599-.695-2.376-1.498-4.569-3.231-5.35-6.077-.364-1.273-.92-2.482-1.294-3.723-.685-2.247-1.252-4.536-1.958-6.804a44.65 44.65 0 0 0-1.006-2.782c-.332-.813-.406-1.84-.214-2.258.813-1.711-.652-2.236-1.294-3.21-.824.579-1.562.311-2.311-.181-3.071.171-6.034-.578-9.03-1.123-4.472-.824-8.644-2.557-12.721-4.537-.288-.139-.759-.374-.77-.62 0-.332.417-.524.749-.706 1.84-.963 3.809-1.562 5.692-2.322-.097-.139-.311-.428-.278-.46 1.636-1.605.032-2.193-.942-2.985-1.851.236-3.167 1.787-5.018 2.044-.256.16-.502.331-.738.481-.107-.246-.203-.503-.032-.792-.075-2.107-.866-4.076-1.819-5.83-.524-.974-1.647-1.82-2.76-2.59-1.851-1.208-3.028-.395-3.916.739-.813 1.038-1.615 2.279-1.519 3.894.054 1.049.118 2.033.439 3.006.011.043.032.075.021.129.086.481-.289.995.214 1.412.514-.492.995-.267 1.445.118.192.042.406.075.609.139.482-.257.739-.62.525-1.166-.311-.043-.781.053-.471-.503.246-.439.556-.824.813-1.22-.653-.952.588-1.744.246-2.685-.021-.064.31-.556.653-.16.224.256.834-.097.802.577-.075 1.498.835 2.792.824 4.354 0 1.017-.15 1.52-.984 1.862-.717.3-1.466.578-2.258.46-.759.364-1.562.481-2.386.492-.716.428-1.444-.118-2.139-.021-.343.032-.311-.129-.396-.418-.535-2.321-1.819-4.268-3.392-5.959-1.423-1.497-4.236-.845-5.199 1.017-.653 1.251-1.059 2.482-.61 3.947.3.92-.471 1.306-1.53 1.274-1.594-.054-3.338-.129-4.761.438-.663.257-1.466.589-2.15 1.027-.032.032-.043.065-.086.075.129.995.214 2.044 1.712 1.755.342-.054.61.278.738.631 2.108-.075 4.237-.278 6.344-.171 1.199.064 2.472.396 3.617.364 2.054-.054 4.065.3 6.13.107 1.573-.15 3.252-.236 4.686-.589 1.273-.31 2.15-.513 3.177.236.353.181.706.353 1.027.524.386.599 1.316.331 1.573.663 1.198 1.573 3.178 1.616 4.718 2.471 2.728 1.488 5.82 2.13 8.827 2.89 2.193.534 4.397 1.048 6.718 1.005 2.964-.043 3.723.599 4.205 2.963-.171.664.011 1.241.406 1.776.129 1.445 1.06 2.675 1.049 4.162-.075.289-.043.567.257.728.374 1.048.941 2.096 1.005 3.156.043.674.813.406.749 1.176-.16 2.13.792 4.077 1.701 5.895.888 1.82 2.632 3.05 4.344 4.162a40.44 40.44 0 0 0 7.339 3.723c1.616.61 3.327.92 5.007 1.348 1.444.364 3.113.321 4.301 1.08 1.198.75 2.621 1.295 3.584 2.45.396-.513.631-.16.877.161.995 1.252 2.568 1.359 3.927 1.862.995.364 2.075.513 3.124.717 1.433.278 2.674-.878 2.45-2.333-.193-1.24-.599-2.46-1.273-3.53-.46-.75-.343-1.658-.835-2.418-.31-.45.342-.674.546-.546 1.027.642 1.915-.235 2.899-.224 1.198 0 3.06-1.862 2.931-2.836-.31-2.332-2.022-3.573-3.691-4.771-1.219-.856-2.771-1.177-4.258-1.476-.77-.15-.856-.546-.492-1.006.803-.995.171-1.84-.257-2.6-.502-.845-1.273-1.658-2.332-1.562-2.204.182-4.354.578-6.291 1.819-.588.364-1.219 1.145-2.129.663-.93-.492-1.851-1.038-2.781-1.53-1.98-.995-3.616-2.61-5.863-3.134-.407-.075-1.038-.75-.995-.92.685-1.84-.3-3.542-.364-5.296-.011-.29-.257-.6.203-.696.428-.107.525.278.525.546 0 1.006.502.802 1.251.824.739.021 1.252-.557 2.108-.343 1.123.268 3.028.514 3.424-.053 1.155-1.584 2.31.235 3.327-.417.128-.065.364-.214.567-.268 1.861-.46 3.552-1.476 5.488-1.605l1.519-.535c-.278.717-1.241.578-1.08 1.338.61.963 1.273 1.733 2.065 1.433 1.786 1.926 2.867 4.098 3.648 6.43.802 2.343 2.193 4.387 3.306 6.59.471-.053 1.091-.363.877.578 1.091.888 2.086 1.883 3.488 2.258.385-.043.845-.428 1.048.257 2.022-.204 2.814-1.284 2.91-3.724.022-.32-.406-.834.118-.995.321-.107.653.278.952.418 1.091.502 1.701 2.246 3.37 1.476.268-.118.46.289.278.46-.599.524-.278.46.225.631 1.241.471 2.365.899 3.777.557 1.337-.3 1.893-.824 1.647-2.269-.406-2.663-2.214-4.493-3.84-6.408-.728-.877-1.637-1.605-2.472-2.396.3-.172.535-.386.792-.46 2.172-.653 2.461-2.472 2.6-4.28.117-1.797-1.541-3.37-3.927-3.948l-.053-.01ZM94.512 17.394c-.01-.107.15-.343.235-.332.503.021.482.546.91.877-.632.022-1.07.043-1.156-.545h.01Zm27.388 25.13c.214.108.385.13.417.236.204.439-.299.524-.449.803-.096-.075-.278-.172-.257-.225.065-.268.182-.503.289-.813ZM85.396 37.72c.043-.064.236.032.31.064.161.321-.063.375-.224.439-.096.032-.235-.032-.353-.054.075-.16.15-.342.267-.449Zm5.853-.428c.524-.406 1.112-.396 1.316-.128.438.535-.46.45-.567.738-.578 1.626-2.697 1.423-3.392 2.685-.663 1.284-1.893 1.07-2.803 1.637-.225.171-.492.107-.685-.043-.267-.256 0-.492.129-.642.845-1.059 1.85-1.99 3.102-2.61.974-.524 2.022-.963 2.9-1.626v-.01Zm60.789-15.534c-.075.224-.182.353-.321.406-.139.054-.321.022-.513-.064-1.947 1.22-3.905 2.493-5.895 3.638-1.733 1.016-3.306 2.236-4.761 3.594-.375.332-.695.246-1.059.332-.054.289.16 1.016-.492.417-.3-.278-.311-.888-.46-1.348-.514-.995-1.669-1.187-2.504-1.562-1.412-.61-2.61-1.594-3.948-2.3-3.766-1.98-7.328-4.376-11.051-6.42-1.37-.737-3.103-1.304-4.611-.662-1.081.47-2.162.545-3.231.877-1.926.588-3.841.717-5.82.77-3.456.107-6.901.107-10.228-1.016-.225-.075-.482-.118-.717-.193-.129-.043-.236-.16-.46-.278.963-1.048 2.214-.781 3.36-.941 1.272-.182 2.535.128 3.819-.257 1.102-.343 1.85-1.124 1.594-1.99-.225-.75-.974-1.551-2.183-1.637-2.172-.171-3.883-1.434-5.51-2.942 1.049-.567 2.001-.193 2.985-.097 2.397.247 4.665 1.177 7.104 1.402.856.096.888-.246 1.038-.792-.075-.706-.706-1.369-.15-2.129-.792-.342-.941-1.733-2.204-1.262.086-1.006-1.048-1.027-1.359-1.723-.406.097-.406-.214-.492-.449-.834.032-1.005-.513-1.07-1.316.557.31 1.028.567 1.498.845l.236.471c1.883.246 3.102 1.658 4.375 2.771 2.589 2.247 5.457 3.745 8.859 3.723 4.247 0 8.077 1.22 11.875 2.964 2.461 1.112 4.804 2.396 7.243 3.509.086-.257.182-.503.257-.738-.043-.386-.974-.567-.353-1.006.653-.47.877.267 1.123.717.311 0 .76-.45.781.374 0 .706.236 1.412.353 2.118 1.595 1.038 3.007 2.343 4.59 3.36.835.546 1.958 1.091 3.242.053.984-.813 2.493-.941 3.819-1.144.385-.62.845-.054 1.263-.086.267-.824 1.048-.235 1.615-.899-.356.97-.895 1.27-1.615.899l-.022.01Zm26.501-5.874c-.482 1.08-.771 2.472-1.937 2.686-1.337.449-4.504-1.038-4.868-2.001-.181-.45.225-.482.428-.62 1.605-.942 3.435-1.167 5.189-1.563 1.198-.246 1.391 1.049 1.198 1.488l-.01.01Zm31.539 34.257s.022.01.032.032h-.021s-.075-.01-.086-.032h.075Zm-.674.054h.086v.182a.44.44 0 0 1-.171-.182c.021.01.075.021.096.01l-.011-.01Zm-58.596-4.077c-.482-.16-.407.118-.235.354.181.203.171.428.149.684-.032.653-.716.942-1.048.931-.439-.043-.364-.717-.289-1.123.096-.364.471-.503-.118-.963-.61-.47-.278-1.594-.139-2.354.075-.428.813-.267 1.081.15.353.567.62 1.187.92 1.787-.203.117.717.898-.321.534Zm41.061 15.813s-.075-.085-.107-.118c-.032-.032-.064-.042-.096-.075.043-.064.096-.096.139-.16.011.043.043.053.054.096.042.075.106.16 0 .268l.01-.01Zm54.67 12.806c-.824.246-.824-.31-.856-.856.075.022.204 0 .214.032.086.108.15.236.214.343.257-.086.353-.749.771-.343.374.375-.343.482-.343.814v.01Zm-4.151-13.277c-.866.375-1.754.76-2.493 1.306-.888.695-.888 1.69-.481 2.728.182.47.439.91.781 1.284.374.492 1.433.47 1.07 1.69-.278-.792-1.305-.364-1.445-1.252-.973-.053-1.198-1.177-2.203-1.444-1.53-.417-2.686.15-2.632 1.754.032.9.342 1.723.631 2.557.235.739.342 1.53.588 2.622-1.091-1.06-1.551-2.183-2.749-2.61-.31-.119-.396-1.06-.664-1.616-.962-2.236-1.925-4.505-2.567-6.88-.139-.502-.428-1.155-.856-1.348-1.509-.674-2.375-2.118-3.713-3.006-.941-.642-.888-1.327.033-2.193 1.144-1.049 2.45-1.797 3.637-2.728.556-.439.813-.417 1.166.235.46.792.845 1.573 1.188 2.407 1.626 3.788 1.658 5.018 6.697 4.996.867-.01 1.712-.117 2.578-.203.407-.17.792-.214 1.06.225.663-.129 1.294.139 1.39.727.129.62-.62.578-1.048.75h.032Z" fill="#000"/></g><defs><linearGradient id="h" x1="148.155" y1="46.293" x2="190.938" y2="46.999" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="b" x1="19.161" y1="218.102" x2="114.379" y2="218.102" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="d" x1="148.304" y1="37.201" x2="191.088" y2="37.907" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="e" x1="148.55" y1="21.954" x2="191.345" y2="22.66" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="f" x1="148.668" y1="15.278" x2="191.452" y2="15.974" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="g" x1="148.229" y1="42.016" x2="191.013" y2="42.722" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="c" x1="127.957" y1="330.35" x2="235.981" y2="330.35" gradientUnits="userSpaceOnUse"><stop stop-color="#7662AB"/><stop offset=".52" stop-color="#EE4F9C"/><stop offset="1" stop-color="#FDBD50"/></linearGradient><linearGradient id="i" x1="182.369" y1="35.164" x2="190.371" y2="35.164" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="j" x1="182.604" y1="20.152" x2="192.211" y2="20.152" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="k" x1="167.198" y1="12" x2="177.982" y2="12" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="l" x1="159.859" y1="37.422" x2="167.262" y2="37.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="m" x1="149" y1="43.133" x2="155.976" y2="43.133" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h328.918v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-pinprivate.svg b/browser/components/newtab/data/content/assets/mr-pinprivate.svg
new file mode 100644
index 0000000000..be3e0c0ba3
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-pinprivate.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="337" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g transform="translate(50 0)" clip-path="url(#a)"><g clip-path="url(#b)"><path d="m22.501 88.36 3.293-12.623 1.646-4.939 3.293 14.818h14.818l-8.78 6.037 6.585 12.073-9.879-2.195v13.171l-7.134-7.683-7.683 6.586-1.098-9.33h-9.33l6.586-4.939L7.135 79.03 22.5 88.36Z" fill="url(#c)"/><path d="m82.32 21.406 3.294-4.39 7.134 4.39-4.39 12.623-6.037-12.623Z" fill="url(#d)"/><path d="m204.155 62.017 4.939-8.232 8.781 6.037-3.293 15.367-10.427-13.172Z" fill="url(#e)"/><path d="m234.888 104.275 1.646-2.744 1.647-.549 3.841 2.196-2.195 6.036-4.939-4.939Z" fill="url(#f)"/><g clip-path="url(#g)"><path d="M170.702 157.546c-5.604-4.084-11.872-6.742-18.497-8.507-4.06-1.087-8.263-1.136-12.442-1.039-3.941.097-7.907-.024-11.848.29-3.514.266-7.005.967-10.59.532-2.992-.363-5.675-1.378-8.216-2.828-4.131-2.344-7.859-5.365-12.038-7.661-5.152-2.852-10.186-5.873-16.264-6.453-4.322-.411-8.43-.218-12.063 2.489-1.495 1.112-3.466 1.33-4.725 3.19-.546.798-1.306 1.426-1.496 2.538-.546 3.094-1.092 6.187-1.78 9.232-1.591 6.937-1.971 13.849-.76 20.809 1.068 6.09 4.321 10.731 9.165 14.404 4.06 3.07 8.714 3.626 13.51 3.771 5.272.145 10.33-1.426 15.482-2.079 3.419-.435 6.862-.556 10.257-.145 3.396.435 6.316 2.272 9.26 3.891a38.753 38.753 0 0 1 6.791 4.761c2.066 1.813 4.274 3.577 6.696 4.786 5.152 2.61 10.732 3.552 17.167 3.504 5.342.314 10.614-1.499 15.172-5.51 2.494-2.2 4.749-4.52 5.509-8 .499-2.369 1.069-4.761 2.018-6.985 1.781-4.108 3.087-8.338 4.132-12.664 1.329-5.389-.071-9.135-4.44-12.326Zm-69.333 4.834c-.404 1.184-1.71 1.402-2.754 1.668-1.995.507-3.966.145-5.936-.314-3.538-.871-7.148-1.571-10.21-3.819-.76-.532-1.544-1.039-1.401-2.151.118-1.112 1.068-1.353 1.875-1.668 1.354-.555 2.802-.845 4.393-.676 4.037.193 8.026.87 11.492 3.432.404.29.903.58 1.164.99.546.798 1.804 1.354 1.377 2.538Zm47.251 13.703c-.285.798-.998 1.523-1.829 1.789-1.187.338-2.374.822-3.086.556-5.984-.459-10.946-1.958-14.959-5.897-1.401-1.354-1.187-2.876.498-3.94 2.066-1.305 4.512-1.812 6.411-.604 2.565 1.692 5.438 2.659 8.073 4.181 1.282.749 2.612 1.45 3.704 2.514.475.435 1.473.628 1.188 1.401Z" fill="#7514CF"/></g><path d="M185.451 266c.362 2.456-.891 5.251-2.746 7.202-2.577 2.722-6.07 4.215-10.141 3.107-4.263-1.156-7.852-3.469-11.2-6.239-.723-.602-1.566-1.011-2.168-1.782-.217-.289-.603-.626-1.06-.289-.386.289 0 .771-.048.915-.868 2.192-.41 4.601-1.108 6.817-.795 2.505-.844 5.131-1.349 7.684-.41 2.096-1.108 4.167-1.373 6.287-.53 4.071-1.47 8.045-1.903 12.14-.747 7.178-.386 14.308-.289 21.486.024 2.288.626 4.48.481 6.769a61.294 61.294 0 0 0 0 7.274c.338 6.504-1.83 12.213-5.901 17.054-2.577 3.059-6.046 5.035-10.141 5.902-3.276.698-6.6.289-9.804.722-4.311.579-8.551.362-12.742-.144-3.204-.385-6.504-.795-9.587-2.288-2.457-1.205-5.275-1.711-7.973-2.457-5.974-1.662-11.972-3.18-17.945-4.77-4.264-1.132-8.359-2.89-12.574-4.239-3.613-1.156-7.274-2.12-10.888-3.252a47.694 47.694 0 0 1-10.14-4.504c-2.987-1.783-5.83-3.854-7.564-6.914-1.325-2.336-1.83-5.034-1.229-7.756.916-4.143 2.41-8.117 3.638-12.14a352.204 352.204 0 0 0 2.529-8.599c1.276-4.577 2.939-9.033 4.263-13.61 1.036-3.565 2.216-7.082 2.746-10.767.313-2.192 1.229-4.215 1.446-6.431a171.432 171.432 0 0 1 2.986-18.524c.314-1.493-.602-1.469-1.469-1.108-2.794 1.18-5.757 1.734-8.623 2.602-3.276.987-6.552 2.143-10.02 2.36-2.795.193-5.854-1.71-6.817-4.456-.482-1.397-1.036-2.794-1.325-4.239-.747-3.686 1.156-6.046 4.72-8.262a115.335 115.335 0 0 1 8.89-5.035c2.191-1.108 4.552-1.903 6.84-2.842 4.673-1.975 9.394-3.878 14.212-5.492 3.18-1.06 6.431-1.927 9.635-2.891 4.528-1.373 9.274-1.589 13.85-2.577 1.927-.41 4.071-.12 6.022-.578 2.819-.675 5.685-.626 8.503-1.156a6.522 6.522 0 0 1 1.205-.121c6.527 0 13.055-.433 19.559.145 4.215.361 8.382 1.06 12.549 1.782 3.349.578 6.721 1.084 9.949 2.24 2.962 1.06 6.166 1.614 8.936 2.987 2.818 1.397 5.998 2.144 8.503 4.336.771.674 2.096.988 3.18 1.542 2.168 1.108 4.191 2.384 5.973 3.95 2.626 2.312 5.155 4.793 7.395 7.491 2.385 2.843 4.914 5.54 6.841 8.768 2.096 3.517 3.541 7.178 3.324 11.924l-.048-.024Zm-91.918-20.306c-.988-.603-1.542.361-2.337.409-5.95.289-11.779 1.469-17.608 2.481-2.89.482-5.781 1.084-8.671 1.71-1.928.41-3.758 1.229-5.83 1.157-.722 0-1.541.529-1.638 1.782-.265 3.613-.554 7.25-1.83 10.719-.338.915-.12 2.023-.169 3.035 0 .361.048.771.53.626 2.12-.626 4.553-.409 6.455-1.349 2.89-1.397 6.07-1.397 9.01-2.481 2.143-.77 4.672-.433 7.033-.674 2.433-.241 4.914-.409 7.323-.771 7.756-1.156 15.488-.241 23.196.169 2.409.12 4.817.289 7.202.385 2.77.121 5.637-.144 8.334.386 4.168.819 8.359 1.228 12.598 1.493 3.252.193 6.335 1.229 9.274 2.409 2.192.867 4.625 1.349 6.576 2.842.385.289 1.156.458 1.228-.506.362-4.793 1.759-9.442 1.879-14.308.048-1.975-.746-2.698-1.975-3.541-2.264-1.541-4.769-2.673-7.419-3.179-5.058-.964-10.117-2.096-15.271-2.65-4.818-.506-9.587-1.301-14.429-1.397-4.818-.096-9.659-.337-14.477.289-3.01.385-6.046.675-8.984.988v-.024ZM55.763 395.76c-.578.818.072 1.252-.048 1.83-2.36-.458-4.697-.674-7.058-.722-1.108-.025-2.192-.603-2.866-1.205-2.072-1.879-4.697-2.818-6.793-4.625-1.903-1.638-2.553-3.733-3.155-5.877-.314-1.084 2.071-3.661 3.588-4.456 1.566-.819 3.325-.843 4.866-1.397 1.88-.651 3.782-.819 5.685-1.181 1.421-.289 2.89-.65 4.288-.506 3.781.41 7.467-.433 11.176-.65 3.132-.193 6.36-.265 9.467-.915.53-.121.867-.313.963.409.024.217.169.338.337.241 3.517-2.168 7.492-.722 11.225-1.349 3.156-.506 6.48-.265 9.732-.385 1.903-.048 4.046-.121 5.805.337 1.734.458 2.963-.891 4.625-.265 1.108.434 2.649-.506 3.709.699.097.12.097.144.241.072 2.457-1.397 4.866-.265 7.299.144.794.145 1.565-.385 2.481-.409 3.227-.048 6.407.385 9.587.626 1.782.121 3.589.506 5.395.337.602-.048 1.325-.192 1.301.844 0 .457.409.602.698.289 1.253-1.349 2.481-.482 3.686 0 .313.12.626.313.963.289 4.047-.506 7.684 1.204 11.49 1.999 2.048.433 3.637 1.301 5.227 2.625 1.951 1.638 2.168 3.565.699 5.637-1.59 2.216-3.71 3.372-6.215 4.095-1.686.482-3.324 1.397-4.962 1.758-2.312.506-4.649.94-6.913 1.59-3.107.891-6.311 1.277-9.442 1.566-2.843.265-5.709 1.541-8.648.554-.409-.145-.53.313-.674.289-.651-.121-1.133 1.421-1.927.096-.241-.385-.651.843-1.133.699-2.842-.747-5.54.506-8.262.433a109.785 109.785 0 0 0-6.286.024c-3.445.121-6.865.41-10.31.458-.819 0-2.12.843-2.553-.747 0-.048-.241-.096-.313-.048-3.204 1.855-6.649.337-9.949.482-1.975.096-4.143.506-6.19-.072-2.048-.554-4.143-.145-6.239-.241-1.638-.072-3.204-.675-4.89-.747-2.433-.096-4.865-.458-7.298-.626-1.205-.072-2.024-.602-2.385-2.048l-.024.049Zm51.668.867c.072-1.397-.795-2.433-1.999-2.505-1.277-.073-1.903.867-1.975 1.806-.097 1.06.216 2.433 1.734 2.337.963-.049 2.288-.049 2.24-1.614v-.024Zm-13.85-16.356c.77.169 1.493.048 1.565-.819.073-.771-.65-1.012-1.276-1.084-.892-.12-1.157.554-1.301 1.229-.193.963.578.578.987.674h.025Zm50.849 5.926c-1.253-.073-2.289-.169-3.324-.193-.362 0-.843.169-.603.747.121.289.506.819.627.65.843-1.108 2.36 0 3.3-1.228v.024ZM81.296 388.1c-.12-.53-.578-.964-1.06-1.108-.289-.073-.867.409-.747.915.097.409.048 1.036.867 1.036.603 0 .771-.338.964-.843h-.024ZM171.167 111.742c-1.397 1.084-2.216-.265-3.035-.77-1.975-1.181-3.734-2.698-5.588-4.047-.771-.554-1.711-.506-2.578-.626-.915-.121-1.18-.627-1.59-1.422-.77-1.445-.818-2.914-1.083-4.432-.145-.915-.868-1.686-.554-2.794.722-2.36 3.372-5.588 5.877-5.082 3.228.674 6.672 1.445 8.599 4.335.723 1.084 1.59 1.253 2.409 1.759 2.818 1.782 5.805 3.227 8.527 5.251 1.445 1.06 3.685 1.686 5.299 2.794 2.409 1.662 5.155 2.722 7.419 4.649.892.771 2.144 1.108 3.156 1.758 2.842 1.831 5.323 4.143 8.069 6.143 1.494 1.084 3.18 1.879 4.649 3.059 2.867 2.336 5.902 4.432 8.792 6.72 2.65 2.096 5.564 3.878 8.383 5.757 2.264 1.494 4.287 3.373 6.479 5.035 1.855 1.397 3.806 2.721 5.54 4.215 2.505 2.168 5.396 3.734 7.997 5.685 1.879 1.397 3.999 2.673 5.998 3.974 1.325.867 2.794 1.566 3.999 2.722 1.06 1.012 2.288 1.999 3.589 2.722 1.758.987 3.3 2.264 4.649 3.637 1.301 1.325 3.083 1.831 4.312 3.204 1.252 1.445 3.275 2.168 4.456 3.517 1.59 1.83 3.709 2.866 5.419 4.504 1.759 1.686 3.373 3.493 5.107 5.203.964.963 1.108 2.192 1.012 3.276-.313 3.011-2.096 5.323-4.264 7.347-.771.698-4.6.385-5.949-.265-2.722-1.277-5.324-2.722-7.805-4.408-1.83-1.229-3.709-2.385-5.492-3.662-3.974-2.866-8.334-5.154-12.26-8.117-3.084-2.361-6.504-4.312-9.467-6.769-3.348-2.77-6.913-5.227-10.165-8.093a43.386 43.386 0 0 0-4.48-3.469c-1.614-1.132-2.915-2.722-4.529-3.758-1.493-.963-2.577-2.36-4.167-3.227-1.734-.94-3.107-2.53-4.769-3.662-1.156-.795-2.24-1.71-3.372-2.409-2.915-1.782-5.782-3.709-8.359-5.877-1.927-1.638-4.697-2.264-5.901-4.793-1.494.216-2.313-.964-3.3-1.711-3.132-2.36-6.191-4.841-9.226-7.322-.554-.458-.939-1.132-1.277-1.783-.144-.241-.168-.481-.481-.602-3.493-1.445-6.215-4.047-9.202-6.215-.747-.529-.626-1.108-.795-1.902l-.048-.049Zm56.269 29.484c-.337-.699-.843-1.422-1.59-1.927-2.457-1.614-4.962-3.156-7.419-4.818-1.782-1.228-3.613-2.433-5.203-3.878-2.047-1.879-4.263-3.613-6.504-5.227-2.143-1.542-4.287-3.18-6.551-4.577-3.084-1.903-5.781-4.311-8.937-6.19-3.131-1.855-6.504-3.324-9.442-5.516-2.626-1.951-5.661-3.276-8.455-4.986-2.891-1.735-5.516-3.758-8.118-5.878-.746-.602-1.469-1.806-2.577-.024-.771 1.253-1.204 2.168-.048 3.18.915.843 1.951 1.565 3.035 2.216.602.361.795.578.409 1.228-.144.241-.53.675-.024 1.06.265.193.723.217.795.048.699-1.638 1.518-.217 2.264-.12 1.012.144 1.253 1.325 2 1.614 2.746 1.084 4.576 3.42 7.13 4.817 2.384 1.301 4.335 3.348 6.551 4.89 2.385 1.638 4.312 3.758 6.576 5.516 2.626 2.023 5.179 4.167 7.925 6.022 1.397.963 2.891 1.831 4.312 2.794 1.855 1.253 3.854 2.337 5.54 3.758 2.409 2.047 5.083 3.733 7.443 5.805 1.614 1.421 3.686 2.144 5.179 3.782.675.746 2.096 1.854 2.794 1.325 1.446-1.157 2.337-2.939 2.963-4.963l-.048.049Zm38.131 27.893c.024 2.12 1.156 4.095-.289 6.143-.265.361-1.229 1.132-.434 1.71 2.385 1.734 4.962 3.203 7.395 4.914 1.782 1.252 3.974 1.927 5.877 3.107.554.337 1.397.482 2.048-.458 1.349-1.854 1.228-3.661-.675-5.203-3.781-3.059-7.828-5.757-11.514-8.984-.578-.506-1.373-1.494-2.432-1.229h.024Zm-33.892-24.834a9.377 9.377 0 0 1-2.553 3.998c-1.084 1.012-.963 1.735.241 2.554 1.541 1.06 2.794 2.505 4.408 3.3.939-1.47 2.529-2.698 3.059-4.673.241-.916.41-1.301-.554-1.855-1.566-.94-2.987-2.144-4.601-3.324ZM147.585 201.106c-6.528.048-12.188-.892-17.415-3.493-2.457-1.228-4.697-2.963-6.793-4.769a39.366 39.366 0 0 0-6.889-4.746c-2.987-1.614-5.95-3.468-9.394-3.878-3.445-.433-6.937-.289-10.406.145-5.251.65-10.382 2.216-15.705 2.071-4.866-.144-9.587-.698-13.706-3.757-4.914-3.638-8.214-8.287-9.298-14.333-1.228-6.961-.843-13.826.77-20.739.7-3.035 1.277-6.142 1.831-9.226.193-1.084.94-1.71 1.518-2.529 1.277-1.83 3.276-2.071 4.793-3.179 3.686-2.674 7.829-2.867 12.237-2.457 6.166.578 11.273 3.589 16.5 6.431 4.24 2.288 8.021 5.299 12.213 7.636 2.577 1.445 5.299 2.457 8.334 2.818 3.637.434 7.178-.265 10.743-.53 4.023-.313 8.021-.192 12.02-.289 4.215-.096 8.503-.072 12.622 1.012 6.72 1.758 13.079 4.408 18.764 8.503 4.432 3.179 5.877 6.889 4.528 12.285-1.083 4.311-2.408 8.527-4.191 12.621-.963 2.192-1.541 4.601-2.071 6.962-.747 3.493-3.059 5.781-5.589 7.973-4.625 3.998-9.972 5.829-15.392 5.516l-.024-.048Zm-87.149-38.589a17.59 17.59 0 0 0 .169 4.047c.843 5.372 3.251 9.78 7.756 12.935.843.578 1.59 1.325 2.48 1.783 3.951 2.023 8.19 2.216 12.502 2.023 1.927-.096 3.758-.578 5.637-.819 4.312-.554 8.6-1.397 12.983-1.518 3.782-.096 7.491.217 11.008 1.783 4.601 2.023 8.913 4.552 12.743 7.828 4.528 3.854 9.635 6.456 15.584 7.154 4.36.506 8.816.964 13.056-.505 4.841-1.687 8.696-4.842 10.791-9.66.891-2.023 1.301-4.263 2.048-6.359 1.878-5.179 3.805-10.333 4.913-15.753.41-2.072.073-3.902-1.71-5.396-1.686-1.421-3.348-2.818-5.299-3.854-3.661-1.975-7.467-3.637-11.345-5.058-5.733-2.096-11.731-1.807-17.681-1.951-5.949-.145-11.875.747-17.8.939-4.192.145-8.022-1.06-11.683-2.842-4.071-1.975-7.443-5.107-11.442-7.275-4.769-2.601-9.394-5.419-14.886-6.407-4.649-.843-8.84-.506-13.104 2.096-2.794 1.71-4.07 3.324-4.432 6.696-.722 6.721-3.227 13.224-2.312 20.137l.024-.024ZM35.481 100.734c-.12 3.541.41 6.865-.096 10.165-.217 1.446-.362 2.843-2.216 3.18-1.903.361-2.794-.626-3.59-2.168-.818-1.614-1.83-3.131-2.794-4.673-.24-.361-.578-1.132-.89-.891-.507.409-1.205.578-1.543 1.325-1.06 2.336-3.083 3.83-5.275 4.914-1.493.722-2.48-.241-2.866-1.831-.482-2.072 0-4.095.096-6.118.073-1.614-.867-2.024-1.999-1.711-2.264.627-4.336-.144-6.48-.457-1.734-.241-2.625-1.494-3.01-3.06-.241-.939-.025-1.806 1.011-2.432 1.638-.988 3.348-1.807 5.179-2.24 1.59-.386 1.566-1.157 1.012-2.289-1.494-2.962-3.035-5.901-4.48-8.888-1.205-2.505-2.313-5.083-3.47-7.612-.312-.698-.288-1.445-.192-2.168.12-.77 1.06-1.517 1.325-1.276 1.18 1.084 2.264-.458 3.42.12 1.132.578 2.096 1.373 3.084 2.12 2.77 2.047 5.54 4.119 8.238 6.263 1.035.843 1.348.505 1.493-.579.313-2.432 1.3-4.745 1.71-7.13.29-1.637 1.012-3.13 1.18-4.793.12-1.156 1.951-2.939 3.035-2.939 1.542 0 2.24 1.06 2.554 2.337.915 3.806 2.264 7.491 2.65 11.417.144 1.446.602 2.698 2.673 2.554 1.614-.12 3.252-.458 4.914-.145 2.072.41 4.143-.433 6.19.024.868.193 1.831.193 2.169 1.277.337 1.132.409 2.216-.723 3.01-1.927 1.374-4.215 1.976-6.335 2.964-.386.192-.386-.049-.506-.362-.169-.385-.843-.216-.819-.048.217.94-1.132 1.59-.145 2.843 1.687 2.143 3.734 3.974 5.107 6.359.337.602.819 1.132 1.108 1.734.554 1.132 1.614 2.312.482 3.613-1.18 1.349-2.867 1.566-4.408.988-1.903-.699-3.686-1.759-5.516-2.674a42.21 42.21 0 0 1-1.325-.698l.048-.025Zm-4.07 5.589c-.434-2.457-.218-4.721-.675-6.962-.313-1.517.192-2.962 1.614-3.757 1.397-.771 2.794-.048 3.974.626.723.41 1.445.867 2.216 1.204.217.097.337.771.747.217.217-.289.144-.506-.048-.746a29.046 29.046 0 0 1-1.06-1.35c-.964-1.204-2-2.384-2.843-3.66-1.18-1.783-.89-3.132.723-4.505.506-.434 1.205-.65 1.542-1.325a6.303 6.303 0 0 0-1.903 0c-4.745.723-6.504-.723-7.106-5.54-.24-1.903-.77-3.758-1.18-5.637h-.434c-.024 3.011-1.325 5.757-1.71 8.72-.169 1.349-1.036 2.65-2.264 3.204-1.229.53-2.53.024-3.662-.867-2.746-2.144-5.588-4.216-8.406-6.287-.169-.12-.241-.627-.627-.265-.313.313-.216.626.12.867.772.53 1.06 1.445 1.205 2.192.217 1.084 1.253 1.903 1.18 2.794-.096 1.204.892 1.397 1.205 2.096.602 1.325 1.782 2.529 1.18 4.215-.217.626.386.506.627.723.722.674 1.902 1.084 1.83 2.312-.072 1.132-.698 1.855-1.782 2.313-1.084.457-2.096 1.083-3.156 1.637.891.241 1.71.17 2.505.145 2.915-.169 5.565 2.288 5.275 5.058-.048.434-.168 1.036.362 1.229.626.241.674-.386.915-.747.241-.385.578-.722.843-1.084 1.975-2.674 3.469-2.649 5.902-.433 1.132 1.035 1.325 2.649 2.866 3.589l.024.024ZM207.299 43.286c.12-1.132.433-2.264.361-3.372-.144-1.975 1.229-2.168 2.578-2.385.819-.144 1.276.458 1.469 1.157.506 1.806.65 3.637.723 5.516.12 2.529.939 4.938 2.095 7.13 1.036 1.999 3.107 2.625 5.251 2.77.795.048 1.831-.169 2.12.698.313.964.819 1.927-.265 3.132-1.301 1.445-1.566 3.54-2.072 5.444-1.011 3.902-1.3 7.948-2.456 11.803-.29.987-.964 2.336-2.457 2.12-2.433-.362-2.77-.868-2.963-2.988-.241-2.529-.819-4.986-1.518-7.419-.626-2.288-2.312-3.589-4.336-4.576-2.505-1.229-4.239-3.132-5.082-5.83-.169-.554-.145-1.228.482-1.18 2.047.12 3.276-.819 3.926-2.65 1.084-3.01 2.072-6.07 2.12-9.321l.024-.049Zm-.843 14.55c3.589 1.95 7.033 3.709 7.852 8.093.314-2.553 1.253-4.89 1.831-7.323.12-.554-.096-1.06-.602-1.3-2.288-1.084-4.071-2.722-5.516-5.203-.578 2.529-1.927 4.167-3.541 5.732h-.024ZM84.668 9.897c-.53-1.325.193-2.602.41-3.854.217-1.301 0-2.578.217-3.854.168-.94.337-1.952 1.59-2.192.963-.193 3.058 1.95 2.697 3.107-.385 1.276.458 2.77-.722 3.902-.12.12-.073.626.072.819 1.517 2.047 1.686 4.673 2.987 6.793.265.457.457.65 1.06.53.89-.169 1.806-.362 2.746.192.939.53 1.18 1.301.794 2.12-2.697 5.974-4.119 12.309-5.708 18.62-.29 1.084-.627 2.601-2.144 2.674-1.71.072-2.53-1.036-2.698-3.108-.361-3.878-1.132-7.66-2.963-11.104-.891-1.686-2.264-3.228-4.046-4.023-2.072-.94-1.759-2.866-2.168-4.48-.169-.626 1.06-1.204 1.638-.867.096.048.264.12.313.072 1.445-1.084 4.215-.217 4.48-3.035.024-.337.193-.578.482-.65.94-.217 1.3-.723 1.011-1.687l-.048.025Zm3.927 16.716c1.156-2.36 1.662-4.624 2.432-6.768.217-.602-.144-1.084-.602-1.253-1.47-.626-2.433-1.734-3.203-3.059-.41-.674-.988-.77-1.253-.024-.289.795-.867 1.204-1.373 1.758-.747.82-1.012 1.494.24 2.481 2.048 1.614 3.012 4.071 3.783 6.865h-.024ZM6.022 167.388c-.434-1.565-1.253-2.746-2.072-3.878-.722-1.011-.674-2.288-1.349-3.324-.41-.626-.072-1.373.554-1.806.65-.458 1.325-.603 2.048-.073.698.53 1.204 1.253 1.638 1.976.554.963.795 1.228 1.541.096 1.012-1.469 2.602-1.204 3.373.506.554-.723 1.06-1.397 1.878-1.903 1.47-.891 2 .313 2.53 1.012.385.505.843 1.686-.579 1.951-.264.048-.264.24-.216.361.963 1.999-1.084 2.529-1.927 3.42-.434.458-.554.771-.578 1.229a.924.924 0 0 0 .963 1.012c.843-.049 1.614.481 2.313.409 2.047-.241 2.48 1.349 2.432 2.505-.072 1.494-1.517 1.759-2.89 1.494-.313-.049-.65 0-.988 0 .747 2.071.506 2.746-1.204 3.589-2.024.987-2.553.746-3.469-1.614-.12-.313-.168-.675-.289-.988-.722-1.806-1.276-1.903-2.529-.433-.337.385-.65.843-1.036 1.132-.602.433-1.228.963-2.047.578-.747-.361-1.35-.867-1.35-1.807 0-.457.194-1.084-.505-.987-1.445.216-2.144-.771-2.216-1.759-.072-.939.988-1.662 1.807-2.216 1.228-.843 2.673-.554 4.215-.506l-.048.024ZM134.867 49.45c1.542.12 2.577 1.107 3.18 2.336 1.951 3.878 4.022 7.684 5.684 11.706 1.157 2.819 2.337 5.66 3.734 8.407.963 1.879 1.975 3.661 3.276 5.3 1.469 1.854 1.325 2.649-.482 3.95-1.084.77-2.577.265-3.493-1.398-1.108-2.023-2.336-3.998-3.203-6.166-.313-.747-1.132-1.349-1.59-2.168-1.012-1.758-1.927-3.661-2.987-5.275-1.517-2.336-2.505-4.914-3.878-7.274-1.108-1.928-1.638-4.095-2.192-6.24-.361-1.348.843-3.227 1.927-3.155l.024-.024ZM76.912 64.001c-.482 1.542-.723 3.42-.217 5.348.265.963.554 1.59 1.71 1.662 2.072.12 2.795 1.397 1.735 3.18-1.518 2.529-2.216 5.37-3.252 8.093-.313.843-.77 1.71-1.397 2.312-1.132 1.132-3.035.29-3.469-1.373-.626-2.36-.746-4.841-1.782-7.082-.434-.915-.675-2.047-1.879-2.24-1.18-.192.169-1.59-1.108-1.95-1.3-.362.072-1.277.024-1.952-.024-.53.602-.65.434-1.349-.241-.94.867-1.204 1.493-1.204 2.192-.048 2.602-.41 2.65-2.89 0-1.133.216-2.072 1.3-2.915.94-.723 1.88-.675 2.554-.362.843.362 1.276 1.421 1.204 2.77v-.048ZM113.381 109.428c-1.181-.217-2.409-.361-2.698-1.758-.289-1.421.409-2.24 1.686-2.915 3.396-1.782 7.25-1.999 10.767-3.396 2.024-.795 4.167-1.614 6.287-1.783.988-.072 1.397-1.06 2.433-.819.939.217 1.951.458 3.011.097.964-.338 1.734-.675 2.072-1.686.529-1.566 1.878-1.277 2.89-.964.819.241 1.229 1.156 1.132 2.24-.313 3.132-2.77 3.927-5.106 4.914-2.915 1.229-6.071 1.542-9.106 2.313-3.757.963-7.563 1.662-11.128 3.251-.723.314-1.542.362-2.264.53l.024-.024ZM135.011 86.98c-.554-.336-.819.025-1.373.483-.77.65-1.782.192-2.649-.313-3.421-1.976-7.034-3.59-10.743-4.963a397.265 397.265 0 0 0-10.623-3.805c-1.373-.482-2.12-1.325-1.855-2.746.241-1.277 1.662-2.144 3.108-1.71 2.938.89 5.949 1.541 8.767 2.986 1.735.891 3.734 1.494 5.541 2.385 1.83.915 3.854 1.397 5.636 2.288 2.481 1.253 5.299.82 7.805 2.048 1.18.578 1.156 1.47 1.084 2.095-.097.892-.964 1.831-2.024 1.494-.891-.29-1.71-.145-2.698-.217l.024-.024ZM231.868 100.377c-.409-.722.747-.506 1.036-.915 1.108-1.542 2.288-3.035 3.372-4.577.434-.626.891-1.95.602-3.107-.217-.94.289-1.759.482-2.626.289-1.276 1.469-1.084 2.216-1.59.578.892 2.023 1.205 1.927 2.53-.096 1.252-.217 2.577-1.228 3.517-.217.192-.506.337-.289.65.168.24.433.385.602-.048.53.313.53.94.65 1.42.265 1.06.964 1.543 1.831 2.072.891.554 2.023 1.253 1.349 2.746-.94 2.072-1.807 4.192-2.722 6.263-.217.458-.506.867-.53 1.421-.072 1.084-.867 1.422-1.783 1.614-.963.193-1.613-.192-1.999-1.036-.289-.626-.506-1.276-.722-1.927-.675-1.999-2.289-3.059-3.927-4.143-.674-.433-.626-1.3-.891-2.312l.024.048Zm8.118.651c-.94.096-1.012-1.18-1.927-1.205-.579 0-.916.795-.868.843.554.554 1.108 1.253 1.976 1.205.265 0 .795-.169.819-.843ZM162.833 20.113c0 .29.024.723-.097 1.085-.385 1.06.313 1.252 1.036 1.252.891 0 1.783-.169 2.674-.265.987-.096 1.903.169 2.312 1.132.362.891-.385 1.373-.819 2.072-1.011 1.614-2.529 1.493-3.878 1.42-1.276-.047-1.325.555-1.108 1.277.506 1.542-.433 2.554-1.084 3.686-.217.361-.482.289-.867.217-.939-.193-1.975-.193-2.216-1.421-.072-.458-.096-.916-.12-1.373-.073-1.157-.217-2.048-1.759-2.216-1.036-.12-1.831-1.108-1.782-2.24.048-1.036.795-1.663 1.854-1.88 1.06-.216 1.59-.794 1.446-2.023-.097-.891.12-1.83.216-2.746.049-.313.073-.626.554-.747.579-.144.554-.216.338-.722-.024-.072-.121-.097-.193-.145.096-.048.217-.072.313-.144 1.325-.795 2.12-.482 2.698.987.337.867.361 1.783.458 2.794h.024ZM27.315 12.883c1.277 1.132 2.65 1.036 4.168.843 1.541-.193 1.637 1.541 2.216 2.48.505.796-.458 1.35-1.06 1.687-1.35.795-1.71 2.313-.53 3.276.722.578.77 1.421 1.204 2.096.482.722-.433 1.565-.626 1.517-2.048-.361-2.842 1.518-4.24 2.264-.819.434-1.42.097-1.999-.41-.53-.457-.433-.915-.096-1.517.361-.65-.241-1.445.144-2.192.024-.072-.36-.457-.578-.505-.602-.12 0 .36-.216.505-.627.506-1.229.265-1.855-.024-.916-.41-1.373-1.108-1.036-2.023.53-1.397.915-2.866 2.216-3.902.626-.506 1.3-1.301.506-2.289-.265-.337-.097-.65.217-.89.265-.194.361.071.554.192.265.168-.265.963.481.65.458-.193.603-.602.338-1.108-.049-.096.072-.313.168-.626l.024-.024ZM202.915 198.579c0-.41-.073-.819 0-1.205.289-1.276-.121-1.71-1.422-1.397-.77.193-1.758.53-1.228-1.036.144-.409-1.012-.481-.554-1.565.53-1.253 1.18-1.735 2.36-1.59.819.096 1.036-.048 1.108-.964.121-1.445.506-2.89 1.494-4.095.265-.337.433-.963.915-.264.675.987.867-1.205 1.686-.193.578.722-.361 1.252.049 1.734.626.747.481 1.638.313 2.337-.313 1.276.265 1.3 1.18 1.349 1.18.072 2.457.072 3.18 1.228.409.65.602 1.469.072 2.096-.843 1.011-1.951 1.638-3.372 1.373-1.205-.241-1.687.313-1.398 1.493.338 1.349.29 1.421-1.059 1.518-.241 0-.554.192-.699.385-.169.265-.072.53.289.65.386.121.554.386.386.795-.169.41-.506.41-.868.434-1.782.168-2.601-.843-2.505-3.156l.073.073ZM33.241 202.531c-1.132-.771-2.023-.049-2.818 1.035-.626.892-1.47.314-2.168.169-.578-.12-.698-.723-.77-1.349-.17-1.277.65-2.746-.627-3.83.963-1.084.096-3.011 2-3.83.794-.337 1.228-1.662 2.047-2.384.843-.747 1.71-.747 2.384.096.265.337.602.723.988.891 1.517.65 2.023 1.71.987 2.963-1.18 1.397-.433 2.65-.048 3.926.41 1.397-.24 2.337-1.95 2.313h-.025Z" fill="#000"/><path d="M142.792 179.623c-6.986-.337-12.55-2.553-17.295-6.576-2.963-2.529-2-6.889 1.011-8.72 1.253-.771 2.602-1.686 4.36-1.638 1.855.048 3.589.313 5.372.843 1.662.506 3.179 1.06 4.601 2.144 1.541 1.156 3.396 1.855 5.034 2.867 1.204.746 2.36 1.589 3.493 2.457 2.986 2.312 1.806 6.286-1.205 7.322-1.927.675-3.902 1.542-5.371 1.325v-.024Zm.12-3.035c.723.265 1.927-.217 3.131-.578a2.928 2.928 0 0 0 1.855-1.759c.289-.794-.722-.987-1.204-1.421-1.132-1.036-2.457-1.734-3.782-2.505-2.65-1.517-5.564-2.481-8.19-4.167-1.903-1.229-4.408-.699-6.503.602-1.687 1.06-1.903 2.578-.506 3.926 4.095 3.903 9.129 5.42 15.175 5.878l.024.024ZM94.376 165.724c-5.107-.77-10.117-1.951-14.646-4.624-1.95-1.157-3.227-2.891-3.637-5.179-.193-1.108 1.397-3.276 2.939-3.999 1.903-.891 3.974-1.132 6.022-1.373 6.335-.747 11.658 1.759 16.042 5.854 3.782 3.516 2.867 6.238-1.83 8.43-1.422.675-3.132 1.132-4.866.867l-.024.024Zm-8.672-12.067c-1.614-.169-3.06.12-4.456.674-.82.313-1.783.554-1.903 1.662-.12 1.108.674 1.59 1.421 2.144 3.107 2.24 6.769 2.939 10.358 3.806 2 .481 3.998.819 5.998.313 1.06-.265 2.384-.482 2.818-1.662.433-1.181-.867-1.735-1.397-2.529-.265-.41-.771-.675-1.18-.988-3.517-2.553-7.564-3.228-11.683-3.42h.024Z" fill="#000"/><g clip-path="url(#h)"><path d="m54.69 276.156 2.707-27.615 49.817-10.83 53.607 12.996-5.957 25.449-45.484-8.663-54.69 8.663Z" fill="url(#i)"/><path d="m22.5 88.36 3.294-12.623 1.646-4.939 3.293 14.818H45.55l-8.78 6.037 6.585 12.073-9.878-2.195v13.171l-7.135-7.683-7.683 6.586-1.098-9.33h-9.33l6.587-4.939L7.134 79.03l15.367 9.33Z" fill="url(#j)"/><path d="m82.32 21.406 3.293-4.39 7.134 4.39-4.39 12.623-6.037-12.623Z" fill="url(#k)"/><path d="m204.154 62.017 4.94-8.232 8.78 6.037-3.292 15.367-10.428-13.172Z" fill="url(#l)"/><path d="m234.887 104.275 1.647-2.744 1.646-.549 3.842 2.196-2.196 6.036-4.939-4.939Z" fill="url(#m)"/><g clip-path="url(#n)"><path d="M170.702 157.546c-5.604-4.084-11.872-6.742-18.497-8.507-4.06-1.087-8.263-1.136-12.441-1.039-3.942.097-7.907-.024-11.849.29-3.514.266-7.004.967-10.59.532-2.991-.363-5.674-1.378-8.215-2.828-4.132-2.344-7.859-5.365-12.038-7.661-5.153-2.852-10.187-5.873-16.265-6.453-4.322-.411-8.43-.218-12.062 2.489-1.496 1.112-3.467 1.33-4.725 3.19-.546.798-1.306 1.426-1.496 2.538-.546 3.094-1.092 6.187-1.78 9.232-1.592 6.937-1.972 13.849-.76 20.809 1.068 6.09 4.32 10.731 9.165 14.404 4.06 3.07 8.714 3.626 13.51 3.771 5.271.145 10.329-1.426 15.481-2.079 3.419-.435 6.862-.556 10.258-.145 3.395.435 6.316 2.272 9.26 3.891a38.79 38.79 0 0 1 6.791 4.761c2.065 1.813 4.274 3.577 6.695 4.786 5.153 2.61 10.733 3.552 17.167 3.504 5.343.314 10.614-1.499 15.173-5.51 2.493-2.2 4.749-4.52 5.509-8 .498-2.369 1.068-4.761 2.018-6.985 1.781-4.108 3.086-8.338 4.131-12.664 1.33-5.389-.071-9.135-4.44-12.326Zm-69.333 4.834c-.403 1.184-1.71 1.402-2.754 1.668-1.994.507-3.965.145-5.936-.314-3.538-.871-7.147-1.571-10.21-3.819-.76-.532-1.543-1.039-1.4-2.151.118-1.112 1.068-1.353 1.875-1.668 1.353-.555 2.802-.845 4.393-.676 4.036.193 8.025.87 11.492 3.432.403.29.902.58 1.163.99.546.798 1.805 1.354 1.377 2.538Zm47.251 13.703c-.285.798-.997 1.523-1.828 1.789-1.187.338-2.375.822-3.087.556-5.983-.459-10.946-1.958-14.959-5.897-1.401-1.354-1.187-2.876.499-3.94 2.066-1.305 4.511-1.812 6.411-.604 2.564 1.692 5.437 2.659 8.073 4.181 1.282.749 2.612 1.45 3.704 2.514.475.435 1.472.628 1.187 1.401Z" fill="#7514CF"/></g><path d="M185.451 266.003c.362 2.457-.891 5.252-2.746 7.203-2.577 2.722-6.07 4.215-10.141 3.107-4.263-1.156-7.852-3.469-11.2-6.239-.723-.602-1.566-1.011-2.168-1.782-.217-.289-.603-.627-1.06-.289-.386.289 0 .771-.048.915-.868 2.192-.41 4.601-1.108 6.817-.795 2.505-.844 5.131-1.349 7.684-.41 2.095-1.108 4.167-1.373 6.287-.53 4.071-1.47 8.045-1.903 12.14-.747 7.178-.386 14.308-.289 21.486.024 2.288.626 4.48.481 6.769a61.294 61.294 0 0 0 0 7.274c.338 6.504-1.83 12.213-5.901 17.054-2.577 3.059-6.046 5.035-10.141 5.902-3.276.698-6.6.289-9.804.722-4.311.578-8.551.362-12.742-.144-3.204-.386-6.504-.795-9.587-2.288-2.457-1.205-5.275-1.711-7.973-2.457-5.974-1.662-11.972-3.18-17.945-4.77-4.264-1.132-8.359-2.89-12.574-4.239-3.613-1.156-7.274-2.12-10.888-3.252a47.745 47.745 0 0 1-10.14-4.504c-2.987-1.783-5.83-3.854-7.564-6.914-1.325-2.336-1.83-5.034-1.229-7.756.916-4.143 2.41-8.117 3.638-12.14a352.204 352.204 0 0 0 2.529-8.599c1.276-4.577 2.939-9.033 4.263-13.61 1.036-3.565 2.216-7.082 2.746-10.767.313-2.192 1.229-4.215 1.446-6.431a171.432 171.432 0 0 1 2.986-18.524c.314-1.493-.602-1.469-1.469-1.108-2.794 1.18-5.757 1.734-8.623 2.602-3.276.987-6.552 2.143-10.02 2.36-2.795.193-5.854-1.71-6.817-4.456-.482-1.397-1.036-2.794-1.325-4.24-.747-3.685 1.156-6.046 4.72-8.262a115.657 115.657 0 0 1 8.89-5.034c2.191-1.108 4.552-1.903 6.84-2.842 4.673-1.975 9.394-3.878 14.212-5.492 3.18-1.06 6.431-1.927 9.635-2.891 4.528-1.373 9.274-1.59 13.85-2.577 1.927-.41 4.071-.121 6.022-.578 2.819-.675 5.685-.627 8.503-1.156a6.522 6.522 0 0 1 1.205-.121c6.527 0 13.055-.433 19.559.145 4.215.361 8.382 1.059 12.549 1.782 3.349.578 6.721 1.084 9.949 2.24 2.962 1.06 6.166 1.614 8.936 2.987 2.818 1.397 5.998 2.144 8.503 4.336.771.674 2.096.988 3.18 1.542 2.168 1.108 4.191 2.384 5.973 3.95 2.626 2.312 5.155 4.793 7.395 7.491 2.385 2.843 4.914 5.54 6.841 8.768 2.096 3.517 3.541 7.178 3.324 11.924l-.048-.025Zm-91.918-20.305c-.988-.603-1.542.361-2.337.409-5.95.289-11.779 1.469-17.608 2.481-2.89.482-5.781 1.084-8.671 1.71-1.928.41-3.758 1.229-5.83 1.156-.722 0-1.541.53-1.638 1.783-.265 3.613-.554 7.25-1.83 10.719-.338.915-.12 2.023-.169 3.035 0 .361.048.771.53.626 2.12-.626 4.553-.409 6.455-1.349 2.89-1.397 6.07-1.397 9.01-2.481 2.143-.77 4.672-.433 7.033-.674 2.433-.241 4.914-.41 7.323-.771 7.756-1.156 15.488-.241 23.196.169 2.409.12 4.817.289 7.202.385 2.77.121 5.637-.144 8.334.386 4.168.819 8.359 1.228 12.598 1.493 3.252.193 6.335 1.228 9.274 2.409 2.192.867 4.625 1.349 6.576 2.842.385.289 1.156.458 1.228-.506.362-4.793 1.759-9.442 1.879-14.308.048-1.975-.746-2.698-1.975-3.541-2.264-1.541-4.769-2.673-7.419-3.179-5.058-.964-10.117-2.096-15.271-2.65-4.818-.506-9.587-1.301-14.429-1.397-4.818-.096-9.659-.337-14.477.289-3.01.385-6.046.674-8.984.988v-.024ZM55.763 395.76c-.578.818.072 1.252-.048 1.83-2.36-.458-4.697-.674-7.058-.722-1.108-.025-2.192-.603-2.866-1.205-2.072-1.879-4.697-2.818-6.793-4.625-1.903-1.638-2.553-3.733-3.155-5.877-.314-1.084 2.071-3.661 3.588-4.456 1.566-.819 3.325-.843 4.866-1.397 1.88-.651 3.782-.819 5.685-1.181 1.421-.289 2.89-.65 4.288-.506 3.781.41 7.467-.433 11.176-.65 3.132-.193 6.36-.265 9.467-.915.53-.121.867-.313.963.409.024.217.169.338.337.241 3.517-2.168 7.492-.722 11.225-1.349 3.156-.506 6.48-.265 9.732-.385 1.903-.048 4.046-.121 5.805.337 1.734.458 2.963-.891 4.625-.265 1.108.434 2.649-.506 3.709.699.097.12.097.144.241.072 2.457-1.397 4.866-.265 7.299.144.794.145 1.565-.385 2.481-.409 3.227-.048 6.407.385 9.587.626 1.782.121 3.589.506 5.395.337.602-.048 1.325-.192 1.301.844 0 .457.409.602.698.289 1.253-1.349 2.481-.482 3.686 0 .313.12.626.313.963.289 4.047-.506 7.684 1.204 11.49 1.999 2.048.433 3.637 1.301 5.227 2.625 1.951 1.638 2.168 3.565.699 5.637-1.59 2.216-3.71 3.372-6.215 4.095-1.686.482-3.324 1.397-4.962 1.758-2.312.506-4.649.94-6.913 1.59-3.107.891-6.311 1.277-9.442 1.566-2.843.265-5.709 1.541-8.648.554-.409-.145-.53.313-.674.289-.651-.121-1.133 1.421-1.927.096-.241-.385-.651.843-1.133.699-2.842-.747-5.54.506-8.262.433a109.785 109.785 0 0 0-6.286.024c-3.445.121-6.865.41-10.31.458-.819 0-2.12.843-2.553-.747 0-.048-.241-.096-.313-.048-3.204 1.855-6.649.337-9.949.482-1.975.096-4.143.506-6.19-.072-2.048-.554-4.143-.145-6.239-.241-1.638-.072-3.204-.675-4.89-.747-2.433-.096-4.865-.458-7.298-.626-1.205-.072-2.024-.602-2.385-2.048l-.024.049Zm51.668.867c.072-1.397-.795-2.433-1.999-2.505-1.277-.073-1.903.867-1.975 1.806-.097 1.06.216 2.433 1.734 2.337.963-.049 2.288-.049 2.24-1.614v-.024Zm-13.85-16.356c.77.169 1.493.048 1.565-.819.073-.771-.65-1.012-1.276-1.084-.892-.12-1.157.554-1.301 1.229-.193.963.578.578.987.674h.025Zm50.849 5.926c-1.253-.073-2.289-.169-3.324-.193-.362 0-.843.169-.603.747.121.289.506.819.627.65.843-1.108 2.36 0 3.3-1.228v.024ZM81.296 388.1c-.12-.53-.578-.964-1.06-1.108-.289-.073-.867.409-.747.915.097.409.048 1.036.867 1.036.603 0 .771-.338.964-.843h-.024ZM171.167 111.742c-1.397 1.084-2.216-.265-3.035-.77-1.975-1.181-3.734-2.698-5.588-4.047-.771-.554-1.711-.506-2.578-.626-.915-.121-1.18-.627-1.59-1.422-.77-1.445-.818-2.914-1.083-4.432-.145-.915-.868-1.686-.554-2.794.722-2.36 3.372-5.588 5.877-5.082 3.228.674 6.672 1.445 8.599 4.335.723 1.084 1.59 1.253 2.409 1.759 2.818 1.782 5.805 3.227 8.527 5.251 1.445 1.06 3.685 1.686 5.299 2.794 2.409 1.662 5.155 2.722 7.419 4.649.892.771 2.144 1.108 3.156 1.758 2.842 1.831 5.323 4.143 8.069 6.143 1.494 1.084 3.18 1.879 4.649 3.059 2.867 2.336 5.902 4.432 8.792 6.72 2.65 2.096 5.564 3.878 8.383 5.757 2.264 1.494 4.287 3.373 6.479 5.035 1.855 1.397 3.806 2.721 5.54 4.215 2.505 2.168 5.396 3.734 7.997 5.685 1.879 1.397 3.999 2.673 5.998 3.974 1.325.867 2.794 1.566 3.999 2.722 1.06 1.012 2.288 1.999 3.589 2.722 1.758.987 3.3 2.264 4.649 3.637 1.301 1.325 3.083 1.831 4.312 3.204 1.252 1.445 3.275 2.168 4.456 3.517 1.59 1.83 3.709 2.866 5.419 4.504 1.759 1.686 3.373 3.493 5.107 5.203.964.963 1.108 2.192 1.012 3.276-.313 3.011-2.096 5.323-4.264 7.347-.771.698-4.6.385-5.949-.265-2.722-1.277-5.324-2.722-7.805-4.408-1.83-1.229-3.709-2.385-5.492-3.662-3.974-2.866-8.334-5.154-12.26-8.117-3.084-2.361-6.504-4.312-9.467-6.769-3.348-2.77-6.913-5.227-10.165-8.093a43.386 43.386 0 0 0-4.48-3.469c-1.614-1.132-2.915-2.722-4.529-3.758-1.493-.963-2.577-2.36-4.167-3.227-1.734-.94-3.107-2.53-4.769-3.662-1.156-.795-2.24-1.71-3.372-2.409-2.915-1.782-5.782-3.709-8.359-5.877-1.927-1.638-4.697-2.264-5.901-4.793-1.494.216-2.313-.964-3.3-1.711-3.132-2.36-6.191-4.841-9.226-7.322-.554-.458-.939-1.132-1.277-1.783-.144-.241-.168-.481-.481-.602-3.493-1.445-6.215-4.047-9.202-6.215-.747-.529-.626-1.108-.795-1.902l-.048-.049Zm56.269 29.484c-.337-.699-.843-1.422-1.59-1.927-2.457-1.614-4.962-3.156-7.419-4.818-1.782-1.228-3.613-2.433-5.203-3.878-2.047-1.879-4.263-3.613-6.504-5.227-2.143-1.542-4.287-3.18-6.551-4.577-3.084-1.903-5.781-4.311-8.937-6.19-3.131-1.855-6.504-3.324-9.442-5.516-2.626-1.951-5.661-3.276-8.455-4.986-2.891-1.735-5.516-3.758-8.118-5.878-.746-.602-1.469-1.806-2.577-.024-.771 1.253-1.204 2.168-.048 3.18.915.843 1.951 1.565 3.035 2.216.602.361.795.578.409 1.228-.144.241-.53.675-.024 1.06.265.193.723.217.795.048.699-1.638 1.518-.217 2.264-.12 1.012.144 1.253 1.325 2 1.614 2.746 1.084 4.576 3.42 7.13 4.817 2.384 1.301 4.335 3.348 6.551 4.89 2.385 1.638 4.312 3.758 6.576 5.516 2.626 2.023 5.179 4.167 7.925 6.022 1.397.963 2.891 1.831 4.312 2.794 1.855 1.253 3.854 2.337 5.54 3.758 2.409 2.047 5.083 3.733 7.443 5.805 1.614 1.421 3.686 2.144 5.179 3.782.675.746 2.096 1.854 2.794 1.325 1.446-1.157 2.337-2.939 2.963-4.963l-.048.049Zm38.131 27.893c.024 2.12 1.156 4.095-.289 6.143-.265.361-1.229 1.132-.434 1.71 2.385 1.734 4.962 3.203 7.395 4.914 1.782 1.252 3.974 1.927 5.877 3.107.554.337 1.397.482 2.048-.458 1.349-1.854 1.228-3.661-.675-5.203-3.781-3.059-7.828-5.757-11.514-8.984-.578-.506-1.373-1.494-2.432-1.229h.024Zm-33.892-24.834a9.377 9.377 0 0 1-2.553 3.998c-1.084 1.012-.963 1.735.241 2.554 1.541 1.06 2.794 2.505 4.408 3.3.939-1.47 2.529-2.698 3.059-4.673.241-.916.41-1.301-.554-1.855-1.566-.94-2.987-2.144-4.601-3.324ZM147.585 201.106c-6.528.048-12.188-.892-17.415-3.493-2.457-1.228-4.697-2.963-6.793-4.769a39.366 39.366 0 0 0-6.889-4.746c-2.987-1.614-5.95-3.468-9.394-3.878-3.445-.433-6.937-.289-10.406.145-5.251.65-10.382 2.216-15.705 2.071-4.866-.144-9.587-.698-13.706-3.757-4.914-3.638-8.214-8.287-9.298-14.333-1.228-6.961-.843-13.826.77-20.739.7-3.035 1.277-6.142 1.831-9.226.193-1.084.94-1.71 1.518-2.529 1.277-1.83 3.276-2.071 4.793-3.179 3.686-2.674 7.829-2.867 12.237-2.457 6.166.578 11.273 3.589 16.5 6.431 4.24 2.288 8.021 5.299 12.213 7.636 2.577 1.445 5.299 2.457 8.334 2.818 3.637.434 7.178-.265 10.743-.53 4.023-.313 8.021-.192 12.02-.289 4.215-.096 8.503-.072 12.622 1.012 6.72 1.758 13.079 4.408 18.764 8.503 4.432 3.179 5.877 6.889 4.528 12.285-1.083 4.311-2.408 8.527-4.191 12.621-.963 2.192-1.541 4.601-2.071 6.962-.747 3.493-3.059 5.781-5.589 7.973-4.625 3.998-9.972 5.829-15.392 5.516l-.024-.048Zm-87.149-38.589a17.59 17.59 0 0 0 .169 4.047c.843 5.372 3.251 9.78 7.756 12.935.843.578 1.59 1.325 2.48 1.783 3.951 2.023 8.19 2.216 12.502 2.023 1.927-.096 3.758-.578 5.637-.819 4.312-.554 8.6-1.397 12.983-1.518 3.782-.096 7.491.217 11.008 1.783 4.601 2.023 8.913 4.552 12.743 7.828 4.528 3.854 9.635 6.456 15.584 7.154 4.36.506 8.816.964 13.056-.505 4.841-1.687 8.696-4.842 10.791-9.66.891-2.023 1.301-4.263 2.048-6.359 1.878-5.179 3.805-10.333 4.913-15.753.41-2.072.073-3.902-1.71-5.396-1.686-1.421-3.348-2.818-5.299-3.854-3.661-1.975-7.467-3.637-11.345-5.058-5.733-2.096-11.731-1.807-17.681-1.951-5.949-.145-11.875.747-17.8.939-4.192.145-8.022-1.06-11.683-2.842-4.071-1.975-7.443-5.107-11.442-7.275-4.769-2.601-9.394-5.419-14.886-6.407-4.649-.843-8.84-.506-13.104 2.096-2.794 1.71-4.07 3.324-4.432 6.696-.722 6.721-3.227 13.224-2.312 20.137l.024-.024ZM35.481 100.731c-.12 3.54.41 6.865-.096 10.165-.217 1.445-.362 2.842-2.216 3.179-1.903.361-2.794-.626-3.59-2.168-.818-1.614-1.83-3.131-2.794-4.673-.24-.361-.578-1.132-.89-.891-.507.409-1.205.578-1.543 1.325-1.06 2.336-3.083 3.83-5.275 4.914-1.493.722-2.48-.241-2.866-1.831-.482-2.072 0-4.095.096-6.118.073-1.614-.867-2.024-1.999-1.711-2.264.627-4.336-.144-6.48-.457-1.734-.241-2.625-1.494-3.01-3.06-.241-.939-.025-1.806 1.011-2.432 1.638-.988 3.348-1.807 5.179-2.24 1.59-.386 1.566-1.157 1.012-2.289-1.494-2.962-3.035-5.901-4.48-8.888-1.205-2.505-2.313-5.082-3.47-7.612-.312-.698-.288-1.445-.192-2.168.12-.77 1.06-1.517 1.325-1.276 1.18 1.084 2.264-.458 3.42.12 1.132.578 2.096 1.373 3.084 2.12 2.77 2.047 5.54 4.119 8.238 6.263 1.035.843 1.348.505 1.493-.578.313-2.433 1.3-4.746 1.71-7.13.29-1.638 1.012-3.132 1.18-4.794.12-1.156 1.951-2.939 3.035-2.939 1.542 0 2.24 1.06 2.554 2.337.915 3.806 2.264 7.491 2.65 11.418.144 1.445.602 2.697 2.673 2.553 1.614-.12 3.252-.458 4.914-.145 2.072.41 4.143-.433 6.19.024.868.193 1.831.193 2.169 1.277.337 1.132.409 2.216-.723 3.011-1.927 1.373-4.215 1.975-6.335 2.963-.386.192-.386-.048-.506-.362-.169-.385-.843-.216-.819-.048.217.94-1.132 1.59-.145 2.843 1.687 2.143 3.734 3.974 5.107 6.359.337.602.819 1.132 1.108 1.734.554 1.132 1.614 2.313.482 3.613-1.18 1.349-2.867 1.566-4.408.988-1.903-.699-3.686-1.759-5.516-2.674a42.21 42.21 0 0 1-1.325-.698l.048-.024Zm-4.07 5.588c-.434-2.457-.218-4.721-.675-6.962-.313-1.517.192-2.962 1.614-3.757 1.397-.771 2.794-.048 3.974.626.723.41 1.445.867 2.216 1.204.217.097.337.771.747.217.217-.289.144-.506-.048-.746a29.046 29.046 0 0 1-1.06-1.35c-.964-1.204-2-2.384-2.843-3.66-1.18-1.783-.89-3.132.723-4.505.506-.434 1.205-.65 1.542-1.325a6.303 6.303 0 0 0-1.903 0c-4.745.723-6.504-.723-7.106-5.54-.24-1.903-.77-3.758-1.18-5.637h-.434c-.024 3.011-1.325 5.757-1.71 8.72-.169 1.35-1.036 2.65-2.264 3.204-1.229.53-2.53.024-3.662-.867-2.746-2.144-5.588-4.216-8.406-6.287-.169-.12-.241-.626-.627-.265-.313.313-.216.626.12.867.772.53 1.06 1.445 1.205 2.192.217 1.084 1.253 1.903 1.18 2.794-.096 1.204.892 1.397 1.205 2.096.602 1.325 1.782 2.529 1.18 4.215-.217.626.386.506.627.723.722.674 1.902 1.084 1.83 2.312-.072 1.132-.698 1.855-1.782 2.313-1.084.457-2.096 1.084-3.156 1.638.891.24 1.71.168 2.505.144 2.915-.169 5.565 2.288 5.275 5.058-.048.434-.168 1.036.362 1.229.626.241.674-.385.915-.747.241-.385.578-.722.843-1.084 1.975-2.673 3.469-2.649 5.902-.433 1.132 1.035 1.325 2.649 2.866 3.589l.024.024ZM207.299 43.286c.12-1.132.433-2.264.361-3.372-.144-1.975 1.229-2.168 2.578-2.385.819-.144 1.276.458 1.469 1.157.506 1.806.65 3.637.723 5.516.12 2.529.939 4.938 2.095 7.13 1.036 1.999 3.107 2.625 5.251 2.77.795.048 1.831-.169 2.12.698.313.964.819 1.927-.265 3.132-1.301 1.445-1.566 3.54-2.072 5.444-1.011 3.902-1.3 7.948-2.456 11.803-.29.987-.964 2.336-2.457 2.12-2.433-.362-2.77-.868-2.963-2.988-.241-2.529-.819-4.986-1.518-7.419-.626-2.288-2.312-3.589-4.336-4.576-2.505-1.229-4.239-3.132-5.082-5.83-.169-.554-.145-1.228.482-1.18 2.047.12 3.276-.819 3.926-2.65 1.084-3.01 2.072-6.07 2.12-9.321l.024-.049Zm-.843 14.55c3.589 1.95 7.033 3.709 7.852 8.093.314-2.553 1.253-4.89 1.831-7.323.12-.554-.096-1.06-.602-1.3-2.288-1.084-4.071-2.722-5.516-5.203-.578 2.529-1.927 4.167-3.541 5.732h-.024ZM84.668 9.897c-.53-1.325.193-2.602.41-3.854.217-1.301 0-2.578.217-3.854.168-.94.337-1.952 1.59-2.192.963-.193 3.058 1.95 2.697 3.107-.385 1.276.458 2.77-.722 3.902-.12.12-.073.626.072.819 1.517 2.047 1.686 4.673 2.987 6.793.265.457.457.65 1.06.53.89-.169 1.806-.362 2.746.192.939.53 1.18 1.301.794 2.12-2.697 5.974-4.119 12.309-5.708 18.62-.29 1.084-.627 2.601-2.144 2.674-1.71.072-2.53-1.036-2.698-3.108-.361-3.878-1.132-7.66-2.963-11.104-.891-1.686-2.264-3.228-4.046-4.023-2.072-.94-1.759-2.866-2.168-4.48-.169-.626 1.06-1.204 1.638-.867.096.048.264.12.313.072 1.445-1.084 4.215-.217 4.48-3.035.024-.337.193-.578.482-.65.94-.217 1.3-.723 1.011-1.687l-.048.025Zm3.927 16.716c1.156-2.36 1.662-4.624 2.432-6.768.217-.602-.144-1.084-.602-1.253-1.47-.626-2.433-1.734-3.203-3.059-.41-.674-.988-.77-1.253-.024-.289.795-.867 1.204-1.373 1.758-.747.82-1.012 1.494.24 2.481 2.048 1.614 3.012 4.071 3.783 6.865h-.024ZM6.022 167.388c-.434-1.565-1.253-2.746-2.072-3.878-.722-1.011-.674-2.288-1.349-3.324-.41-.626-.072-1.373.554-1.806.65-.458 1.325-.603 2.048-.073.698.53 1.204 1.253 1.638 1.976.554.963.795 1.228 1.541.096 1.012-1.469 2.602-1.204 3.373.506.554-.723 1.06-1.397 1.878-1.903 1.47-.891 2 .313 2.53 1.012.385.505.843 1.686-.579 1.951-.264.048-.264.24-.216.361.963 1.999-1.084 2.529-1.927 3.42-.434.458-.554.771-.578 1.229a.924.924 0 0 0 .963 1.012c.843-.049 1.614.481 2.313.409 2.047-.241 2.48 1.349 2.432 2.505-.072 1.494-1.517 1.759-2.89 1.494-.313-.049-.65 0-.988 0 .747 2.071.506 2.746-1.204 3.589-2.024.987-2.553.746-3.469-1.614-.12-.313-.168-.675-.289-.988-.722-1.806-1.276-1.903-2.529-.433-.337.385-.65.843-1.036 1.132-.602.433-1.228.963-2.047.578-.747-.361-1.35-.867-1.35-1.807 0-.457.194-1.084-.505-.987-1.445.216-2.144-.771-2.216-1.759-.072-.939.988-1.662 1.807-2.216 1.228-.843 2.673-.554 4.215-.506l-.048.024ZM134.867 49.453c1.542.12 2.577 1.108 3.18 2.337 1.951 3.878 4.022 7.684 5.684 11.706 1.157 2.818 2.337 5.66 3.734 8.407.963 1.879 1.975 3.661 3.276 5.3 1.469 1.854 1.325 2.649-.482 3.95-1.084.77-2.577.264-3.493-1.398-1.108-2.023-2.336-3.998-3.203-6.166-.313-.747-1.132-1.349-1.59-2.168-1.012-1.758-1.927-3.661-2.987-5.275-1.517-2.337-2.505-4.914-3.878-7.275-1.108-1.927-1.638-4.095-2.192-6.238-.361-1.35.843-3.228 1.927-3.156l.024-.024ZM76.912 64.001c-.482 1.542-.723 3.42-.217 5.348.265.963.554 1.59 1.71 1.662 2.072.12 2.795 1.397 1.735 3.18-1.518 2.529-2.216 5.37-3.252 8.093-.313.843-.77 1.71-1.397 2.312-1.132 1.132-3.035.29-3.469-1.373-.626-2.36-.746-4.841-1.782-7.082-.434-.915-.675-2.047-1.879-2.24-1.18-.192.169-1.59-1.108-1.95-1.3-.362.072-1.277.024-1.952-.024-.53.602-.65.434-1.349-.241-.94.867-1.204 1.493-1.204 2.192-.048 2.602-.41 2.65-2.89 0-1.133.216-2.072 1.3-2.915.94-.723 1.88-.675 2.554-.362.843.362 1.276 1.421 1.204 2.77v-.048ZM113.381 109.432c-1.181-.217-2.409-.361-2.698-1.758-.289-1.421.409-2.24 1.686-2.915 3.396-1.782 7.25-1.999 10.767-3.396 2.024-.795 4.167-1.614 6.287-1.783.988-.072 1.397-1.06 2.433-.819.939.217 1.951.458 3.011.097.964-.338 1.734-.675 2.072-1.687.529-1.565 1.878-1.276 2.89-.963.819.24 1.229 1.156 1.132 2.24-.313 3.132-2.77 3.926-5.106 4.914-2.915 1.228-6.071 1.542-9.106 2.312-3.757.964-7.563 1.662-11.128 3.252-.723.313-1.542.362-2.264.53l.024-.024ZM135.011 86.98c-.554-.336-.819.025-1.373.483-.771.65-1.783.192-2.65-.313-3.42-1.976-7.033-3.59-10.743-4.963a397.197 397.197 0 0 0-10.622-3.805c-1.373-.482-2.12-1.325-1.855-2.746.241-1.277 1.662-2.144 3.107-1.71 2.939.89 5.95 1.541 8.768 2.986 1.734.891 3.734 1.494 5.54 2.385 1.831.915 3.854 1.397 5.637 2.288 2.481 1.253 5.299.82 7.804 2.048 1.18.578 1.156 1.47 1.084 2.095-.096.892-.963 1.831-2.023 1.494-.892-.29-1.711-.145-2.698-.217l.024-.024ZM231.868 100.373c-.409-.722.747-.506 1.036-.915 1.108-1.542 2.288-3.035 3.372-4.577.434-.626.891-1.95.602-3.107-.217-.94.289-1.758.482-2.626.289-1.276 1.469-1.084 2.216-1.59.578.892 2.023 1.205 1.927 2.53-.096 1.252-.217 2.577-1.228 3.517-.217.192-.506.337-.289.65.168.24.433.385.602-.048.53.313.53.94.65 1.421.265 1.06.964 1.542 1.831 2.072.891.553 2.023 1.252 1.349 2.746-.94 2.071-1.807 4.191-2.722 6.262-.217.458-.506.867-.53 1.421-.072 1.084-.867 1.422-1.783 1.614-.963.193-1.613-.192-1.999-1.035-.289-.627-.506-1.277-.722-1.927-.675-2-2.289-3.06-3.927-4.144-.674-.433-.626-1.3-.891-2.312l.024.048Zm8.118.651c-.94.096-1.012-1.18-1.927-1.205-.579 0-.916.795-.868.843.554.554 1.108 1.253 1.976 1.205.265 0 .795-.169.819-.843ZM162.832 20.113c0 .29.024.723-.096 1.085-.386 1.06.313 1.252 1.036 1.252.891 0 1.782-.169 2.673-.265.988-.096 1.903.169 2.313 1.132.361.891-.386 1.373-.819 2.072-1.012 1.614-2.529 1.493-3.878 1.42-1.277-.047-1.325.555-1.108 1.277.505 1.542-.434 2.554-1.084 3.686-.217.361-.482.289-.867.217-.94-.193-1.976-.193-2.217-1.421-.072-.458-.096-.916-.12-1.373-.072-1.157-.217-2.048-1.758-2.216-1.036-.12-1.831-1.108-1.783-2.24.048-1.036.795-1.663 1.855-1.88 1.06-.216 1.59-.794 1.445-2.023-.096-.891.121-1.83.217-2.746.048-.313.072-.626.554-.747.578-.144.554-.216.337-.722-.024-.072-.12-.097-.193-.145.097-.048.217-.072.314-.144 1.324-.795 2.119-.482 2.697.987.338.867.362 1.783.458 2.794h.024ZM27.315 12.887c1.277 1.132 2.65 1.035 4.168.843 1.541-.193 1.637 1.541 2.216 2.48.505.796-.458 1.35-1.06 1.687-1.35.795-1.71 2.312-.53 3.276.722.578.77 1.421 1.204 2.096.482.722-.433 1.565-.626 1.517-2.048-.361-2.842 1.518-4.24 2.264-.819.434-1.42.097-1.999-.41-.53-.457-.433-.915-.096-1.517.361-.65-.241-1.445.144-2.192.024-.072-.36-.457-.578-.506-.602-.12 0 .362-.216.506-.627.506-1.229.265-1.855-.024-.916-.41-1.373-1.108-1.036-2.023.53-1.397.915-2.867 2.216-3.902.626-.506 1.3-1.301.506-2.289-.265-.337-.097-.65.217-.89.265-.194.361.071.554.192.265.168-.265.963.481.65.458-.193.603-.602.338-1.108-.049-.096.072-.313.168-.626l.024-.024ZM202.914 198.583c0-.41-.072-.819 0-1.205.289-1.277-.12-1.71-1.421-1.397-.771.193-1.759.53-1.229-1.036.145-.409-1.011-.481-.554-1.565.53-1.253 1.181-1.735 2.361-1.59.819.096 1.036-.048 1.108-.964.12-1.445.506-2.89 1.493-4.095.265-.337.434-.963.916-.265.674.988.867-1.204 1.686-.192.578.722-.361 1.252.048 1.734.626.747.482 1.638.313 2.337-.313 1.276.265 1.3 1.181 1.348 1.18.073 2.456.073 3.179 1.229.41.65.602 1.469.072 2.096-.843 1.011-1.951 1.638-3.372 1.373-1.204-.241-1.686.313-1.397 1.493.337 1.349.289 1.421-1.06 1.517-.241 0-.554.193-.698.386-.169.265-.073.53.289.65.385.121.554.386.385.795-.169.41-.506.41-.867.434-1.783.168-2.602-.843-2.505-3.156l.072.073ZM33.241 202.535c-1.132-.771-2.023-.049-2.818 1.035-.626.892-1.47.313-2.168.169-.578-.121-.698-.723-.77-1.349-.17-1.277.65-2.746-.627-3.83.963-1.084.096-3.011 2-3.83.794-.337 1.228-1.662 2.047-2.385.843-.746 1.71-.746 2.384.097.265.337.602.722.988.891 1.517.65 2.023 1.71.987 2.963-1.18 1.397-.433 2.649-.048 3.926.41 1.397-.24 2.337-1.95 2.313h-.025Z" fill="#000"/><path d="M142.792 179.619c-6.985-.337-12.55-2.553-17.295-6.576-2.963-2.529-1.999-6.889 1.012-8.72 1.252-.77 2.601-1.686 4.36-1.638 1.854.049 3.589.314 5.371.843 1.662.506 3.18 1.06 4.601 2.144 1.542 1.156 3.396 1.855 5.034 2.867 1.205.746 2.361 1.59 3.493 2.457 2.987 2.312 1.807 6.287-1.204 7.322-1.927.675-3.903 1.542-5.372 1.325v-.024Zm.121-3.035c.722.265 1.927-.217 3.131-.578a2.93 2.93 0 0 0 1.855-1.759c.289-.794-.723-.987-1.205-1.421-1.132-1.035-2.457-1.734-3.781-2.505-2.65-1.517-5.565-2.481-8.19-4.167-1.903-1.228-4.408-.698-6.504.602-1.686 1.06-1.903 2.578-.506 3.927 4.095 3.902 9.129 5.419 15.175 5.877l.025.024ZM94.375 165.728c-5.106-.77-10.117-1.951-14.645-4.624-1.951-1.157-3.228-2.891-3.637-5.179-.193-1.108 1.397-3.276 2.938-3.999 1.903-.891 3.975-1.132 6.022-1.373 6.335-.747 11.659 1.759 16.043 5.853 3.781 3.517 2.866 6.239-1.831 8.431-1.421.675-3.132 1.132-4.866.867l-.024.024Zm-8.671-12.068c-1.614-.168-3.06.121-4.457.675-.819.313-1.782.554-1.903 1.662-.12 1.108.675 1.59 1.422 2.144 3.107 2.24 6.768 2.938 10.357 3.806 2 .481 3.999.819 5.998.313 1.06-.265 2.385-.482 2.818-1.662.434-1.181-.867-1.735-1.397-2.53-.265-.409-.77-.674-1.18-.987-3.517-2.553-7.563-3.228-11.682-3.421h.024Z" fill="#000"/></g></g></g><defs><linearGradient id="l" x1="7.134" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="c" x1="7.135" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="e" x1="7.135" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="f" x1="7.135" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="i" x1="54.69" y1="237.711" x2="160.821" y2="237.711" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="j" x1="7.134" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="k" x1="7.134" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="d" x1="7.135" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="m" x1="7.134" y1="17.016" x2="242.022" y2="17.016" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h286.488v400H0z"/></clipPath><clipPath id="b"><path fill="#fff" d="M0 0h286.475v400H0z"/></clipPath><clipPath id="g"><path fill="#fff" transform="translate(59.27 131.711)" d="M0 0h116.346v71.344H0z"/></clipPath><clipPath id="h"><path fill="#fff" d="M0 0h286.475v400H0z"/></clipPath><clipPath id="n"><path fill="#fff" transform="translate(59.271 131.715)" d="M0 0h116.346v71.344H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-pintaskbar.svg b/browser/components/newtab/data/content/assets/mr-pintaskbar.svg
new file mode 100644
index 0000000000..386af26d89
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-pintaskbar.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="341" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M311.144 181.613c1.216.332 2.576.708 4.036 1.083 5.306 1.371 11.785 2.831 16.395 3.162l1.659-2.211-6.634-4.975c-4.986-1.691-15.478-5.141-20.453-6.633a71.35 71.35 0 0 1 1.072-1.648l.034-.066c2.476-3.748 5.616-8.015 7.894-12.195.011-.011.022-.022.022-.033.884-1.603 1.636-3.206 2.155-4.743l1.537-3.98v-3.869c-1.227.276-3.781.829-4.975 1.105l-7.739 8.292c-.31.564-.719 1.338-1.194 2.211-.011.011-.022.022-.022.033-1.371 2.521-3.239 5.926-4.533 8.292-.343.631-.641 1.183-.884 1.626.066-2.19.199-6.258.32-10.083v-.122c.089-2.996.177-5.826.232-7.485l-.154-.464-.045-.122-4.223-12.128h-2.211c-.044.287-.122.818-.232 1.515-.465 3.007-1.393 9.076-1.825 11.763.012.011.012.022 0 .033-.066.476-.121.84-.154 1.062.11 3.582.431 13.93.552 17.689-4.3-7.319-10.945-25.097-18.794-29.298l-1.106 2.764c1.703 5.749 6.866 21.183 8.845 27.087-7.109-5.672-6.866-6.225-16.031-8.292l-.553 3.317 6.081 8.844 10.867 8.292.299.221.442.332c-.685.243-1.769.619-3.095 1.083-5.285 1.869-14.428 5.075-17.347 6.103l-4.986 5.528 3.869 3.87s.642-.277 1.603-.697c3.096-1.327 9.586-4.102 10.006-4.278 1.083-.719 2.587-1.725 4.102-2.731.011-.011.022-.022.044-.033.265-.177.531-.354.785-.52 1.26-.851 2.465-1.647 3.361-2.244-.022 3.537-.199 7.374-.409 11.299-.332 6.611-.719 13.51-.454 19.768.056 1.249.133 2.454.244 3.626l.066.685c.011-.022.232-.376.586-.928 1.493-2.3 5.252-8.082 5.495-8.469 1.094-3.416 3.14-9.751 4.522-14.505.066-.233.132-.465.188-.686.331-1.161.608-2.2.818-3.051 2.775 6.887 9.353 21.426 13.267 27.639h3.316v-9.95c-.066-.188-.176-.509-.32-.918 0 0 0-.011-.011-.022-.807-2.266-2.576-7.297-2.985-8.457-.045-.454-.122-1.272-.221-2.267l-.034-.365c-.022-.21-.044-.42-.055-.641l-.066-.674-.199-2.101-.266-2.764-.077-.774-.066-.707-.056-.608-.066-.708 12.714 13.82 10.172 6.423.331.21v-6.633c-4.013-8.392-12.261-18.419-18.242-25.429l2.753.719s.022.011.033.011Zm-17.18-1.78c-.155 5.683-8.923.453-4.732-3.162 1.945-2.211 4.997 1.227 4.709 3.162h.023Z" fill="url(#b)"/><path d="m89 4.422 2.21 37.037-7.186-1.659-8.292-4.975-6.08-1.105v3.317l7.739 5.528 10.503 4.422c-4.589 2.94-14.14 8.9-18.795 11.608l.552 2.764c5.628-2.023 17.28-4.732 23.218-5.528l2.211 11.056v12.715l4.422 9.397 3.87-11.609 1.658-9.397v-9.95c4.699 3.36 13.61 14.67 17.137 19.347l7.186 4.423-1.658-8.845c-3.041-4.666-8.867-14.461-11.609-19.348 5.849 3.417 17.789 10.072 23.77 13.267l1.106-2.764-11.609-10.503-12.161-8.291 18.795-11.056h-5.528l-17.69 5.527 6.634-22.664-2.211-4.422L102.266 39.8 88.999 4.42Z" fill="url(#c)"/><path d="m30.956 75.732 3.317-7.74 6.633 9.398-3.87 12.715-6.08-14.373Z" fill="url(#d)"/><path d="m40.906 24.875 3.87-7.186 4.422 7.186-4.422 9.95-3.87-9.95Z" fill="url(#e)"/><path d="m78.496 174.129 4.422-7.186 5.528 8.291-5.528 11.056-4.422-12.161Z" fill="url(#f)"/><path d="m25.285 293.607.143.465h-4.422l-2.764-1.659v7.187L6.633 285.78c.531-.277 2.698-1.349 3.273-1.636.077-.011 3.847-3.859 3.914-3.892v-7.186c3.261 1.603 12.692 5.97 14.925 8.844v2.211h-2.211l2.764 6.634-5.528-2.211 1.515 5.063Z" fill="url(#g)"/><path d="M67.993 279.699c-.132.243-3.195 6.401-3.317 6.634l-2.764-4.423-1.658 6.081-1.658 1.106-2.211-8.292-5.528 8.844-1.659-1.658.553-10.503-7.872 5.771-.42.31v-8.292c2.742-5.937 7.53-14.472 11.056-19.901l4.975 4.423h7.186c1.482 4.986 3.03 14.704 3.317 19.9Z" fill="url(#h)"/><path d="M184.632 42.566c.177-.232 4.721-8.546 4.975-8.292l7.187 7.186-6.634 17.69-5.528-16.584Z" fill="url(#i)"/><path d="m253.731 61.912 4.975-5.528 5.528 6.634-5.528 10.503-4.975-11.609Z" fill="url(#j)"/><path d="M145.484 385.483c-2.057.409-14.251 2.852-16.584 3.316-.221-.044-7.197-1.094-7.186-1.105-8.403-6.877-9.409-9.563-13.267-19.348a390.56 390.56 0 0 1 2.764-3.869l34.273 21.006ZM234.483 370.559a5164.892 5164.892 0 0 1-5.528 13.82c-2.366 2.532-5.362 5.749-7.739 8.292-8.148.298-24.654-.21-32.615-1.659l-11.056-2.211c-1.47-.741-4.046-2.012-5.527-2.764 2.454-3.914 6.887-11.697 8.291-16.031 1.537.332 9.873 1.858 11.609 2.211l11.056-1.658 13.82-4.422c10.503-.255 8.502-.144 17.689 4.422ZM197.391 220.499c-7.883 9.309-24.522 9.099-33.555 1.658-4.234-2.509 4.135-3.626 3.815-12.88 10.912 7.242 26.368-2.432 25.992 2.565-.431 3.704 4.665 5.716 3.748 8.646v.011Z" fill="#845B25"/><path d="M176.926 184.289c3.815-.033 7.319-1.979 9.917-4.676 3.184-1.924 8.126 4.92 15.611 1.747.542-.122 1.006-.487 1.283.42 1.039 5.881 7.761 5.362 7.816 8.104-7.319 22.753-41.061 30.425-54.704 8.811-6.158-11.973-6.324-7.076 1.614-11.852 6.335-1.437 1.095-5.55 11.465-2.543 4.411 1.327.31 2.223 6.589-.895" fill="#845B25"/><path d="M26.634 282.343c9.96-.443-4.633-9.232-7.33-10.857-2.875-1.249-5.385-2.808-7.817-4.776-7.485-3.35-14.218 4.754-10.381 11.708 2.554 5.13 22.244 34.284 16.694 12.438 1.868 1.647 6.28 3.681 7.584.973l-1.514-5.064 5.528 2.211-2.764-6.633ZM3.36 275.798c.32-2.831.774-6.921 4.522-6.081l-.022-.022c6.058-.542 3.759 8.8-.21 9.541-2.709.564-4.566-.044-4.29-3.438Zm20.044 5.716c.675 1.006 1.393 2.012 1.68 3.36-2.188-.608-3.637-2.133-5.538-3.128-4.82.508 3.25 6.456 3.494 8.844-3.14 1.46-7.375-7.219-8.392-2.885-.055 2.377 1.88 3.681 1.36 6.191-3.03-3.693-5.893-7.164-8.834-10.746 1.957-.465 4.246-.664 4.942-3.007 1.216-2.123 3.417-4.367 2.93-7.165-.243-2.476 12.051 5.694 11.974 7.308-1.581-1.514-6.103-1.735-3.616 1.228Zm44.721-10.515c.376-6.467-4.334-12.515-.619-18.441 2.963-8.402-9.066-14.56-14.925-8.513-1.803 1.946-.94 4.732-2.123 6.932a47.588 47.588 0 0 0-3.516 5.407c-4.92 8.877-18.297 37.191 2.908 19.325l-.553 10.503 1.658 1.659 5.528-8.845 2.212 8.292 1.658-1.106 1.658-6.08 2.764 4.422c2.786-4.776 3.87-7.971 3.35-13.555Zm-14.384-20.928c.266-1.902.012-4.434 2.698-4.069 3.04-.343 7.618-.707 8.458 3.228 2.023 8.834-10.68 7.485-11.133.863l-.023-.022Zm10.105 30.425c-1.282-3.095-1.227-5.837-1.392-8.966-.078-2.001-2.798-1.249-2.566.52.166 3.515-.884 6.832-1.625 10.613-1.68-3.615.144-6.887-1.028-10.359-2.919-4.069-4.964 10.216-7.22 11.885.166-4.677 1.051-9.209 2.5-13.632.762-1.271-.708-2.808-1.681-1.426-3.571 2.941-5.362 7.065-9.597 9.574 2.035-8.712 6.048-16.307 10.105-24.046v.022c4.235 7.242 11.045 3.306 11.686 5.329.962 6.921 2.61 13.466.818 20.486Zm47.364 83.98-1.625 2.267c.585.73.176.862-.266 1.017a7.716 7.716 0 0 0-.763.851c3.77 9.663 4.942 12.35 13.157 19.083l.619.099v-.022c1.802-1.238 5.406.221 5.793-1.879-.11-.94-.365-2.057-1.813-1.891-2.875-.022-5.495 2.311-7.916-.188 1.725-1.625 5.495-.133 6.291-2.023.066-1.117-.984-1.67-1.913-1.703-1.658-.088-3.405-.409-4.986.564-1.205.741-2.134.022-3.25-.674 1.37-1.559 8.833.365 7.263-2.399-.608-.42-1.094-1.371-1.99-.885-.696.354-.906-.442-1.537-.354-1.293.188-2.62.078-3.924.078-.398 0-1.007.376-1.117-.299.497-1.625 8.292-.155 4.599-3.239-2.211-2.045-6.092 1.437-7.33-1.349-.033-6.866 28.159 12.714 31.708 14.605l3.273-.652-34.273-21.007Zm114.516 22.853c-1.404.531-6.169 0-6.235 1.603.431 1.736 2.719 1.05 4.057 1.238l2.698-2.885c-.166.022-.343.033-.52.044Zm-1.26-3.649c-1.25-.287-2.001.487-2.93.885-.464.21-.044.619 0 .929.088.608.564.608 1.028.608h4.776c.354-.398 1.858-1.825 1.88-2.388-1.626.442-3.173.342-4.754-.034Zm2.145-3.891c-1.394-.022-4.677-.487-4.821 1.448 1.592 2.045 5.716.033 8.193.564l.95-2.355c-1.448.177-2.852.464-4.322.343Zm4.72-4.588c-2.741.486-8.358-2.532-9.054 1.47 1.757 1.835 6.777-.332 9.342 1.05.221-.552.774-1.934.984-2.465-.409.011-.863-.044-1.272-.055Zm.697-5.871-4.909-2.454c-17.678-1.051-28.303 11.741-46.81 3.128-2.156 5.617-3.859 11.565-7.75 16.308l2.819 1.404c4.068-4.024 5.395-9.165 6.512-14.539 17.114 10.072 35.279-11.464 51.675-.32l.884-2.222c-.752.044-1.592-.708-2.421-1.305Zm102.919-188.436c-6.512-7.12-16.96-10.392-26.424-11.31 4.146-7.805 13.864-17.656 12.549-26.766-8.359-4.478-15.843 10.282-19.89 16.197-.265-7.883.896-16.717-1.725-24.301-8.258-12.327-11.619 19.912-9.43 24.024-.863.144-.829-.42-1.039-.773-3.748-7.364-6.921-15.191-12.67-21.316-12.339-6.368.32 21.26.674 25.771-4.212-2.83-16.108-8.69-13.919 1.415 3.56 6.534 9.497 11.023 14.903 15.943-36.363 10.182-22.101 27.827.133 9.618-.255 10.36-2.256 21.659.044 31.885 6.567 4.821 11.232-15.08 12.504-19.535.431-1.172 1.293-2.377.652-3.627 0-.044.177-.188.277-.232 1.979 2.488 2.542 6.965 3.781 10.149 10.536 30.271 19.458 14.815 9.961-7.617.077.088.144.177.221.265l-.862-8.999 12.714 13.82 10.171 6.423c6.037-6.799-10.237-25.793-15.235-31.244 4.257.63 26.192 10.57 22.61.21Zm-24.356-3.958c-10.824-2.808-1.316 4.788 1.47 7.894 5.417 6.877 13.389 15.434 13.289 24.279-4.29.21-28.325-31.045-27.429-21.858 4.245 10.57 8.988 21.758 8.037 33.378-6.081-9.674-9.74-20.553-13.344-31.31-.011-2.145-2.875-3.582-3.206-.829-.841 10.414-3.295 21.161-8.646 30.204-1.227-2.111.951-9.066-1.791-8.778 2.399-1.349 1.47-3.328 1.603-4.975-.73-4.622 6.435-32.128-3.693-18.364-4.588 4.113-11.863 8.878-17.954 6.777 1.669-3.261 7.109-4.632 10.337-6.501 4.279-2.62 11.1-3.361 14.019-7.197-.056-.785-.31-1.437-1.283-1.813-7.02-2.852-12.836-8.469-16.042-15.334.055-3.616 16.075 6.611 15.733 9.795.652.984 1.282 1.327 2.189.542.453-.376.674-.078 1.028.066 1.05.332 1.935-.586.984-1.437-2.477-2.466-4.898-4.467-5.285-8.104-2.233-7.396-4.444-14.826-6.103-22.366 4.146 1.216 19.481 38.961 19.37 25.804-1.172-10.005-2.344-20.331.84-30.116 1.791 8.933 2.632 17.767 2.952 26.844-.232 1.957.841 6.777 3.052 3.372 3.383-8.281 8.413-16.252 15.92-21.349 3.007-1.072-3.184 9.044-3.726 10.271-18.419 27.993-4.544 9.342 18.486 25.649-7.032 1.117-13.909-3.184-20.807-4.544Z" fill="#010101"/><path d="M333.124 241.016c-8.558 1.847-12.781 10.581-17.038 17.347-6.6 11.443-19.347 16.374-27.153 26.744 4.898-12.305 15.445-21.968 21.935-33.643 11.819-17.103 6.567-38.585-3.892-54.395 5.44 3.538 13.61 18.276 20.598 14.859l-10.172-6.423-12.714-13.82.862 9c18.895 27.219 6.136 48.734-13.068 70.193 1.482-8.988 1.139-19.569-2.377-28.369-2.399-7.662-11.542-20.365-19.745-11.476-9.486 15.003 17.435 32.482 16.318 45.196.409 10.558-8.535 19.392-7.64 30.448.21 10.414.995 20.785 5.827 30.237.696 2.731 7.65 14.373 5.03 15.158-12.393 2.366-25.074 4.876-37.744 4.19l-.067-.232c8.425-5.904 13.455-13.764 16.109-23.648 4.046-10.227-3.671-24.224-15.523-21.416-.641.133-.807-.508-.265-.707 3.339-2.808 4.124-7.496 5.13-11.498-.299-16.694-12.88-31.432-20.1-46.059-3.902-6.943-1.47-18.297-10.083-21.669-1.879.144-3.77.044-5.251-1.161-8.524-5.981-21.404-5.362-26.623-15.368-3.206-3.261 9.862-5.948 11.642-10.89 1.283-1.492 5.34 3.383 11.156 1.67 4.521-.763 8.501-2.62 10.901-6.866.276-.508.552-.597 1.16-.597 12.405.929 16.44-14.66 14.782-24.533-.088-.674.044-.962.586-1.26 7.971-4.555 7.518-17.69 1.603-23.859-.332-3.051 1.846-6.589.586-10.282-2.863-13.355-18.275-11.398-17.601-14.693 2.51-6.136-2.178-12.869-5.771-17.711-6.346-7.761-16.783-14.572-26.965-12.15.122 1.392-.144 1.238-.818.276-3.394-.453-4.876 4.864-8.17 5.196-3.24 1.017-3.837 1.371-5.727-1.382-4.854-6.667-15.821-15.976-24.257-14.384-12.272 4.379-20.122 15.246-25.384 26.656-2.941 2.443-7.783.564-11.454 1.88-7.474 1.293-13.919 6.113-17.081 13.045-6.015 15.998 7.219 29.553 12.006 43.892.398.929.288 1.47-.254 2.278-3.306 4.82-3.936 10.171-2.565 15.71 2.587 9.375 9.906 19.602 20.465 19.834 3.372 1.382 8.8-1.802 10.359-.133.962 1.416 2.311 2.366 3.969 2.72 4.157.652 9.143.896 12.338-2.355.697-.741 1.073-.11 1.46.288 1.359 1.901 3.504 3.405 4.897 5.019-.442 2.255-1.05 4.356-3.106 5.804-.575.409-1.161-.287-1.559.365-7.43 6.446-19.182 5.119-28.148 8.922-2.93.929-5.915 1.813-8.403 3.958-1.514 1.316-2.697 3.251-5.052 3.483-.807.077-1.537.674-2.278 1.139-8.402 4.278-6.047 10.06-9.11 17.479-.387 2.996-3.991 5.904-3.438 8.988 0 .044-.144.166-.166.166-1.238-.564-1.238.719-1.448 1.183-4.235 11.885-14.926 25.627-7.607 38.109-16.042-3.007-24.113 4.091-23.914 20.155 2.311 10.371 8.536 19.149 15.412 27.12-10.746-1.105-21.912-.564-32.294 1.039-1.88-1.072-4.323.222-6.556.421-4.102 2.41-1.758-16.739-2.211-19.459 1.16-39.159 5.638-6.5 22.554-42.156.53-7.307-18.298 10.216-19.514 12.969 1.15-5.771 1.449-11.432 4.356-16.529 1.825 3.914 5.937 3.361 6.501-.84 5.406 4.754 6.313-1.636 6.645-6.103l-3.229 6.468-2.764-4.422-1.658 6.08-1.658 1.106-2.212-8.292-5.527 8.845-1.659-1.659.553-10.503-7.872 5.772c2.023-.553 3.394-2.035 5.064-3.428.276 2.433-1.117 11.034 2.233 11.631 1.537-.299 1.04.398.884 1.194-1.448 7.673-2.542 15.379-3.56 23.129-3.172-10.127-8.225-20.122-17.302-26.18-.398-.266-1.105-5.186-.619-5.484h-2.045l2.764 6.633-5.528-2.211 1.514 5.064c.465-.586-.298-1.758.1-2.466 5.815 3.793 11.288 8.535 13.853 15.103 2.82 6.545 7.451 14.074 5.472 21.227-1.846-11.277-13.664-20.918-24.731-22.09-1.128 0-2.167 1.581-.863 2.035 1.415.74.277 1.348.675 2.421 1.79 3.106 2.41 7.164 5.218 9.497 2.786 7.584 10.591 16.738 19.558 13.886.01 6.368-.177 12.493.785 18.695.21.785-.177.995-.929 1.095-5.174.243-9.994 3.35-15.102 1.625-.653-.155-1.26-.066-1.382.486 6.534 10.194 25.041-1.625 35.157-.641 10.526-.331 21.913-2.465 31.708 2.234 4.434 4.289 9.276 9.22 14.683 11.807l1.625-2.266 34.273 21.006-3.273.652c.332.21.719.42.752.829-6.744 1.968-14.66 3.77-21.249.73-8.226-6.733-9.387-9.442-13.157-19.082-2.951 3.427 1.957 6.202 3.107 9.264.232.31.586.52.498.984-.376 2.256 1.039 3.262 2.808 4.047 1.459-.067-.675 2.609 3.107 3.703.972.376 1.835.631 1.835 1.935 1.736 3.781 7.009 3.173 10.403 3.582 4.898-.331 9.707-2.012 14.506-3.117.984-.443 1.68-.21 2.465.398 17.413 11.652 11.73 15.92 25.727 1.138 1.006-.564 1.537.763 2.399 1.017 13.953 4.567 29.033 5.528 43.637 4.71 6.767-.011 12.803-9.077 14.871-14.693-.653-.763-.067-1.205.022-1.813.088-2.023 1.249-3.306 2.399-4.754-.232-2.09 1.382-3.251 2.476-4.555 2.51-1.935 9.707-13.698 12.383-10.658 2.211 0 11.354 1.902 11.542-.774.089-.895 1.703-1.437 1.471.044 1.547 3.173 12.968-.696 16.55-.829 7.64-1.979 15.478-2.41 23.052-4.146 5.052-4.997-5.407-3.427-7.872-2.731-8.756-13.421-16.274-32.172-12.571-48.612 4.721-9.21 15.423-12.548 23.87-17.391 9.43-5.539 19.889-10.459 25.882-19.978 4.488-5.881 13.123-24.654 0-24.367Zm-115.313-72.714c3.439-1.559 5.196-6.755 2.753-9.729-.851-.608.21-2.344 1.117-1.415 1.514.995 2.675 3.648 2.233 5.793-.752 7.242-10.205 9.674-6.103 5.351Zm-105.417-40.641c-1.006-.011-1.194-1.382-.166-1.581.774.155 1.36 1.658.166 1.581Zm-46.678 163.98c-1.05 5.915-9.972 15.058-14.56 15.014 3.261-6.556 9.176-10.338 14.56-15.014Zm-24.588 38.054c-8.889-3.527-13.787-13.61-17.645-21.714l.022-.022c5.583 2.189 10.337 5.396 14.174 9.851 1.558 1.99 9.32 12.073 3.449 11.885Zm187.717-17.988c1.802-4.09 1.028-21.116 4.588-20.785 6.678-1.415 5.97-5.406-.884-2.532-.509-7.009 2.631-13.853 1.868-20.608-.984-1.094.763-.995.641-1.879-.177-2.355.619-4.577.454-7.153 6.777 14.649 30.635 46.103 4.831 53.753-2.112.343-3.759 1.935-6.092.741-1.139-1.205-5.152.254-5.406-1.537Zm-.166 6.125c.409.066.829-.276 1.36.055-.398.752-1.305 1.117-2.012 1.084-.343-.487-.067-1.404.652-1.139Zm-17.225-212.791c.586-.31.21-1.305 1.006-1.416.409-.033.829.432.697.487-.63.387 0 1.503-.929 1.581-.42.044-.862-.608-.774-.652Zm-30.503 33.609c3.494-7.639 16.042-3.527 15.556 4.511-.299.697-.166.398-.841.188-1.647-.509-1.481-2.112-2.167-3.14-1.459-2.145-3.736-3.538-6.257-3.538v-.022c-3.394-.508-4.666 4.82-6.468 3.98-.707-.486-.309-1.138.177-1.979Zm-3.925 26.048c-.276 1.769-2.664.774-3.891.995-5.716.94.309 7.076-2.355 8.126-1.99.11-2.079-5.218-2.145-6.799 0-2.875 2.83-3.538 5.318-3.328v-.022l.022-.022c1.05.066 2.885-.443 3.051 1.05Zm-15.577-48.027c1.05-3.084 4.057-3.67 6.843-4.157l-.022-.022c1.703.619 8.126 2.488 6.954 5.064-.641.497-1.094.541-1.503 0-6.711-7.164-12.991 3.184-12.272-.885Zm-22.377 75.136c-2.886 1.946-7.872-3.405-8.126-6.324-1.371-1.968-3.063-8.259.53-8.613.708.255.542.929.398 1.261-1.415 3.46.818 6.169 1.979 8.999.442 2.698 5.506 2.432 5.219 4.677Zm14.825-49.32c-5.992-7.806-16.815-2.853-15.522 6.589-.321 1.183 1.139 4.433-.442 5.141-.84.166-1.028-.575-1.194-1.349-.796-5.207-1.15-11.951 4.289-14.66 1.04-.332-.342.84.465.862.398.067.398-.519.398-.818 2.919-3.117 8.137-2.388 11.807 1.028.808.852 2.941 1.803 1.791 3.207-.563.586-1.116.398-1.592 0Zm6.225 57.103c-5.174-11.067-6.91-6.324.906-10.591.885-.642 2.764-.885 3.516-1.869.564-3.781 10.957.31 12.637 1.824 4.5 3.958-2.874 15.379 5.937 15.633l.044.056c2.775.033 8.06-4.312 5.76-6.899-1.116-.443-2.443.077-2.686 1.138-.409 1.637-1.603 2.189-3.041 2.521-3.117-.718-.232-8.424-1.592-11.222.277-1.37-2.719-3.626-1.017-4.068 2.698-.376 4.588-2.145 6.49-3.847 3.085-1.648 7.275 4.477 14.041 1.592 1.78-.752 1.647 5.085 7.363 6.323 2.775 1.803-1.647 7.253-3.195 8.967-11.211 14.892-34.373 16.805-45.163.442Zm7.872 19.901c1.536-2.057 2.531-5.329 2.023-7.076l.022-.044c6.457 2.808 13.577 3.88 20.298 1.37 1.029-.398 1.405-.055 1.515.885.232 2.366 1.603 4.19 2.676 6.235-4.777 4.644-11.565 6.258-17.922 4.356-1.99-.785-11.575-2.896-8.612-5.726Zm-37.657 13.797h.056c9.939-5.904 22.321-4.411 32.172-10.337.553-.42.84-.232 1.261.122 9.043 8.336 25.074 8.911 33.631-.188.244-.42.454-.299.664-.089 2.134 2.3 5.163 2.842 7.883 3.98 3.427 1.725 8.579 2.609 11.409 4.213-7.706 1.05-16.573 1.293-24.511 1.647-.375-.21-.674.077-.928.287-.288.255.53.929-.288 1.04-.575.055-.508-.807-.951-.841-1.26-.132-2.564-.387-3.792-.177-1.581.255-3.327-.497-4.732.719-11.31-1.216-23.106 1.039-34.549-.298-.42.11-1.072-.266-1.238.508-.045.133-.111.299-.277.133-4.853-2.444-10.204.066-15.754-.719l-.1.067.044-.067Zm36.142 97.413c16.551-1.338 33.532.21 49.652-3.306-13.82 11.089-28.049 21.194-44.467 27.751-1.116.431-1.979.254-2.908-.885-7.042-8.214-14.107-16.495-21.746-24.19 6.456.21 12.968.42 19.469.63Zm-5.34-49.95c.166.652 1.282 1.072.464 1.979-.32.343-.32.11-.508-.022-1.028-.653-.022-1.283.044-1.957Zm8.568-10.636c.553-1.249 1.139-4.864 2.985-4.079.144.099.509 0 .719-.111 9.829-5.229 11.045 27.706-.299 20.044-4.101-3.593-4.378-10.746-3.405-15.854Zm18.773-35.522c1.017-.232 1.67.121 1.835 1.448-.818-.254-1.746.785-2.332-.398-.255-.508 0-.929.497-1.05Zm-89.453 55.843c2.267-7.275 6.789-14.174 8.546-21.393-.497-1.095 1.338-.089 1.349-1.449.299-1.083.321-2.189 1.183-3.073.232-.254.863-.973.078-1.526-.056-.033-.078-.376-.045-.376 1.316-.608 1.316-2.1 2.068-3.073 1.758-2.499 1.061 4.776 1.879 5.605.631 1.703.233 3.472.819 5.13.541 1.581-.343 3.604 1.448 4.831-1.415 2.466-.254 4.942-.542 7.64l-.044.044c-1.404-1.526-4.82-2.465-3.45.42.697 1.239 2.234 1.791 2.897 2.985 2.466 6.38 2.278 13.875 3.671 20.686-.94 1.868-5.429-.885-7.12-1.327-6.711-2.056-13.466-7.44-12.737-15.124Zm143.538 68.712c-4.986 2.708-9.906 6.379-15.445 7.728l4.909 2.454c-.409-.287-.608-.398-1.083-.685 3.405-1.913 7.064-3.107 10.525-4.821-2.355 1.99-4.478 5.418-7.021 6.811l-.884 2.222c.984.741.309 2.565-.962 2.399-.21.52-.763 1.924-.984 2.466 1.106.309.232 1.824-.686 1.724l-.95 2.355c1.802.033.63 1.924-.763 1.913-.022.564-1.537 1.99-1.88 2.388h.885l.022-.022v.022h-.022c-.641.774-1.25 1.072-1.979 1.183l-2.698 2.885c.586.023 1.183.056 1.78.122-8.469 7.651-20.564 1.946-30.636 2.112-5.494-.509-15.677-.951-19.314-4.688l-2.819-1.404c-2.2 2.421-7.861 10.813-11.233 9.143-9.563-7.374-19.867-13.665-29.818-20.508-14.007-9.508-31.542-14.638-41.326-29.376-5.55-8.236-13.986-16.219-13.787-26.832.221-8.723 6.247-15.998 15.456-15.158l-.022.022c10.448 1.261 19.27 7.662 29.552 9.763 10.68 7.993 21.15 16.517 30.304 26.39 8.104 9.939 16.584 19.657 24.843 29.419 1.979 1.736 2.145 3.549 1.846 5.473l1.935-4.643 2.532.486c-1.537-1.017-12.184-11.808-8.757-12.117 15.158-6.446 29.132-15.445 41.637-26.092 10.458-9.497 32.028-21.924 46.18-16.241 13.919 15.721-5.628 35.191-19.337 43.107Zm41.294-97.944c-34.107-44.864 12.349-36.385 6.246 10.492l-.022.022s0-.033.011-.055c-1.614-3.881-3.869-7.197-6.235-10.459Zm51.94-10.182c-6.954 20.973-29.364 31.277-47.805 40.431 0 .011-.011.011-.011.022h-.023c4.29-10.282 16.131-13.798 23.074-21.78 5.307-4.975 9.795-10.68 12.803-17.347 3.239-6.191 15.997-15.4 11.962-1.326Z" fill="#000"/><path d="M284.643 87.01c.619-35.545 45.517-37.049 53.787-4.523 9.63 46.026-52.648 49.199-53.776 4.511l-.022.022.011-.01Zm41.205 1.116c7.419-4.621 11.034-10.26 4.025-17.159-1.205-1.47-7.452-8.214-8.734-6.102-.233 2.852-2.786 5.306-3.162 7.75 3.372 4.72 5.881 10.05 7.849 15.544l.022-.022v-.011Zm-27.562-3.427c.52 3.36-.11 9.84 2.488 12.062 2.808-.553 11.255-.597 12.15-3.14-1.448-4.81-2.211-10.88-4.754-14.826-8.612 2.83-9.917-2.123-9.851 5.893h-.022l-.011.01Zm-8.922-9.873c-2.078 5.782-3.991 13.035-1.371 18.695 3.007 1.515 6.147 2.654 9.663 2.952-1.349-5.384-1.902-10.69-1.47-16.175.044-.762-.133-1.094-.951-1.348-2.322-.719-4.334-1.957-5.849-4.146l-.022.022Zm45.185 28.601c3.472-6.445 3.56-16.174.984-21.813-2.576 2.94-4.621 6.17-8.104 8.082-.74.486-1.116.696-.63 1.769 1.99 1.702.708 9.11 2.753 9.309 2.145 0 3.538 1.415 5.008 2.631l-.022.022h.011ZM316.34 73.941c-9.342 7.209-4.3 2.322-1.326 18.453.442 2.653 6.423-2.4 8.214-2.72 1.161-3.107-4.931-12.272-6.865-15.733h-.023Zm-28.059 22.322c2.52 8.159 8.026 14.152 14.969 18.574.255.21 1.239-.21 1.161-.487-.376-1.138.465-1.769.774-2.631-.531-3.129-4.102-5.76-5.008-9.032-1.758-5.307-7.573-4.025-11.896-6.424Zm26.865 6.025c-.652-1.514-.265-5.693-2.399-5.373-3.637 1.073-7.33 1.913-11.155 1.836-.442 0-.885.088-.63.652 1.127 1.703 4.256 9.851 6.08 8.955 1.814-3.239 6.114-3.648 8.127-6.047l-.023-.023Zm11.322-2.564c-.686-1.57-.973-8.115-3.052-7.684-2.255 1.536-6.335 2.288-7.684 4.466 1.493 1.415.509 4.577 2.001 5.451 1.747-.763 3.704-.564 5.407-1.448 1.061-.609 2.178-.642 3.095.022.354-.144.166-.531.233-.796v-.011ZM302.51 64.09c-1.791 4.002-2.532 8.17-3.372 12.316.077 3.118 5.704.84 7.683.553 2.167-.564-3.549-11.145-4.311-12.87Zm19.834 39.148c-.641-.398-4.588.675-4.467 1.471.487 3.471.885 6.976 1.327 10.47.066.541.276.11.442.022 3.483-3.007 6.158-7.983 6.424-12.405-.255-.144-.841-.166-.995 0-.763.829-1.681.442-2.731.442Zm-6.048-32.47c.918-2.477 4.655-6.91 1.703-8.359-3.947-1.194-9.276-2.388-12.991-.32 5.031 1.205 8.248 4.676 11.266 8.678h.022Zm-16.163-6.889c-4.014.697-6.966 5.108-9.365 8.26-1.293 1.735 3.593 4.112 5.009 4.842 1.968.287 2.31-10.625 4.333-13.102h.023Zm15.898 46.247h.022c.652-8.358-3.483-3.67-7.308-.586-1.89 2.377 5.053 4.942 6.799 6.003 2.101.73.233-4.179.509-5.439l-.022.022Zm-10.78-45.528c2.024 1.57 3.295 11.918 5.495 10.757.995-1.05 4.577-2.09 3.582-3.747-2.675-2.72-4.82-6.722-9.077-7.01Zm18.021 50.459c3.881-1.957 15.656-9.63 6.236-11.896-1.681-.862-2.985 9.674-6.213 11.918l-.023-.022Zm-10.038 2.123c-2.377-.896-4.279-3.262-6.258-4.301-3.084 4.234 3.527 4.002 6.258 4.301ZM190.636 29.906c-.254 3.438 1.404 7.495 5.329 7.396 1.282.32 1.725 1.072.951 2.322-2.167 4.521-3.074 9.43-5.683 13.775-1.183 2.19-2.211 4.511-2.72 6.987-.11.564-.11 1.14-.84 1.206-.763.066-1.028-.42-1.205-1.073-1.437-6.865-1.99-14.162-6.313-19.989-1.349-.984-1.095-3.427.696-3.073 4.81 2.708 5.473-10.537 5.727-13.522.1-1.625-.53-4.654 1.681-4.93 2.189-.056 1.714 3.747 1.979 5.24.033 3.438.619 3.383.387 6.324v-.652l.011-.011Zm-2.554 4.842c-.63 2.19-1.305 3.914-2.841 5.163-.487.398-.166.774.044 1.006 2.487 3.24 2.333 7.242 3.051 11.167 5.329-15.965 4.887-6.546-.276-17.336h.022ZM157.568 12.438c-.1 1.493.575 3.295 2.277 3.262 1.67.066-3.106 9.33-3.548 10.713-1.692-2.41-.918-6.755-3.218-9.287-.564-.431-.486-1.504.299-1.36 3.04 1.437 1.57-7.85 3.173-8.137 1.161-.155.873 4.345 1.017 5.097v-.288Zm-1.095 2.134c-.265.962-.563 1.725-1.216 2.277.542 1.593 1.261 3.428 1.327 5.374.464-1.736 1.493-3.483 1.625-5.097-.851-.586-1.426-1.393-1.736-2.543v-.011Z" fill="#010101"/><path d="M157.568 12.438c-.1 1.493.575 3.295 2.277 3.262 1.67.066-3.106 9.33-3.548 10.713-1.692-2.41-.918-6.755-3.218-9.287-.564-.431-.486-1.504.299-1.36 3.04 1.437 1.57-7.85 3.173-8.137 1.161-.155.873 4.345 1.017 5.097v-.288Zm-1.095 2.134c-.265.962-.563 1.725-1.216 2.277.542 1.593 1.261 3.428 1.327 5.374.464-1.736 1.493-3.483 1.625-5.097-.851-.586-1.426-1.393-1.736-2.543v-.011Z" fill="#000"/><path d="M41.691 75.025c-1.88 4.666-5.174 9.21-5.14 14.66-.144 1.98-.763 3.914-.51 5.96.145 1.205-1.26 1.094-1.68 1.857-3.482-2.853-.265-21.139-7.893-21.88-1.007-.11-1.239-1.138-.277-1.702 1.869-1.14 2.753-3.074 3.14-4.843 1.67-2.952 1.028-13.19 3.372-13.565 4.6 3.87 0 16.307 7.606 17.778 1.095.044 1.371.63 1.371 1.79l.022-.044-.01-.01Zm-8.822-5.727c-.608 1.603-.84 2.908-1.493 4.069-.232.398-.608.763-.143 1.327 2.167 2.564 2.51 5.837 3.394 9.076 3.67-10.757.475-4.82-1.747-14.472h-.011ZM259.072 43.284c-.41 2.94-1.57 16.274 3.935 14.405 1.482-1.647 3.793.498 2.212 2.256-3.45 4.93-6.678 9.983-7.33 16.219.342 3.195-3.815 2.067-3.306-.675.685-4.555-.719-9.961-4.445-12.847-1.116-.763-.508-2.09-1.282-2.885 2.233-2.687 4.057-.818 5.097-5.141 2.2-3.273 1.216-13.92 3.77-14.616 1.459.232 1.194 1.902 1.282 3.284h.067Zm-1.858 24.953c4.5-8.989 1.57-4.49-.508-12.383-4.898 9.32-2.245 2.366.486 12.405l.022-.022ZM83.284 154.948c-.41 2.94-1.57 16.274 3.935 14.405 1.482-1.647 3.793.509 2.212 2.256-3.45 4.931-6.678 9.983-7.33 16.219.342 3.195-3.815 2.067-3.306-.675.685-4.555-.708-9.961-4.445-12.847-1.116-.762-.508-2.089-1.282-2.885 2.233-2.687 4.057-.807 5.097-5.141 2.2-3.273 1.216-13.908 3.77-14.616 1.459.232 1.194 1.902 1.282 3.284h.067Zm-1.858 24.953c4.5-9 1.57-4.489-.508-12.383-4.887 9.32-2.245 2.366.486 12.405l.022-.022ZM39.646 37.845c.918-3.46.74-12.382-3.35-13.5-.973-.275-.796-1.912-1.913-2.089-.331-.044-.53-.586-.398-1.006.122-.42.321-.718.84-.906 5.54-1.128 6.06-7.419 6.922-12.029 4.179-6.014.475 14.671 6.28 11.1.961-.63 2.144.453 1.813 1.47-2.521 5.396-6.855 10.702-7.054 17.015.785 2.952-2.83 2.035-3.162-.066h.022v.011Zm2.908-8.259c4.311-8.137 1.536-3.725-.089-11.221-3.493 3.726-.575 6.854.089 11.221ZM62.797 116.506c1.581-2.156 1.935-7.208 5.075-6.655.552.398.53.95.298 1.492-.785 2.255-1.957 4.168-2.543 6.512 2.2-.586 4.788-3.792 6.778-2.399.53.63.165 1.415-.531 1.913-1.183 1.547-6.623 3.04-5.307 5.096.807 1.161 4.124 4.367 1.139 4.721-.929 0-2.023.542-2.698-.995-.143 1.415 1.073 2.952-.74 3.416-1.26.332-1.095-1.116-1.537-1.89-.509.542-.719 1.304-1.625 1.492-3.162.564-1.018-3.261-.741-4.864-1.028-.255-2.654 1.006-3.306-.166-.873-1.736 3.814-2.267 1.537-4.047-2.31-1.746-3.129-4.201.509-4.566.884.089.762-.21.718-.718.055-.73-.564-1.935.675-2.09 2 .089 1.293 2.477 2.3 3.748ZM226.059 14.062c-1.482 1.482-1.416 6.545-4.058 5.628-.553-.21-1.161-.675-.763-1.67.321-1.824 3.66-7.606-.398-5.163-.53.21-1.205.995-1.581 0-.298-.774-.608-1.88.84-2.1.863-.122 1.537-.719 2.333-1.05-1.039-1.66-4.566-6.468-.11-4.865 2.377-.741 1.006 1.503 2.277 2.885.973-1.028.608-2.355.863-3.493.254-1.095.696-1.68 1.835-1.814 3.206-.32 1.526 3.693.674 5.396 2.72-.221 5.042-4.334 7.408-2.256.508.564.884 1.305-.144 1.725-2.421 1.139-5.605 2.167-7.496 3.704.044.84.885 1.304 1.537 1.647.785.398 2.299 2.488 2.045 3.24-.464 1.47-1.901.53-2.609-.255-.94.74.984 2.61-1.028 2.886-2.278 0-1.095-2.985-1.625-4.467v.022ZM31.476 172.161c-1.481 1.481-1.415 6.545-4.057 5.627-3.118-.862 4.278-9.696-1.161-6.821-.531.21-1.205.995-1.581 0-.299-.774-.608-1.88.84-2.101.862-.122 1.537-.719 2.333-1.05-1.04-1.659-4.566-6.468-.11-4.865 2.376-.741 1.005 1.504 2.277 2.886.973-1.029.608-2.355.862-3.494.254-1.095.697-1.68 1.835-1.813 3.206-.321 1.526 3.693.675 5.395 2.72-.221 5.041-4.345 7.407-2.255.509.564.885 1.304-.144 1.724-2.42 1.139-5.605 2.167-7.495 3.704.044.84.884 1.305 1.536 1.647.774.398 2.3 2.488 2.046 3.24-.465 1.481-1.902.53-2.61-.254-.94.729.984 2.609-1.028 2.885-2.277 0-1.094-2.985-1.625-4.466v.022-.011ZM50.05 208.778c-.973.951-.951 4.157-2.665 3.56-.354-.133-.763-.431-.497-1.05.232-1.195 2.377-4.799-.266-3.262-.343.133-.785.63-1.039 0-.807-1.36 1.26-1.404 2.078-2.001-.707-1.084-2.974-4.091-.066-3.074 1.559-.464.652.94 1.493 1.825.63-.653.398-1.493.563-2.212.166-.696.454-1.061 1.194-1.149 2.09-.21 1.007 2.321.443 3.405 1.78-.133 3.306-2.742 4.853-1.426.332.365.575.829-.1 1.094-1.591.719-3.67 1.36-4.908 2.344.31 1.061 2.565 1.725 2.344 3.096-.31.928-1.238.342-1.714-.166-.586.497.586 1.713-.674 1.824-1.482 0-.719-1.868-1.062-2.819l.023.011ZM286.412 178.154c-1.183-7.872 12.947-7.452 12.427-.1 1.172 8.801-13.145 8.436-12.427.089v.022-.011Zm8.845.884c.287-1.934-2.764-5.373-4.721-3.162-4.19 3.616 4.577 8.834 4.732 3.162h-.022.011ZM193.765 203.692c-.487 2.709-5.318 7.12-7.496 4.467-.431-2.2 4.245-2.465 4.732-5.163.674-2.443 2.576-1.371 2.775.696h-.022.011ZM168.413 196.428c-6.456.353-5.373-5.219-2.332-3.472 2.432 2.532 4.245-1.791 6.124-.343 1.206 1.758-2.565 3.947-3.792 3.793v.022ZM192.748 194.474c-1.471-.166-4.257-1.78-2.985-3.516.42-.398.862-.796 1.68-.254.984 1.182 2.863 1.592 3.914-.089 3.339-2.72 3.129 4.091-2.609 3.859ZM100.707 35.809c4.655-8.469 8.281-17.756 14.229-25.296 8.602-3.66-.21 20.365-1.492 23.626 29.64-7.374 37.037-2.045 3.936 9.01 7.308 5.462 14.892 10.791 21.448 17.226 7.905 15.301-15.932-.144-19.812-3.56 3.869 7.031 9.231 14.383 10.005 22.72-.995 3.748-6.335 2.454-8.358-.21-5.782-6.092-10.702-12.803-15.323-19.79-.398-.487-.675-.653-1.238-.487 1.459 4.644-1.714 31.51-8.945 29.652-4.3-4.157-4.477-25.992-5.45-33.19-7.308 2.233-14.395 4.787-21.813 6.468-12.25-.708 9.33-14.693 12.802-15.965-4.123-4.322-17.214-6.998-15.268-14.34 3.615-3.846 8.359.786 12.46 1.405 2.698 1.16 5.605 1.857 8.104 3.471.674.653 1.283.1.84-.674-4.3-53.41 1.404-41.935 14.019-.11l-.144.022v.022Zm36.131 26.788c-12.405-17.336-40.442-17.446-9.475-28.325-29.453 7.86-16.34 6.434-11.852-19.525h-.276c-20.675 35.357-13.488 31.72-26.678-4.311.53 37.18 10.536 35.124-17.877 24.3l-.255.321c22.83 15.644 21.195 7.44-1.348 22.443 33.753-5.804 18.728-15.268 27.352 26.236 10.348-24.29-5.285-47.253 23.77-12.128 6.755 8.723 4.068 2.84 1.581-2.908-2.919-6.29-7.087-11.863-10.968-17.568-3.383-9.862 21.979 12.372 26.026 11.388v.077Z" fill="#010101"/></g><defs><linearGradient id="b" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="c" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="d" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="e" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="f" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="g" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="h" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="i" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="j" x1="6.633" y1="4.422" x2="333.234" y2="4.422" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h340.088v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-privacysegmentation.svg b/browser/components/newtab/data/content/assets/mr-privacysegmentation.svg
new file mode 100644
index 0000000000..feda0087d7
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-privacysegmentation.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="389" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><g clip-path="url(#b)"><path d="M372.478 328.041c-2.103 2.739-4.104 5.58-6.181 8.319-2.027 2.687-4.079 5.373-6.208 7.957-2.462 2.971-5.155 5.761-7.797 8.577-2.463 2.609-5.31 4.753-7.849 7.233-1.975 1.964-4.284 3.798-6.567 5.529-2.462 1.86-4.976 3.668-7.438 5.503-.513.387-.667.413-1.283 0-4.078-2.636-6.823-6.666-10.131-10.05-2.232-2.299-3.95-5.089-6.054-7.544-2.513-2.945-5.258-5.631-7.977-8.344-2.847-2.816-5.386-5.864-7.926-8.939-.051-.077-.077-.206-.205-.465 2.899-.981 5.387-2.609 7.875-4.159 5.643-3.513 10.747-7.776 15.851-11.987 3.489-2.868 6.772-5.916 9.978-9.016 3.514-3.384 7.003-6.975 9.285-11.445.616-1.188 1.078-2.428 1.334-3.746.128-.697.411-1.472.872-1.679.59-.258.821.723 1.257 1.033 3.206 2.3 5.797 5.322 8.747 7.906 2.077 1.834 4.001 4.004 5.976 6.019 3.053 3.1 5.669 6.614 8.952 9.533 1.565 1.395 3.078 2.919 4.309 4.624.488.698 1.001 0 1.488.569 1.282 1.498 1.282 2.48-.308 4.572ZM321.401 281.546c-1.134 2.261-2.479 4.445-3.85 6.628-1.687 2.73-3.691 5.277-5.748 7.642-1.397 1.56-3.243 3.016-5.009 4.393-2.742 2.08-5.643 4.004-8.306 6.239a151.716 151.716 0 0 1-9.465 7.304c-1.398-.753-1.951.676-2.795 1.066-2.004-2.131-3.243-4.757-5.326-6.862-1.029-1.04-1.767-2.6-2.637-3.925-1.608-2.574-3.48-5.017-5.141-7.565-.739-1.143-.396-1.455.29-2.027 2.214-1.716 4.403-3.509 6.697-5.121 2.768-1.95 5.326-4.133 7.962-6.213 3.771-2.937 7.41-6.004 11.022-9.124 2.768-2.417 5.379-5.017 8.042-7.512.237-.208.448-.364.632-.65 1.345-1.975 2.136-1.975 3.454-.104 1.424 2.028 2.848 4.107 4.43 5.979 1.45 1.767 2.478 3.795 4.06 5.407.291.312.554.883.897.935 3.085.52 1.16 2.756.791 3.51Z" fill="#4E3413"/><path d="m147.992 179.145-19.981-71.35v-8.123l10.978 4.61 14.053 22.174 8.124 44.566-13.174 8.123Z" fill="#FFDBC7"/><path d="M189.62 194.948c-.432 8.627-1.649 17.179-3.551 25.603a85.254 85.254 0 0 1-5.936 17.559c-2.131 4.567-4.794 8.881-7.66 13.042-.863 1.244-1.497 2.69-2.232 4.009-.837 1.447-2.435 2.462-2.993 4.111-.939 2.766-3.501 4.212-5.073 6.47-1.674 2.335-3.678 4.441-5.454 6.725-3.044 3.882-6.569 7.282-9.765 10.987-1.675 1.903-3.323 3.882-5.023 5.734-2.638 2.842-4.794 6.039-7.533 8.881-4.515-5.582-8.092-11.723-12.302-17.457-2.765-3.781-5.352-7.765-8.447-11.292-2.688-3.07-5.504-6.09-8.548-8.855-1.496-1.345-2.891-2.842-4.337-4.238-.355-.33-.507-.584-.305-1.091 2.207-5.303 2.943-10.962 3.78-16.595 1.091-7.282 1.725-14.615 1.623-21.999-.051-5.608-.101-11.241-1.192-16.798-.685-3.451-1.37-6.927-2.486-10.251-1.116-3.248-2.765-6.268-4.388-9.262-2.334-4.288-5.301-8.17-7.736-12.382-1.953-3.426-3.881-6.852-5.403-10.505-.279-.66-.533-1.371-.609-2.081-.101-.787-.583-1.726.305-2.309.963-.66 1.953-.152 2.688.406 5.961 4.618 10.958 10.023 14.408 16.798 1.724 3.374 3.754 6.597 5.529 9.921.381.736 1.015 1.091 1.548 1.37.608.33.989.584 1.192 1.269.228.837.862 1.319 1.801 1.142.837-.153 1.623-.051 2.029-1.218 1.09-3.121 1.192-6.268 1.014-9.49-.431-8.044-2.891-15.631-5.402-23.218-1.674-5.1-3.374-10.2-4.389-15.503-.101-.533-.076-1.092-.025-1.624.051-.99-.203-2.335.761-2.792 1.015-.482 2.308.102 3.196.736 1.877 1.32 3.526 2.944 4.515 5.101.102.228.228.532.406.583 3.221.812 4.084 3.603 4.971 6.191 1.573 4.568 3.602 9.008 4.642 13.753 1.218 5.608 1.573 11.267.964 17.001-.33 3.02-.761 5.988-1.522 8.932-.355 1.472.71 3.349 1.852 3.222 1.268-.127 2.486-.761 2.79-2.309a74.549 74.549 0 0 0 1.573-14.057c.076-4.06-.051-8.069-.888-12.002a75.41 75.41 0 0 0-4.743-14.717c-1.446-3.35-2.461-6.877-3.729-10.302-1.573-4.314-3.145-8.627-3.577-13.22-.202-2.055-.456-4.136.051-6.217.457-1.827 1.598-2.309 3.272-1.522 1.421.685 2.309 1.852 3.323 2.918 1.218 1.294 2.537 2.486 4.109 3.273 1.421.711 1.446 2.182 1.827 3.299 1.217 3.501 3.119 6.699 4.489 10.124 1.395 3.502 3.145 6.851 4.16 10.556.812 3.019 1.902 6.013 2.41 9.033.735 4.415 1.496 8.881 1.547 13.398.051 3.349.279 6.673.178 10.048-.051 1.7-.305 3.375-.305 5.049 0 1.218.66 2.411 2.105 2.436 1.167 0 2.233-.38 2.461-1.903.279-1.827.659-3.603.406-5.455-.178-1.193.355-1.294 1.369-1.041 3.754.965 7.432 1.193 10.933-1.015 1.04-.659 1.471-.101 1.496.99.076 4.846.406 9.693.711 14.514.202 3.096.38 6.267.735 9.389.305 2.461.228 4.948 1.091 7.333.203.507.177 1.116.989.989-.304.939 1.801 1.168.634 2.563-.71.837-.583 2.233.127 3.223.558.735 1.547.989 2.486.761.735-.178 1.446-.432 1.674-1.37.964-4.187 2.993-7.968 4.312-12.028 1.268-3.882 2.613-7.739 3.5-11.697.584-2.512 1.142-5.05 1.471-7.613.33-2.664.711-5.354 1.193-7.992.558-3.02.634-6.141 1.014-9.211.152-1.218.558-2.462.939-3.654.634-2.03 2.257-2.411 4.109-1.345 2.79 1.599 3.551 4.288 3.957 7.079.558 3.933.786 7.892 1.014 11.876.356 6.419.178 12.814-.126 19.233Z" fill="#FFDBC7"/><path d="m69.165 72.448 4.172-13.172 5.49-4.172 6.147 5.489 3.074 11.855-6.806 5.05h-7.905l-4.172-5.05Z" fill="url(#c)"/><path d="m311.134 61.032-6.367-13.392 6.367-5.269 5.929 6.806-5.929 11.855Z" fill="url(#d)"/><path d="m349.779 84.742 10.1-9.88 2.635 2.635-1.756 14.71-4.611 7.464h-6.368l-3.074-7.245 3.074-7.684Z" fill="url(#e)"/><path d="m49.404 203.952-5.49-6.367-3.074 5.05 5.929 10.318 2.635-9.001Z" fill="url(#f)"/><path d="M144.039 170.143v-6.147l8.344-1.318 6.368-4.171 2.854 8.343-9.881 4.61-7.685-1.317Z" fill="url(#g)"/><path d="m286.103 340.285-12.077-17.563-1.756-9.22 3.733-3.952 10.1 8.562 16.248-11.416 14.492-15.587 5.929-11.855-9.223-11.636 5.051-1.756 5.709 5.488 15.809 12.294-4.172 17.783-16.468 17.783-33.375 21.075Z" fill="url(#h)"/><path d="M385.803 291.858c-3.983-6.14-8.523-6.343-14.256-4.11-2.308.913-4.819 1.751-6.518 3.705-1.193 1.37-2.943 1.065-4.262 1.979-1.801 1.268-3.855 2.106-5.884 2.994-.914.38-1.877.913-2.461 1.675-.558.71-.634.659-1.243.126-1.978-1.776-4.109-3.425-6.113-5.176-.786-.71-2.105-1.827-1.953-2.41.406-1.599 0-3.248.381-4.695.735-2.765-.33-4.973-1.852-6.876-1.42-1.726-2.739-3.553-4.642-4.948-2.612-1.929-5.073-3.958-8.269-4.872-1.42-.381-3.17-1.142-3.855-1.979-1.421-1.675-3.12-2.055-4.921-2.385-1.471-.279-3.323-.736-4.414-.102-2.08 1.218-2.79-.355-3.551-1.294-.583-.71-2.156-1.319-1.395-2.563.837-1.319 1.573-2.664 2.334-4.009 2.08-3.603 2.917-7.46 1.75-11.469-.837-2.867-2.181-5.659-5.403-6.673-4.54-1.421-8.548-.406-11.997 2.892-1.04.964-2.309.914-3.298.127-.507-.431-2.283-.787-.862-2.157-.432-.355-.102-1.395-.634-1.268-.888.177-1.015-.381-1.421-.787-1.446-1.345-1.699-3.324-2.587-4.973-.863-1.599-1.395-3.401-2.562-4.822-1.395-1.725-1.522-3.856-1.573-5.81-.05-2.132.355-4.339.99-6.369.583-1.827.913-3.654 2.435-5.354 1.598-1.802 2.409-4.491 3.678-6.724 2.003-3.553 4.591-6.699 7.406-9.617 1.116-1.142 2.232-2.385 3.551-3.35 1.522-1.091 2.943-2.283 4.642-3.146 1.674-.837 3.982-.913 4.642-3.451.127-.533.786-1.649 1.598-2.36 2.917-2.486 5.504-5.227 6.798-9.134 1.09-3.401 1.217-6.446-.558-9.516-1.142-1.979-3.019-3.045-5.073-3.984-.863-.38-.711.609-1.446.483-1.598-.28-3.196.558-4.642 1.141-1.978.812-3.957 1.802-5.783 3.096a179.528 179.528 0 0 0-4.946 3.679c-2.106 1.624-4.363 2.995-6.545 4.492-.355.253-1.344.786-1.699-.686-.431-1.877.33-3.298 1.015-4.871 1.445-3.324 3.094-6.598 5.149-9.516 1.877-2.613 3.779-5.227 5.808-7.764 1.979-2.487 3.78-5.177 5.809-7.587 1.167-1.37 2.308-2.842 3.5-4.212 2.537-2.918 4.693-6.141 6.976-9.262 1.623-2.182 3.373-4.314 4.768-6.572 1.471-2.41 2.917-5.024 2.486-8.272-.304-2.512-1.319-4.973-3.576-5.1-2.435-.127-4.921.482-7.255 1.345-2.156.812-4.109 1.979-5.961 3.273-2.054 1.421-4.083 2.918-5.707 4.821-1.674 1.979-3.449 3.806-5.123 5.76-1.218 1.421-2.436 2.766-3.425 4.39-.507.837-.634 2.41-1.471 2.487-1.167.126-1.75 1.014-1.877 1.497-.304 1.141-1.091 1.953-1.725 2.715-2.004 2.461-3.475 5.328-5.682 7.561-.862.863-.862 2.309-2.079 2.817-.635-.838.431-.939.583-1.472.888-2.994 2.587-5.633 4.058-8.348 1.598-2.944 3.526-5.684 5.226-8.577 2.308-3.857 4.388-7.84 6.518-11.799 1.472-2.74 2.791-5.886 2.664-9.337-.153-3.781-1.37-5.811-4.794-5.735-2.816.076-5.175 1.725-7.508 3.172a26.23 26.23 0 0 0-2.512 1.776c-.71.584-.811 2.081-2.282 1.446-.076 0-.229.153-.229.229-.126.71-.608.989-1.166.761-.66-.254-.203-.964-.33-1.446-.102-.457.076-.99-.051-1.421-.304-1.168-.558-2.436-2.232-2.386-2.46.051-4.794.457-6.95 1.802-2.131 1.294-4.363 2.284-5.859 4.517-.635.989-1.04 2.461-2.435 2.867-1.421.406-1.979 1.649-2.816 2.664-.533.609-1.015 2.056-2.435.939-.127-.101-1.192-.33-1.953-.228-3.45.355-5.834 2.639-8.548 4.263-1.04.609-2.004 1.674-2.714 2.664-1.37 1.852-2.917 3.552-4.236 5.43-.457.634-.431 1.497-.761 1.7-2.258 1.37-3.12 3.908-4.363 5.887-1.775 2.791-3.551 5.811-4.312 9.16-.304 1.37-1.42 2.411-1.42 3.781.025 1.573-.584 3.095-1.193 4.263-1.268 2.385-1.978 4.973-3.246 7.333-1.192 2.258-1.725 4.796-2.816 7.105-.456.938-.862 2.03-1.293 2.994-.787 1.675-1.015 3.476-1.624 5.176-1.42 3.882-2.511 7.917-4.084 11.748-.963 2.36-1.116 4.923-2.206 7.232-1.091 2.335-1.953 4.796-2.435 7.308-.584 3.248-2.03 6.242-2.638 9.49-.279 1.395-.051 2.893-.457 4.161-.888 2.766-.659 5.557-.583 8.323.101 2.893.558 5.76 1.141 8.653.786 3.831 1.75 7.612 3.5 11.063 2.943 5.861 7.762 10.2 12.632 14.463.837.736 1.7 1.497 2.511 2.335 1.04 1.065 2.359 2.004 3.628 2.791 2.587 1.548 5.174 3.095 7.026 5.43 4.058 5.176 7.888 10.556 11.82 15.859.406.507.507.862.177 1.573-1.014 2.334-2.359 4.618-2.612 7.232-.406 4.364.127 8.449 4.185 11.063 2.942 1.878 6.113 1.192 9.03 0 4.819-2.005 4.819-2.487 8.168 1.066.304.329.558.786.659 1.065.685 1.751 3.297 2.462 2.308 5.329-.532 1.472-1.268 3.096-1.293 4.897-.026 3.147-.229 6.268.735 9.287 1.218 3.755 3.704 6.775 5.961 9.921 1.446 2.056 3.145 3.908 4.845 5.76 2.105 2.309 4.921 2.842 7.051 1.497 1.759-1.099 3.34-.879 4.744.66.152.178.38.305.507.457 1.649 2.004 3.094 3.857.482 6.343-1.421 1.345-1.979 3.451-3.171 5.075-1.801 2.462-3.196 5.227-4.261 8.12-1.066 2.944-2.131 5.785-2.308 9.084-.127 2.233.329 4.339.481 6.471.178 2.816 1.827 5.227 3.628 7.18 1.243 1.345 2.587 3.857 5.352 2.259.279-.178.964-.254.659.659-.228.711.355 1.041 1.015 1.472 1.014.685 2.004.229 2.942.482 2.943.736 5.834.229 8.574-.609 6.696-2.08 12.631-5.81 18.516-9.49 2.917-1.827 5.935-3.552 8.624-5.683 1.953-1.548 4.135-2.817 5.986-4.542 2.309-2.107 4.744-4.111 7.026-6.243a180.834 180.834 0 0 1 4.033-3.653c.812-.736.736-.889.254-1.574 1.598.66 2.41-.482 3.019-1.294 1.648-2.157 3.627-3.984 5.428-5.963 1.953-2.182 3.678-4.567 5.504-6.825 1.877-2.309 3.45-4.974 5.352-7.257 2.511-3.045 4.692-6.293 6.95-9.465 1.522-2.182 2.739-4.644 4.236-6.851 2.689-4.009 4.616-8.272 5.504-12.966.989-5.38.736-10.632-2.333-15.377v-.026Zm-65.569-22.583c.355.33 1.192-.076 1.065.609-.127.838-.786 1.447-1.446 1.98-.431.329-.811.076-1.242-.28-.863-.71-1.218-1.674-1.725-2.613 1.192.228 2.409-.508 3.348.304Zm-19.937-24.587c.71-.279 1.446-.685 1.953-1.117.837-.685 1.522-1.167 2.41-.761 5.098-.457 6.899 4.77 5.529 8.5-.71 1.98-1.902 3.73-2.511 5.76-.203.635-.735.305-1.065-.076-2.689-3.248-5.225-6.572-7.229-10.302-.558-1.015-.305-1.548.913-2.004Zm14.864-74.727c.38-.28.862-.559 1.141-.305.355.279.051.761-.127 1.193-1.065 2.233-2.815 3.933-4.286 5.861-.33.381-.71.634-1.167.558-.71-.152-.304-.812-.406-1.218-.076-.33-.482-.685-.33-.761.406-1.497.508-2.461 2.004-3.146 1.066-.508 2.131-1.421 3.171-2.182ZM253.27 298.329c-.431-.254-.634-.482-.634-.964 0-.533.101-1.244-.761-.482.051-.305-1.319-.711.051-.965.482-.076.127-.406.127-.659-.076-1.777.456-3.451.938-5.101.254-.862.685-1.04 1.319-.152 1.015 1.472 2.359 2.639 3.45 4.085.786 1.066 1.496 2.614 3.044 3.147-2.03 2.03-5.276 2.41-7.534 1.091Zm15.803-6.065c-1.167.965-2.41.077-3.222-.558-1.471-1.116-3.145-1.928-4.566-3.045-1.318-1.015-2.282-2.512-4.033-3.019-.101-2.36-1.978-3.806-3.196-5.481-1.192-1.624-2.105-3.578-3.779-4.872-1.37-1.066-1.826-2.816-3.044-4.009a27.864 27.864 0 0 1-4.515-5.938c-1.801-3.197-4.819-4.871-7.406-6.901-2.511-1.98-5.048-4.01-7.635-5.938-3.272-2.461-8.421-8.399-9.74-10.657-1.903-3.299-3.881-6.75-3.957-10.683-.051-1.674-.33-3.375-.406-5.024-.076-1.598-.381-3.4-.381-5.075 0-3.831.254-7.663.964-11.418.152-.863.178-1.751.254-2.588.127-1.574.609-3.071 1.091-4.492.963-2.765 1.699-5.582 2.511-8.373.558-1.954 1.572-3.654 2.181-5.582 1.776-5.836 3.475-11.698 5.631-17.407.989-2.664 2.334-5.329 3.323-7.968 1.547-4.085 3.221-8.145 4.692-12.281 1.117-3.121 2.512-6.166 3.755-9.261 1.344-3.35 3.145-6.445 5.073-9.338 1.978-2.918 3.525-6.217 6.544-8.501 1.395-1.04 2.612-2.562 4.033-3.73.355-.304.609-.685 1.167-.761.558-.076 1.116-.786 1.648-.279.558.558-.025 1.243-.203 1.802a136.987 136.987 0 0 1-2.688 8.094c-.964 2.69-1.928 5.481-3.349 8.044-1.141 2.03-1.826 4.313-2.942 6.369-1.598 2.994-2.46 6.267-3.729 9.388-.481 1.243-.76 2.538.508 3.578.862.736 1.801.558 2.663.076.837-.482 1.116-1.522 1.319-2.284.989-3.755 2.917-7.104 4.49-10.606 1.775-3.958 3.348-7.993 4.997-12.002.938-2.233 1.572-4.618 2.561-6.826 1.091-2.385 2.08-4.796 3.805-6.902 1.395-1.7 2.613-3.552 4.185-5.125 1.598-1.548 3.678-2.791 4.871-4.466 1.04-1.446 2.257-.99 3.246-1.624 1.218-.787.558.66.99.761-1.066 1.573-1.421 3.476-2.207 5.177-.888 1.877-1.827 3.755-2.714 5.658-.964 2.055-2.106 4.035-3.146 6.064-.887 1.726-1.826 3.553-2.333 5.405-.507 1.929-1.649 3.476-2.359 5.253-1.573 3.907-3.45 7.663-4.946 11.596-.508 1.319-1.395 2.588-2.004 3.983-.33.787-.964 1.345-.025 2.107.152.126.177.304-.406.38-1.37.152-2.689 5.43-1.751 6.471 1.624 1.827 2.537 1.624 3.704-.838 1.775-3.755 3.5-7.561 5.225-11.342 2.334-5.05 4.667-10.124 6.696-15.301 1.827-4.618 4.135-9.008 6.57-13.321.761-1.345 2.131-2.208 3.069-3.375 1.015-1.294 2.029-2.563 3.145-3.781 2.943-3.146 6.747-5.049 10.425-7.155.939-.508 1.877.127 1.598 1.167-.456 1.7-1.116 3.375-1.699 5.024-.66 1.802-1.674 3.349-2.384 5.049-1.142 2.715-3.095 4.999-4.11 7.714-.963 2.665-3.17 4.517-4.235 7.156-.812 2.03-2.537 3.628-3.425 5.684-.761 1.801-2.13 3.171-2.486 5.303-.228 1.472-1.192 3.095-1.953 4.491-1.293 2.334-1.953 4.821-2.891 7.232-1.142 2.892-2.232 5.836-3.019 8.855-.406 1.548-.887 3.096-1.243 4.644-.38 1.725 1.015 1.928 1.522 2.867.888-.736 2.461-.33 2.892-1.827.507-1.751 1.623-3.222 2.613-4.694.507-.761 1.395-1.243 1.039-2.385-.076-.152.102-.558.66-.584.583-.025 1.141-1.548 1.091-2.385-.026-.152.025-.406.127-.431 2.435-1.066 2.815-3.629 4.185-5.481.634-.863 1.42-1.726 2.004-2.614 1.927-2.892 4.033-5.633 6.011-8.475.863-1.243 1.471-3.121 2.334-3.781 2.283-1.776 3.12-4.516 5.174-6.343 1.75-1.523 2.79-3.629 4.312-5.354 1.37-1.573 2.968-2.918 4.262-4.542 1.953-2.411 4.312-4.39 7.026-5.811 1.927-.989 3.855-2.08 6.037-2.36 1.065-.126 1.775 1.371 1.09 2.335-.558.736-.862 1.497-.786 2.309.076 1.091-1.979.837-1.243 2.182-1.877.837-2.156 2.969-3.374 4.364-2.105 2.386-3.931 5.025-5.707 7.689-1.699 2.512-3.855 4.669-5.605 7.13-1.877 2.563-3.856 5.075-5.758 7.638-1.649 2.182-3.678 4.085-4.693 6.699-.355.888-1.04 1.623-1.648 2.258-2.207 2.36-3.425 5.328-4.845 8.094-.888 1.675-1.624 3.654-2.182 5.583a3.199 3.199 0 0 0 .254 2.359c1.268 2.386.761 3.654-1.699 4.669-3.019 1.244-5.682 3.02-8.32 4.897-2.105 1.523-4.439 2.741-6.468 4.339-2.435 1.904-5.099 3.578-6.925 6.268-.71 1.091-1.699 2.106-2.486 3.197-1.801 2.436-3.373 4.973-4.692 7.739-1.319 2.715-1.776 5.557-2.587 8.323-.635 2.182 0 4.415-.279 6.623-.127.938 1.192.583 1.369 1.421.127.71.33.786 1.294.507 1.014-.279 1.953.051 1.699-1.446-.152-1.041.508-2.132.178-2.994-.812-1.98.127-3.705.507-5.481.431-2.081.812-4.212 2.308-5.862.33-.38-.076-.812.229-1.268 1.75-2.639 3.424-5.278 5.681-7.613 3.171-3.248 6.57-6.064 10.426-8.424 1.395-.837 2.764-1.725 3.754-3.096.253-.38 1.065-.355 1.623-.634 2.993-1.472 5.809-3.248 8.954-4.44 2.967-1.142 5.884-2.665 8.32-4.771 1.8-1.573 3.956-2.69 5.681-4.263 2.867-2.563 6.443-3.324 9.791-4.719.533-.229 1.091.127 1.345.634.202.457-.153.584-.584.888-.837.634-1.801.888-2.638 1.421-1.04.66-1.293 1.497-.659 2.639-1.116-.863-1.649-.964-2.714.355-2.08 2.614-2.816 6.801-1.091 9.617.558.914.761 1.472-.583 2.335a20.422 20.422 0 0 0-3.831 3.044c-1.674 1.751-3.627 3.223-5.428 4.822-1.851 1.674-3.424 3.679-5.047 5.607-3.298 3.959-5.809 8.45-8.143 12.992-.811 1.573-2.003 2.893-2.536 4.669-.837 2.689-.507 5.455-1.141 8.12-.812 3.552.659 6.394 2.384 9.337 1.649 2.791 3.323 5.608 4.971 8.399 2.004 3.426 3.983 6.851 6.012 10.277 1.42 2.385 2.866 4.77 4.363 7.13.659 1.04 1.978 1.472 2.993 1.801 1.522.533 1.877 2.005 2.968 2.817.558.431-.051 1.472-.381 1.751-3.145 2.512-5.327 5.963-8.472 8.5-3.323 2.715-6.468 5.684-9.816 8.399-3.627 2.944-7.432 5.735-10.907 8.906-1.497 1.371-3.399 2.411-5.022 3.73Zm7.863 23.725c-.355.305-1.218.508-1.471.305-.406-.33-.736-1.117-.635-1.599.153-.659.077-1.319.279-2.004.356.786 1.396.964 1.446 1.954.026.456.989.812.381 1.344Zm-.026-11.266c-1.547-2.512-3.348-4.897-4.946-7.384-.71-1.116-.38-1.421.279-1.979 2.131-1.675 4.236-3.425 6.443-4.999 2.663-1.903 5.124-4.034 7.66-6.064 3.627-2.867 7.128-5.861 10.603-8.906 2.663-2.36 5.174-4.898 7.736-7.334.228-.203.431-.355.609-.634 1.293-1.928 2.054-1.928 3.323-.101 1.369 1.979 2.739 4.009 4.261 5.836 1.395 1.725 2.384 3.704 3.906 5.278.279.304.533.862.863.913 2.967.507 1.116 2.69.761 3.426-1.091 2.207-2.385 4.339-3.704 6.47-1.623 2.664-3.551 5.151-5.529 7.46-1.345 1.522-3.12 2.943-4.82 4.288-2.638 2.03-5.428 3.908-7.99 6.09a146.021 146.021 0 0 1-9.106 7.13c-1.344-.736-1.877.66-2.688 1.041-1.928-2.081-3.12-4.644-5.124-6.699-.989-1.015-1.7-2.538-2.537-3.832Zm15.473 29.663c-1.192.634-2.486 1.142-3.602 1.903-1.344.939-2.181.304-2.79-.761-.279-.483-.685-.812-1.015-1.218-1.953-2.487-3.145-5.456-5.225-7.841-.127-.152-.101-.381-.228-.482-.66-.584-1.801-1.218-1.573-1.979.33-.99 1.751-.965 2.664-1.371 3.627-1.547 6.95-3.577 10.247-5.734 4.135-2.715 7.813-5.988 11.795-8.906 6.29-4.619 12.175-9.693 15.904-16.874 1.598-3.02 3.652-5.836 4.768-9.059.914-2.639 2.131-5.252 2.283-8.297 1.776 1.141 2.943 2.816 4.414 4.161 1.75 1.573 3.602 3.02 5.022 5.024.431.584 1.218 1.193 1.75 1.954.457.66.863 1.167.406 1.954-.279.457.051.786.254 1.142.076.203.431.406.431.456-1.04 1.624-.279 3.604-.939 5.202-.532 1.269-1.166 2.461-1.395 3.857-.203 1.193-1.42 1.776-1.978 2.791-1.065 1.929-2.334 3.857-3.754 5.379-1.7 1.827-3.424 3.705-5.276 5.405-4.87 4.491-9.588 9.11-15.042 12.89-2.029 1.421-3.88 3.071-5.91 4.492-3.525 2.461-7.482 3.958-11.211 5.912Zm78.657-4.542c-2.08 2.689-4.058 5.481-6.113 8.17-2.004 2.639-4.033 5.278-6.138 7.816-2.435 2.918-5.099 5.658-7.711 8.424-2.435 2.563-5.251 4.669-7.762 7.105-1.953 1.928-4.236 3.73-6.493 5.43-2.435 1.827-4.921 3.603-7.356 5.404-.508.381-.66.406-1.268 0-4.034-2.588-6.748-6.546-10.02-9.87-2.206-2.258-3.906-4.999-5.986-7.409-2.486-2.893-5.2-5.532-7.888-8.196-2.816-2.766-5.327-5.76-7.838-8.78-.051-.076-.076-.203-.203-.457 2.866-.964 5.327-2.562 7.787-4.085 5.58-3.451 10.628-7.637 15.676-11.773 3.449-2.817 6.696-5.811 9.867-8.856 3.475-3.324 6.924-6.851 9.182-11.241.609-1.167 1.065-2.385 1.319-3.679.127-.685.406-1.446.862-1.649.584-.254.812.71 1.243 1.014 3.171 2.259 5.733 5.228 8.65 7.765 2.054 1.802 3.956 3.933 5.91 5.912 3.018 3.045 5.605 6.496 8.852 9.363 1.547 1.371 3.044 2.868 4.261 4.542.482.685.99 0 1.471.559 1.269 1.471 1.269 2.435-.304 4.491Z" fill="#000"/><path d="M319.169 110.704c-2.182.279-4.109 1.37-6.037 2.36-2.714 1.421-5.073 3.4-7.026 5.811-1.294 1.624-2.892 2.969-4.262 4.542-1.522 1.725-2.561 3.831-4.312 5.354-2.054 1.827-2.891 4.567-5.174 6.343-.863.66-1.471 2.538-2.334 3.781-1.978 2.842-4.084 5.582-6.011 8.475-.584.888-1.37 1.751-2.004 2.614-1.37 1.852-1.75 4.415-4.185 5.48-.102.026-.153.28-.127.432.051.837-.507 2.36-1.091 2.385-.558.025-.735.431-.659.584.355 1.141-.533 1.624-1.04 2.385-.99 1.472-2.106 2.943-2.613 4.694-.431 1.497-2.004 1.091-2.892 1.827-.507-.939-1.902-1.142-1.521-2.867.355-1.548.837-3.096 1.242-4.644.787-3.019 1.877-5.963 3.019-8.855.938-2.411 1.598-4.898 2.891-7.232.761-1.396 1.725-3.02 1.954-4.491.355-2.132 1.724-3.502 2.485-5.304.888-2.055 2.613-3.653 3.425-5.683 1.065-2.639 3.272-4.492 4.236-7.156 1.014-2.715 2.967-4.999 4.109-7.714.71-1.7 1.725-3.248 2.384-5.049.583-1.649 1.243-3.324 1.7-5.024.279-1.041-.66-1.675-1.598-1.167-3.678 2.106-7.483 4.009-10.425 7.155-1.117 1.218-2.131 2.487-3.146 3.781-.938 1.167-2.308 2.03-3.069 3.375-2.435 4.313-4.743 8.703-6.569 13.321-2.03 5.176-4.363 10.251-6.697 15.301-1.725 3.781-3.45 7.587-5.225 11.342-1.167 2.461-2.08 2.664-3.703.837-.939-1.04.38-6.318 1.75-6.47.583-.076.558-.254.406-.381-.939-.761-.305-1.319.025-2.106.609-1.395 1.497-2.664 2.004-3.983 1.496-3.933 3.373-7.689 4.946-11.597.71-1.776 1.852-3.324 2.359-5.252.507-1.852 1.446-3.679 2.334-5.405 1.04-2.03 2.181-4.009 3.145-6.064.888-1.903 1.826-3.781 2.714-5.659.786-1.7 1.141-3.603 2.207-5.176-.432-.101.228-1.548-.99-.761-.989.634-2.206.177-3.246 1.624-1.192 1.674-3.272 2.918-4.87 4.466-1.573 1.573-2.791 3.425-4.186 5.125-1.724 2.106-2.714 4.517-3.804 6.902-.99 2.208-1.624 4.593-2.562 6.826-1.649 4.009-3.222 8.043-4.997 12.002-1.573 3.501-3.501 6.851-4.49 10.606-.203.761-.482 1.802-1.319 2.284-.862.482-1.801.66-2.663-.076-1.268-1.041-.989-2.335-.507-3.578 1.268-3.121 2.13-6.394 3.728-9.388 1.116-2.056 1.801-4.339 2.943-6.369 1.42-2.563 2.384-5.354 3.348-8.044a137.731 137.731 0 0 0 2.689-8.094c.177-.559.76-1.244.202-1.802-.532-.508-1.09.203-1.648.279-.558.076-.812.457-1.167.761-1.421 1.168-2.638 2.69-4.033 3.73-3.019 2.284-4.566 5.583-6.544 8.501-1.928 2.892-3.729 5.988-5.073 9.337-1.243 3.096-2.638 6.141-3.754 9.262-1.472 4.136-3.146 8.196-4.693 12.281-.989 2.639-2.334 5.303-3.323 7.968-2.156 5.709-3.855 11.57-5.631 17.406-.609 1.929-1.623 3.629-2.181 5.583-.812 2.791-1.547 5.608-2.511 8.373-.482 1.421-.964 2.918-1.091 4.492-.076.837-.101 1.725-.254 2.588-.71 3.755-.989 7.587-.964 11.418 0 1.675.305 3.476.381 5.075.076 1.649.355 3.349.406 5.024.076 3.933 2.054 7.384 3.957 10.683 1.319 2.258 6.468 8.196 9.74 10.657 2.587 1.928 5.124 3.958 7.635 5.937 2.587 2.03 5.605 3.705 7.406 6.902a27.864 27.864 0 0 0 4.515 5.938c1.218 1.192 1.674 2.943 3.044 4.009 1.674 1.294 2.587 3.248 3.78 4.872 1.217 1.675 3.094 3.121 3.196 5.481 1.75.507 2.714 2.004 4.033 3.019 1.42 1.117 3.094 1.929 4.565 3.045.812.634 2.055 1.523 3.222.558 1.623-1.319 3.525-2.359 5.022-3.73 3.475-3.171 7.28-5.963 10.907-8.906 3.348-2.715 6.493-5.684 9.816-8.399 3.146-2.537 5.327-5.988 8.472-8.5.33-.279.939-1.32.381-1.751-1.091-.812-1.446-2.284-2.968-2.817-1.015-.33-2.334-.761-2.993-1.801a299.095 299.095 0 0 1-4.363-7.13c-2.029-3.426-4.008-6.851-6.011-10.277-1.649-2.791-3.323-5.608-4.972-8.399-1.725-2.943-3.196-5.785-2.384-9.338.634-2.664.304-5.43 1.141-8.119.533-1.777 1.725-3.096 2.537-4.669 2.333-4.542 4.844-9.033 8.142-12.992 1.623-1.928 3.196-3.933 5.047-5.608 1.801-1.598 3.754-3.07 5.429-4.821a20.39 20.39 0 0 1 3.83-3.045c1.344-.862 1.141-1.421.583-2.334-1.725-2.817-.989-7.003 1.091-9.617 1.065-1.319 1.598-1.218 2.714-.355-.634-1.142-.381-1.979.659-2.639.837-.533 1.801-.787 2.638-1.421.432-.304.787-.431.584-.888-.254-.508-.812-.863-1.345-.634-3.348 1.395-6.924 2.156-9.791 4.719-1.724 1.573-3.88 2.69-5.681 4.263-2.435 2.106-5.352 3.629-8.32 4.77-3.145 1.193-5.961 2.969-8.954 4.441-.558.279-1.37.254-1.623.634-.99 1.37-2.359 2.259-3.754 3.096-3.856 2.36-7.255 5.176-10.425 8.424-2.258 2.335-3.932 4.974-5.682 7.612-.305.457.101.889-.228 1.269-1.497 1.649-1.877 3.781-2.309 5.862-.38 1.776-1.319 3.501-.507 5.48.33.863-.33 1.954-.178 2.995.254 1.497-.684 1.167-1.699 1.446-.964.279-1.167.203-1.294-.508-.177-.837-1.496-.482-1.369-1.42.279-2.208-.355-4.441.279-6.623.811-2.766 1.268-5.608 2.587-8.323 1.319-2.766 2.892-5.303 4.692-7.739.787-1.091 1.776-2.106 2.486-3.197 1.827-2.69 4.49-4.365 6.925-6.268 2.029-1.598 4.363-2.816 6.468-4.339 2.638-1.877 5.301-3.654 8.32-4.897 2.46-1.015 2.967-2.284 1.699-4.669a3.196 3.196 0 0 1-.253-2.36c.558-1.928 1.293-3.907 2.181-5.582 1.42-2.766 2.638-5.735 4.845-8.094.608-.635 1.293-1.371 1.648-2.259 1.015-2.613 3.044-4.516 4.693-6.698 1.902-2.563 3.881-5.075 5.758-7.638 1.75-2.461 3.906-4.618 5.605-7.13 1.776-2.665 3.602-5.303 5.708-7.689 1.217-1.395 1.496-3.527 3.373-4.364-.735-1.345 1.319-1.091 1.243-2.182-.076-.812.228-1.573.786-2.309.685-.965-.025-2.462-1.09-2.335Zm-61.84 69.805c-1.04.254-2.537.279-3.196-.482-1.142-1.294-2.79-1.573-4.008-2.588-2.029-1.7-4.667-2.106-7.051-2.817-2.08-.634-4.338-1.167-6.595-1.37-.736-.076-1.979.127-1.903-1.32.051-1.091.203-2.106 1.446-2.486.381-.127.482-.203.71.279.33.634.609.583.888-.203.355-.964.786-.178 1.091-.127 1.851.381 3.728.076 5.58.787 3.297 1.319 6.671 2.334 9.74 4.212 1.446.888 2.765 1.954 4.236 2.765.584.305.051.787.051 1.193.456 1.091-.254 1.979-.989 2.157Z" fill="#4E3413"/><path d="M193.205 170.236c-.177-5.734-1.192-11.19-4.87-15.808-1.598-2.03-4.007-3.248-6.468-2.943-4.845.634-6.214 2.41-7.178 7.383-.533 2.868-.609 5.786-1.015 8.628-.862 5.912-1.623 11.824-2.942 17.66-.609 2.563-1.116 5.177-2.131 7.587-1.217 2.893-1.978 5.912-2.967 8.805-.914-1.649-.888-3.705-.964-5.405-.178-5.658-.508-11.266-.812-16.899-.076-1.167-.837-2.588-.634-3.096.888-2.486.051-4.872-.178-7.181-.685-7.028-1.623-14.006-3.323-20.883-1.724-7.003-3.196-14.133-5.58-20.933-1.851-5.278-4.185-10.378-6.95-15.326-3.247-5.887-7.711-10.125-13.19-13.601-1.648-1.04-3.348-1.066-5.073-.203-3.069 1.522-5.2 5.938-4.464 9.211.178.888.406 1.852-.558 2.613-.989-1.421-2.359-2.309-3.729-3.121-1.927-1.167-3.906-.964-6.037-.152-2.688 1.066-2.815 3.603-3.373 5.709-.837 3.147-.457 6.369.203 9.541a409.52 409.52 0 0 0 1.344 5.912c-1.877-1.192-3.779-1.725-5.606-2.157-3.069-.71-5.986.356-6.873 3.198-.482 1.573-.533 3.273-.33 4.948.279 2.309.532 4.618 1.192 6.851.583 2.055 1.42 4.009 1.928 6.115.913 3.704 2.156 7.333 3.399 10.987.989 2.969 1.851 5.988 2.663 8.982.685 2.639.178 5.557.862 8.298.026.152-.228.406-.38.583-.152.153-.355.102-.457-.076-.786-1.471-2.156-2.791-2.562-4.187-.634-2.232-1.826-4.009-3.043-5.81-1.598-2.385-2.41-5.405-5.327-6.801-1.015-3.552-4.287-5.176-6.722-7.383-2.029-1.827-4.54-3.908-7.863-2.563-2.055-1.497-2.74.457-3.399 1.573-1.573 2.639-1.395 5.532-.558 8.373 1.167 3.933 3.45 7.334 5.403 10.886.558.99 1.902 1.852 2.03 2.487.38 1.852 1.521 3.146 2.383 4.592 3.602 5.938 7.23 11.901 9.081 18.625 1.243 4.542 1.852 9.262 2.131 14.007.355 5.684.279 11.342.127 17.001-.102 4.415-.837 8.83-1.472 13.22-.126.888-.05 2.334-1.877 2.283-4.464-.152-9.943 2.69-11.566 6.648-.736 1.726-2.004 3.274-3.221 4.771-4.845 6.039-9.944 11.849-15.194 17.584-4.439 4.846-8.903 9.693-13.291 14.59-5.048 5.633-9.893 11.419-14.712 17.229a204.59 204.59 0 0 1-3.07 3.578c-.532.609-1.166.609-1.547.102-1.648-2.157-4.236-3.096-6.366-4.466-3.957-2.588-8.421-4.39-13.292-4.568-4.007-.152-7.71.736-10.83 3.527-1.193 1.066-3.196 1.548-3.374 3.35-.203 2.157-.609 4.364-.583 6.521.076 4.136 1.877 7.841 3.5 11.571 2.181 4.998 6.214 8.576 9.69 12.535 2.714 3.07 5.63 6.013 8.42 9.007 4.313 4.644 8.828 9.034 13.495 13.271 4.236 3.832 8.852 7.232 13.164 10.987 4.211 3.654 8.32 7.435 12.683 10.886 3.754 2.969 7.635 5.785 11.642 8.348 3.095 1.979 6.393 3.628 9.538 5.506 4.007 2.385 8.117 4.542 12.58 5.963 3.07.99 6.266 1.193 9.437 1.269 3.043.101 6.037-.761 8.903-1.929 3.145-1.294 5.884-2.943 7.482-6.267 1.066-2.258.711-4.314.482-6.521-.405-3.68-1.623-7.054-4.033-9.846-2.536-2.968-5.326-5.683-8.269-8.272-.659-.583-1.471-1.395-.532-2.232 1.877-1.701 3.551-3.502 5.022-5.634 2.359-3.476 5.58-6.318 7.99-9.819 1.243-1.827 2.613-3.604 4.008-5.329 1.319-1.624 2.511-3.375 3.576-5.1 2.689-4.339 5.631-8.501 8.371-12.814.558-.914.405-2.259 1.116-2.766 1.623-1.193 1.902-3.121 2.891-4.618 3.019-4.567 3.602-9.845 3.602-15.149 0-2.232-.076-4.618-1.598-6.673-.33-.431-.862-1.928.076-2.969 1.319-1.471 2.435-3.121 3.754-4.593 2.537-2.816 5.2-5.506 7.686-8.373 1.141-1.294 2.232-2.715 3.373-3.882 2.131-2.157 3.754-4.669 5.758-6.902 2.004-2.208 3.729-4.669 5.504-7.08 2.791-3.755 5.073-7.815 7.788-11.621 4.083-5.785 6.975-12.205 9.359-18.802 1.497-4.212 2.461-8.602 3.653-12.916 1.116-4.009 1.496-8.12 2.207-12.179.456-2.512.583-5.151.837-7.74.558-6.064.532-12.154.634-18.218.051-3.832-.457-7.663-.584-11.495Zm-37.591-2.69c-.837.609-1.369 1.371-2.739 1.168-1.015-.153-2.663-.432-3.374 1.116-.025.076-.203.102-.304.152-.482-1.421-1.776-.659-2.663-.964-1.37-.457-1.37-1.573-1.319-2.588.05-1.116 1.369-.888 1.902-.939 3.754-.254 7.331-.812 10.248-3.933.735 4.136 1.268 3.756-1.751 5.988Zm-25.973-63.993c.253-1.244.913-1.65 2.232-1.092 3.931 1.624 6.823 4.441 9.182 7.816 3.5 5.049 6.29 10.479 8.193 16.315 1.192 3.578 2.004 7.308 3.069 10.937 1.623 5.531 2.765 11.164 4.109 16.772.076.355.076.711.101 1.04-.152.483.356 1.421-.862 1.015-.38-.101-.533.406-.685.711-1.319 2.512-3.627 3.527-6.214 3.882-3.627.508-3.602.432-4.262-3.222-.558-2.995-.989-6.039-1.826-8.983-.786-2.639-.837-5.455-1.725-8.043-.989-2.817-1.877-5.659-3.196-8.323-1.826-3.705-3.399-7.536-5.149-11.292-1.674-3.654-3.145-7.561-3.551-11.723-.177-1.979.178-3.882.584-5.81Zm7.812 212.281c-.507 1.674-1.623 3.045-2.537 4.516-2.561 4.162-4.844 8.551-7.761 12.459-3.12 4.187-5.834 8.678-9.03 12.814-1.75 2.284-3.425 4.644-5.124 6.927-1.395 1.878-3.323 3.578-4.997 5.329-1.116 1.167-2.054 2.512-3.348 3.527-.609.457-.837 1.142-1.902.939-.609-.152-1.649.761-1.573 1.446.254 1.878-1.091 2.842-2.03 3.933-2.08 2.36-4.438 4.466-6.467 6.877-2.968 3.527-6.392 6.622-9.512 9.997-.406.431-.863.913-1.04 1.472-.229.786-.584.888-1.243.583-.66.584-.964-.076-1.344-.38-2.486-1.954-5.15-3.603-7.864-5.253-2.46-1.522-4.794-3.476-7.076-5.379-3.4-2.867-6.722-5.836-10.172-8.678-.736-.609-2.511-.939-2.511-1.37.025-1.472-1.116-1.65-1.826-2.259-3.146-2.588-6.468-4.948-9.461-7.688a253.213 253.213 0 0 1-12.1-11.824c-2.74-2.842-5.377-5.811-8.243-8.552-1.167-1.116-2.004-2.537-3.323-3.501-.634-.457-.558-.914.05-1.396 3.222-2.537 5.961-5.582 9.513-7.84 2.46-1.548 4.59-3.807 6.772-5.837 2.942-2.74 5.606-5.709 8.269-8.678.178-.177.38-.329.482-.532 1.7-3.02 3.83-5.735 5.96-8.45 1.421-1.827 3.12-3.349 4.237-5.532.532-1.015 2.029-2.08 3.12-3.07 2.562-2.309 4.54-5.151 6.95-7.587 2.79-2.791 5.377-5.734 8.04-8.652 2.207-2.411 4.059-5.151 6.29-7.46 2.588-2.665 4.795-5.608 7.154-8.425 1.395-1.649 2.714-3.375 3.88-5.201.787-1.193 1.294-.914 2.055-.127 2.993 3.019 5.834 6.191 9.03 8.957 2.258 2.004 4.109 4.364 6.418 6.293 2.359 1.953 4.033 4.516 5.96 6.851 4.059 4.922 7.61 10.251 11.212 15.529 1.851 2.664 3.5 5.481 5.707 7.916.812.889 1.395 2.183 2.054 3.299.888 1.472 2.08 2.741 3.12 4.009 1.319 1.573 2.232 3.451 3.704 4.897 1.522 1.548 1.014 3.375.507 5.101Zm51.288-120.883c-.431 8.627-1.649 17.178-3.551 25.602a85.21 85.21 0 0 1-5.935 17.559c-2.131 4.568-4.794 8.881-7.661 13.043-.862 1.243-1.496 2.689-2.232 4.009-.837 1.446-2.435 2.461-2.993 4.11-.938 2.766-3.5 4.213-5.073 6.471-1.674 2.334-3.678 4.44-5.453 6.724-3.044 3.882-6.57 7.282-9.766 10.987-1.674 1.903-3.323 3.882-5.022 5.735-2.638 2.842-4.794 6.039-7.534 8.881-4.515-5.583-8.091-11.723-12.302-17.458-2.764-3.781-5.352-7.764-8.446-11.291-2.689-3.071-5.504-6.09-8.548-8.856-1.497-1.345-2.892-2.842-4.338-4.237-.355-.33-.507-.584-.304-1.092 2.207-5.303 2.942-10.961 3.779-16.594 1.091-7.283 1.725-14.616 1.624-22-.051-5.608-.102-11.241-1.192-16.798-.685-3.45-1.37-6.927-2.486-10.251-1.116-3.248-2.765-6.267-4.388-9.261-2.334-4.289-5.302-8.171-7.737-12.383-1.953-3.426-3.88-6.851-5.403-10.505-.279-.66-.532-1.37-.608-2.081-.102-.786-.584-1.725.304-2.309.964-.659 1.953-.152 2.689.406 5.96 4.618 10.957 10.023 14.407 16.798 1.725 3.375 3.754 6.597 5.53 9.921.38.736 1.014 1.091 1.547 1.371.609.329.989.583 1.192 1.268.228.838.863 1.32 1.801 1.142.837-.152 1.623-.051 2.029-1.218 1.091-3.121 1.192-6.267 1.015-9.49-.431-8.043-2.892-15.63-5.403-23.217-1.674-5.1-3.373-10.201-4.388-15.504-.101-.533-.076-1.091-.025-1.624.05-.989-.203-2.334.761-2.791 1.014-.482 2.308.101 3.196.736 1.877 1.319 3.525 2.943 4.515 5.1.101.228.228.533.405.584 3.222.812 4.084 3.603 4.972 6.191 1.573 4.567 3.602 9.008 4.642 13.753 1.217 5.608 1.572 11.266.964 17.001-.33 3.019-.761 5.988-1.522 8.931-.355 1.472.71 3.35 1.851 3.223 1.269-.127 2.486-.761 2.791-2.309a74.64 74.64 0 0 0 1.572-14.058c.076-4.059-.051-8.069-.888-12.002a75.431 75.431 0 0 0-4.743-14.717c-1.446-3.349-2.46-6.876-3.729-10.302-1.572-4.313-3.145-8.627-3.576-13.22-.203-2.055-.457-4.136.051-6.216.456-1.827 1.598-2.309 3.272-1.523 1.42.685 2.308 1.853 3.323 2.918 1.217 1.294 2.536 2.487 4.109 3.274 1.42.71 1.446 2.182 1.826 3.298 1.218 3.502 3.12 6.699 4.49 10.125 1.395 3.501 3.145 6.851 4.16 10.555.811 3.02 1.902 6.014 2.409 9.033.736 4.416 1.497 8.881 1.547 13.398.051 3.349.279 6.674.178 10.048-.051 1.7-.304 3.375-.304 5.05 0 1.218.659 2.41 2.105 2.436 1.167 0 2.232-.381 2.46-1.903.279-1.827.66-3.604.406-5.456-.177-1.192.355-1.294 1.37-1.04 3.754.964 7.432 1.192 10.932-1.015 1.04-.66 1.471-.102 1.497.989.076 4.847.406 9.693.71 14.515.203 3.095.38 6.267.736 9.388.304 2.461.228 4.948 1.09 7.333.203.508.178 1.117.99.99-.305.939 1.8 1.167.634 2.563-.711.837-.584 2.233.126 3.222.559.736 1.548.99 2.486.761.736-.177 1.446-.431 1.674-1.37.964-4.187 2.993-7.967 4.312-12.027 1.269-3.883 2.613-7.739 3.501-11.698.583-2.512 1.141-5.049 1.471-7.612.33-2.664.71-5.354 1.192-7.993.558-3.02.634-6.141 1.015-9.211.152-1.218.558-2.461.938-3.654.634-2.03 2.258-2.41 4.109-1.345 2.791 1.599 3.551 4.289 3.957 7.08.558 3.933.787 7.891 1.015 11.875.355 6.42.178 12.814-.127 19.234ZM75.588 52.73c.634-2.995.938-5.583 1.724-8.12.254-.787.685-1.396 1.116-2.005.102-.152.761-1.548 1.091 0 0 .102.304.178.482.178 2.004-.076 2.511.279 2.765 2.309.406 3.298.685 6.597 1.09 9.896.127.99.356 1.953.635 2.892.304.914.913.533 1.395.153.786-.61 1.395-1.37 2.435-1.7.355-.102.431-.94 1.065-.28.152.153.38.127.38-.279.026-1.903 1.193-2.436 2.867-2.258.127 0 .33.076.33.05.456-1.04 1.192-1.116 1.8-.304.685.888 1.243 1.98.381 3.121-1.725 2.36-3.45 4.72-5.682 6.648-2.029 1.726-2.13 3.299-.076 4.974 2.587 2.131 5.25 4.187 7.838 6.293 2.283 1.852 2.13 4.44-.28 5.379-1.166.457-2.333-.102-3.373-.38-2.282-.61-4.464-1.625-6.696-2.411-.583-.203-.406-.94-1.167-1.218.178 1.294.913 2.157 1.446 3.095.38.71.99 1.218.71 2.259-.203.786.99 1.04 1.42 1.75.888 1.447 1.675 2.868 1.903 4.542.203 1.447.228 3.02-1.37 3.63-1.395.532-2.587-.204-3.55-1.397-2.436-2.968-5.15-5.709-7.078-9.058-.152-.28-.558-.558-.862-.558-.507 0-.66.583-.71.913-.61 4.01-3.146 6.851-5.657 9.744-.989 1.116-3.45 1.472-4.997.761-1.547-.71-1.902-2.005-1.75-3.578.305-2.892 1.776-5.328 3.095-7.815.532-.99.862-2.157 1.851-2.842.33-.228.508-.533.406-.939-.152-.609-.66-.355-1.065-.38-3.602-.381-7.255-.229-10.831-1.066-2.359-.558-3.703-1.573-3.678-3.096.025-1.395 2.283-2.309 4.236-2.309 2.359 0 4.718.026 7.051 0 .406 0 1.066.254 1.243-.406.153-.558-.38-.837-.735-1.142-2.993-2.613-6.113-5.05-9.005-7.764-1.192-1.117-1.42-2.208-.913-3.502.482-1.192 1.7-1.497 2.866-1.42 2.816.202 5.276 1.547 7.711 2.841.634.33 1.294 1.066 1.903.685.482-.304.127-1.192 0-1.852-.533-2.563-1.269-5.151-1.395-7.74-.153-3.146-1.7-5.937-1.75-9.109 0-1.344.05-2.765-.432-4.161-.38-1.066.152-2.284 1.395-2.715 1.066-.355 1.75-.228 2.588 1.04 1.319 2.005 2.003 4.01 2.13 6.344.05.837.71 1.624.99 2.487.862 2.588 1.395 5.277 1.851 7.967.102.61.482.939.837 1.827l.026.025Zm10.754 18.7c-1.344-.99-2.333-2.106-3.246-3.476-.71-1.091.66-1.294.279-2.334-.508-1.37-.203-2.107-1.598-3.07-.61-.432-.812-.99-1.066-1.574-.431-1.015-.811-2.055-1.192-3.07-.152 0-.304.05-.457.05.178 2.284-1.75 4.263-.786 6.7.228.583-.228 1.192-.609 1.268-1.395.33-2.333 1.624-3.83 1.75-.355.026-.786.102-.684.61.278 1.268-1.243 3.298 1.521 3.552.33.026.863.533.888.838.127 1.7 1.37 1.344 2.385 1.395.228 0 .532 0 .71.127 1.319 1.142 1.37.102 1.522-.863.228-1.42.811-2.207 2.536-1.928 1.116.177 2.359.38 3.602 0l.025.025ZM361.249 99.797c-.203 2.918.33 5.709.787 8.475.406 2.309.152 4.618.507 6.927.254 1.599-.913 2.487-2.283 2.791-1.014.229-1.37-.837-1.877-1.548-1.496-2.182-1.471-4.871-2.46-7.257-.939-2.258-1.446-4.668-2.182-7.003-.253-.812-.761-.939-1.471-.33-1.775 1.523-3.957 2.157-6.189 2.715-1.75.432-3.551.381-5.327.482-.684.051-1.471-.126-1.902-.837-.228-.355-.786-.812.203-.964.228-.026.685.152.659-.305 0-.253-.228-.685-.405-.736-2.511-.583-.609-1.7-.153-2.283 1.142-1.421 3.095-1.802 4.465-3.147-.685-.532-1.37-1.09-2.08-1.598-.837-.584-1.243-1.447-1.015-2.36.254-1.015.634-2.132 2.004-2.335.583-.101 1.167-.304 1.75-.482 1.522-.456 1.776-1.37 1.421-2.892-.964-4.11-2.867-8.044-2.588-12.383.102-1.548-.431-3.425 1.827-4.288.634-.254 1.09-.355 1.623-.178.558.178 1.141.508.102.94 0 0-.001.151.025.177 3.526 1.624 2.841 5.658 4.591 8.145 3.374-2.258 5.479-5.963 9.106-7.993 1.978-1.117 4.464-1.117 5.352.28.989 1.547.482 3.323.127 5.023-.584 2.918-2.182 5.481-2.942 8.45 1.648-.355 3.272-.558 4.743-1.091 1.725-.61 3.5-.28 5.25-.533 2.055-.28 3.983 1.066 4.186 2.36.253 1.573-1.015 3.374-2.968 4.186a94.348 94.348 0 0 1-9.005 3.121c-.406.127-.989.254-1.065.736-.051.33.355.559.685.761a25.357 25.357 0 0 1 7.026 7.207c.685 1.04.38 2.182-.381 2.994-1.065 1.116-2.409 1.04-3.601.228-1.649-1.116-3.298-2.207-4.642-3.78-.508-.584-1.75-.584-1.928-1.777l.025.102Zm-.71-21.873c-.304.254-.507.482-.735.635-.254.127-.558.177-.863.253-.71.153-1.522 1.066-1.547 1.168-.457 2.182-1.953 3.577-3.424 4.998-.153.153-.229.178-.254.482 0 1.7-.558 2.107-2.46 2.183-.558.025-1.446.583-1.218.888.685.913.304 1.725-.051 2.41-.862 1.599-.938 2.766 1.218 3.172.127 0 .304.28.304.431-.177 2.106.939 2.411 2.664 2.005.253-.05.684 0 .837.203.887.964 1.395.025 1.572-.457.482-1.345 1.218-2.613 1.167-4.136 0-.583 0-1.116-.558-1.32-1.395-.43-.938-1.75-.634-2.207 1.167-1.801 1.243-4.009 2.41-5.734.482-.71.253-2.005 1.598-2.03.228 0 .228-.33.126-.38-1.293-.762.279-1.523-.126-2.538l-.026-.026ZM187.905 74.116c-.482-.152-.964 1.421-1.193.076-.304-1.7-1.598-2.588-2.485-3.806-3.323-4.542-5.327-9.718-7.585-14.793-1.471-3.299-3.272-6.445-4.235-9.947-.102-.38-.863-.583-.914-1.116-.025-.305-.811-1.117.457-.964.355.05.431-.736.101-.812-.431-.127-.456-.99-1.116-.533-.355.254-.431.228-.608-.305-.609-1.725-1.193-3.45-1.7-5.201-.228-.787.558-.559.913-.736.381-.178 1.142.304.913-.812-.126-.685 0-1.04-.887-.888-.508.076-.66-.482-.711-.964-.076-.71.178-1.523-.405-2.132a.53.53 0 0 1-.127-.33c.05-.355.279-.939.507-.837 1.623.584 2.587-2.31 3.703-1.142 2.156 2.258 4.186 4.821 4.668 8.12.126.786.76.228.989.71.735 1.599 1.75 3.02 2.004 4.872.076.584.634 1.573 1.242 2.335 1.066 1.294 1.649 3.07 2.106 4.669.811 2.867 2.308 5.379 3.297 8.145 1.066 2.943 2.41 5.81 3.653 8.652a232.77 232.77 0 0 0 3.551 7.714c1.167 2.436 2.131 4.973 3.171 7.46.076.152.05.406.152.507 3.221 2.842 3.17 7.156 4.718 10.734.634 1.472.811 3.222 1.395 4.796.101.253 0 .609-.051.888-.38 1.395-.939 2.689-.964 4.212 0 .837-1.116 1.294-2.08 1.167-1.268-.178-2.486-1.015-2.587-2.055-.203-2.182-1.649-3.756-2.283-5.71-.812-2.511-1.852-4.998-2.866-7.46-1.116-2.74-2.384-5.43-3.424-8.17-.558-1.472-1.015-2.969-1.852-4.263-.66-1.04.888-1.193.456-2.03l.077-.05ZM231.71 83.504c-1.497-.228-1.04-1.167-1.167-1.98-.33-2.207.862-4.084 1.192-6.14.304-1.827.178-3.831.786-5.404.711-1.853.381-3.4.229-5.1 0-.28.076-.61.228-.838 1.674-2.385 1.091-4.999.913-7.612-.279-3.502.406-6.928 1.04-10.378.33-1.802 1.116-3.553 1.091-5.43 0-.813.228-1.523.558-2.233 1.319-2.69 1.319-5.735 2.13-8.552.609-2.106 1.345-4.161 2.791-5.861.684-.812 3.069-.28 3.88.888 1.218 1.75 1.548 3.806 1.725 5.861.127 1.777-.05 3.553-.101 5.304-.076 2.182-.584 4.39-.228 6.597.228 1.472-.761 2.74-1.015 4.187-.304 1.725-.888 3.375-1.091 5.176-.253 2.157-1.04 4.212-1.775 6.268-.787 2.258-2.664 4.516-2.613 6.495.076 2.665-1.217 5.05-.837 7.663.152 1.066-.38 2.056-1.547 2.386.101.609 1.268.025.888.939-1.345 3.298-1.345 6.901-2.461 10.276-.456 1.421-1.217 2.639-1.725 4.035-.482 1.319-2.206.888-3.373.279-2.283-1.218-1.142-3.121-1.471-4.72-.279-1.37.076-2.157 1.927-2.106h.026ZM208.095 75.566c.634-.025 1.04-.05 1.572-.076-.152-.228-.228-.38-.329-.457-.914-.558-1.598-1.142-.584-2.258.355-.38.533-.888-.456-.66-.482.127-.381-.507-.381-.812-.177-2.715-.761-5.455-1.446-7.993-.887-3.349-.507-6.85-1.674-10.124-.304-.812-.456-1.878.127-2.918.279-.507-.279-1.37-.38-2.106-.381-3.02.177-5.912.456-8.856.102-1.04 1.243-1.243 1.826-1.37.964-.178 1.903.457 2.562 1.345a10.555 10.555 0 0 1 1.903 4.745c.253 1.878 1.09 3.527 1.395 5.38.253 1.598.304 2.968-.431 4.516-.355.761-.153 2.309.228 2.969 1.268 2.258.71 4.82 1.598 7.13 1.344 3.476 1.04 7.308 2.207 10.91.659 2.056 1.293 4.517.101 7.055-1.141 2.461-.761 2.639-2.435 3.425-.203.102-.533.33-.558.229-.457-1.269-1.928-1.015-2.638-1.7-1.015-.99-1.192-2.462-1.496-3.882-.305-1.472-.051-3.122-1.218-4.492h.051ZM163.782 81.857c-.786.863.051 1.218.558 1.802 1.801 2.08 3.83 3.933 5.733 5.938 2.866 2.994 5.757 5.988 7.888 9.59.609 1.016 1.116 2.031 0 3.046-.938.863-2.029.837-3.12.38-1.902-.786-3.044-2.537-4.718-3.628-1.166-.761-2.105-2.106-3.12-2.715-1.674-.99-3.12-2.182-4.616-3.375-2.283-1.801-4.642-3.552-6.417-5.912-.482-.634-1.218-.736-1.801-1.066-1.979-1.192-3.095-3.222-4.591-4.796-1.776-1.877-3.957-3.882-3.831-7.054.051-1.623 1.117-2.334 2.131-2.968.71-.432 1.624.279 2.41.736 2.207 1.319 4.388 2.69 6.747 3.73 2.308 1.014 4.287 2.537 5.986 4.44.457.533.533 1.193.761 1.903v-.05ZM314.983 32.708c-.202 2.36.102 4.974-.405 7.359-.508 2.41.786 3.933 1.445 5.81.305.863 1.243 1.066 1.776.71 1.344-.938 2.384-.253 3.069.61.888 1.091.228 2.309-.456 3.35-.508.735-1.218 1.344-1.674 2.08-2.537 4.01-4.186 8.399-5.429 12.966a3.496 3.496 0 0 1-.456.99c-.634 1.015-1.395 1.827-2.74 1.472-1.293-.356-1.75-1.396-1.775-2.589-.076-2.639.177-5.303-.431-7.916-.279-1.142-.609-2.31-1.091-3.375-.888-1.878-2.511-2.817-4.515-3.096-1.04-.152-1.877-.457-2.283-1.65-.609-1.725.051-2.79 1.953-2.79 1.319 0 1.75-.457 1.674-1.827-.05-.761.634-.838.939-.787 2.79.508 3.272-1.75 3.957-3.45 1.141-2.843 1.522-5.913 1.953-8.933.203-1.37.964-2.309 2.46-2.36 1.243-.05 2.055 1.295 2.08 3.426h-.051Zm-7.533 15.605c3.095 1.624 3.83 4.212 4.54 7.08 1.015-1.447 1.218-2.867 2.106-3.933.304-.38.329-1.015-.229-1.244-1.902-.786-2.511-2.537-3.119-4.237-1.294.482-1.37 2.157-3.273 2.334h-.025ZM251.545 93.68c.507-1.168-.279-2.843.761-4.162.051-.076 0-.305.025-.33 1.7-.812.559-2.487 1.091-3.654.431-.99.051-2.36 1.471-2.842.102-.025.229-.203.203-.279-.558-2.537.837-4.694 1.243-7.029.482-2.918 1.421-5.734 2.74-8.17 1.42-2.639 2.206-5.735 4.641-7.815 1.167-1.015 2.968-.685 3.678.532 2.131 3.578.787 6.928-.456 10.277-1.04 2.791-1.725 5.71-3.146 8.374-.583 1.09-.532 2.436-.507 3.704.051 1.599-.228 2.867-1.699 4.01-1.446 1.141-2.232 3.07-2.689 4.82-.507 1.954-1.978 3.375-2.435 5.304-.355 1.497-2.029 1.7-2.79 1.192-1.142-.786-2.74-1.725-2.182-3.907l.051-.026Z" fill="#000"/><path d="M43.704 215.426c-.127-2.791-.253-5.583-1.674-8.095-.355-.609-.66-1.37-1.623-1.065-1.192.38-2.308-.127-2.866-.965-.685-.964-.508-2.283.38-3.197 1.928-2.004 1.826-4.592 2.181-7.054.432-2.892.305-5.81.33-8.703 0-.812.152-1.497.634-2.208.609-.837 1.395-1.243 2.283-1.116.863.127 1.497.812 1.725 1.7.38 1.345.025 2.766.203 4.06.406 3.172.177 6.496 1.775 9.464.305.559.432 1.066 1.117 1.244.811.228 1.319-.178 1.674-.761.355-.584.913-.939 1.37-1.421.76-.863 1.623-.863 2.358-.203.812.735 1.522 1.624.812 2.867-1.674 3.019-2.587 6.318-3.45 9.617a173.459 173.459 0 0 1-2.333 8.069c-.33 1.04-1.116 1.827-2.283 1.649-.939-.152-1.979-.152-2.13-1.751-.052-.558-.381-1.421-.457-2.182l-.026.051Zm3.095-8.805c.685-1.472 1.395-2.867-1.04-3.375-.508-.101-.939-.736-1.294-1.218-.279-.38-.583-.761-.99-.431-.557.457.128 1.091.305 1.167 1.598.812 2.03 2.512 3.019 3.857ZM128.144 23.773c-.913 1.548-2.46 1.498-3.703 1.777-1.167.253-1.548.558-1.548 1.827 0 2.36-1.268 2.994-3.322 2.055-.913-.431-.888-1.218-.812-1.827.228-1.827-.66-1.675-1.928-1.421-1.04.228-2.257.33-2.891-.736-.533-.888.025-1.827.456-2.715.33-.66.913-.457 1.421-.584 2.917-.685 3.246-1.09 2.764-4.11-.253-1.523.964-2.715.711-4.238-.026-.152.71-.862 1.293-.66.787.254 1.776.559 1.827 1.472.101 1.472.558 2.918.279 4.44-.229 1.295.101 2.158 1.775 2.005 1.116-.101 2.41-.482 3.221.838.127.203.787.05.432.609-.254.38-.457.076-.736-.051-.735-.33-1.573-.99-2.131.076-.228.457-.025 1.142-.025 1.7.685-.253 1.522.584 2.156-.253.127-.178.254-.432.812-.28l-.051.076ZM340.095 159.3c-1.04-.127-1.624-.71-2.283-1.142-1.091-.71-1.243-2.892-.102-3.273 1.04-.33 1.345-.913 1.548-1.725.203-.787 1.065-.66 1.42-1.218-.279-.66-1.75-.229-1.268-1.599.177-.507.101-1.243.609-1.421.71-.254.279.685.659.914.406.253.888.786 1.268.482 1.852-1.574 1.573.583 1.674 1.091.153.888.279.989 1.193.939 1.293-.102 2.359.532 2.485 2.03.102 1.319-.634 2.004-1.877 2.207-1.369.228-1.978.914-1.826 2.411.127 1.294-.304 2.512-1.573 3.248-.963.558-2.079.507-2.561-.406-.356-.66-1.573-2.03.634-2.538ZM278.94 6.878c-.279.888-.508 1.98-1.547 2.335-.888.279-1.827-.051-2.258-.99-.279-.609-.609-.71-1.243-.736-.938-.05-1.75-.533-2.029-1.497-.254-.888.101-1.573.888-2.131.608-.432.786-1.142.887-1.903.153-1.015.838-1.574 1.878-1.878 1.217-.355 1.471.583 1.851 1.243.964 1.675 1.04 3.654 1.573 5.557ZM258.318 180.108c.457 1.091-.254 1.979-.989 2.157-1.04.254-2.537.279-3.196-.482-1.142-1.294-2.79-1.573-4.008-2.588-2.029-1.7-4.667-2.106-7.051-2.817-2.08-.634-4.338-1.167-6.595-1.37-.736-.076-1.979.127-1.903-1.319.051-1.092.203-2.106 1.446-2.487.381-.127.482-.203.71.279.33.634.609.584.888-.203.355-.964.786-.178 1.091-.127 1.851.381 3.728.076 5.58.787 3.298 1.319 6.671 2.334 9.74 4.212 1.446.888 2.765 1.954 4.236 2.766.584.304.051.786.051 1.192Z" fill="#000"/></g></g><defs><linearGradient id="c" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="d" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="e" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="f" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="g" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><linearGradient id="h" x1="40.84" y1="42.371" x2="388.572" y2="297.259" gradientUnits="userSpaceOnUse"><stop stop-color="#9059FF"/><stop offset=".521" stop-color="#FF4AA2"/><stop offset="1" stop-color="#FFBD4F"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h388.656v400H0z"/></clipPath><clipPath id="b"><path fill="#fff" d="M0 0h388.644v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-rtamo-background-image.svg b/browser/components/newtab/data/content/assets/mr-rtamo-background-image.svg
new file mode 100644
index 0000000000..25a66c2a96
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-rtamo-background-image.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="400" height="550" fill="none"><g clip-path="url(#a)"><path fill="#fff" d="M0 0h400v550H0z"/><path fill="url(#b)" d="M0 0h400v550H0z"/><path fill="url(#c)" fill-rule="evenodd" d="M272.671 215.932a56.175 56.175 0 0 1 20.086 25.394 102.923 102.923 0 0 1 6.497 50.298c-.062.517-.12 1.034-.178 1.551-.087.775-.174 1.549-.274 2.324-8.841 51.21-55.389 87.146-107.17 82.735-51.78-4.41-91.58-47.701-91.632-99.669v-.516a95.098 95.098 0 0 1 1.64-13.809v-.219c.117-.969.801-5.373.995-6.252l.129-.671a84.495 84.495 0 0 1 13.485-30.329 88.718 88.718 0 0 1 9.352-11.212 72.249 72.249 0 0 1 9.791-8.383 18.712 18.712 0 0 1 3.332-1.782 54.875 54.875 0 0 0 3.462 25.084 74.104 74.104 0 0 1 24.103-18.626 46.31 46.31 0 0 0 .284 24.464 30.49 30.49 0 0 1 2.583 1.964 50.087 50.087 0 0 1 27.565-10.618 73.028 73.028 0 0 1 34.462-55.645h.077a.321.321 0 0 1 .194 0 .283.283 0 0 1 .232.284c.334 1.373.833 2.7 1.486 3.953.31.632.658 1.317 1.111 2.04.571.969 1.165 1.938 1.758 2.907l.592.968c6.306 9.941 13.179 17.733 19.878 25.328 9.963 11.294 19.542 22.154 26.3 38.998v-.168a103.795 103.795 0 0 0-10.14-30.393Zm-95.314 103.765c.135.064.267.129.399.196l-.399-.196Zm.399.196.19.096c.262.133.526.267.806.393l-.996-.489Z" clip-rule="evenodd"/><path fill="url(#d)" d="M292.757 241.316a56.175 56.175 0 0 0-20.086-25.394 103.795 103.795 0 0 1 10.14 30.393v.207a90.665 90.665 0 0 1-3.087 67.567c-15.135 31.483-47.797 50.697-82.668 48.632-47.269-1.323-87.258-35.343-96.139-81.789a43.096 43.096 0 0 1 .711-16.701A73.633 73.633 0 0 0 100 278.039v.516c.052 51.968 39.852 95.259 91.632 99.67 51.781 4.41 98.329-31.525 107.17-82.736.168-1.291.297-2.583.452-3.875a102.923 102.923 0 0 0-6.497-50.298Z"/><path fill="url(#e)" d="M292.757 241.316a56.175 56.175 0 0 0-20.086-25.394 103.795 103.795 0 0 1 10.14 30.393v.207a90.665 90.665 0 0 1-3.087 67.567c-15.135 31.483-47.797 50.697-82.668 48.632-47.269-1.323-87.258-35.343-96.139-81.789a43.096 43.096 0 0 1 .711-16.701A73.633 73.633 0 0 0 100 278.039v.516c.052 51.968 39.852 95.259 91.632 99.67 51.781 4.41 98.329-31.525 107.17-82.736.168-1.291.297-2.583.452-3.875a102.923 102.923 0 0 0-6.497-50.298Z"/><path fill="url(#f)" d="m244.104 253.103.632.465a54.394 54.394 0 0 0-9.3-12.129c-19.584-18.321-21.465-48.742-4.288-69.337a73.03 73.03 0 0 0-34.423 55.568c1.162-.078 2.325-.181 3.513-.181a50.518 50.518 0 0 1 43.866 25.614Z"/><path fill="url(#g)" d="M200.305 259.317a24.205 24.205 0 0 1-12.038 11.07c-28.417 0-33.093 17.231-33.093 17.231a42.266 42.266 0 0 0 23.586 32.77c.556.284 1.124.542 1.679.801.982.439 1.964.839 2.946 1.201a44.374 44.374 0 0 0 13.033 2.583c19.638 1.884 37.881-10.344 43.6-29.225 5.72-18.882-2.67-39.177-20.053-48.508a34.569 34.569 0 0 1 24.141 5.851 50.517 50.517 0 0 0-43.917-25.614c-1.188 0-2.351.104-3.513.181a50.084 50.084 0 0 0-27.564 10.618c1.537 1.292 3.255 3.022 6.884 6.6a157.767 157.767 0 0 0 24.309 14.441Z"/><path fill="url(#h)" d="M200.305 259.317a24.205 24.205 0 0 1-12.038 11.07c-28.417 0-33.093 17.231-33.093 17.231a42.266 42.266 0 0 0 23.586 32.77c.556.284 1.124.542 1.679.801.982.439 1.964.839 2.946 1.201a44.374 44.374 0 0 0 13.033 2.583c19.638 1.884 37.881-10.344 43.6-29.225 5.72-18.882-2.67-39.177-20.053-48.508a34.569 34.569 0 0 1 24.141 5.851 50.517 50.517 0 0 0-43.917-25.614c-1.188 0-2.351.104-3.513.181a50.084 50.084 0 0 0-27.564 10.618c1.537 1.292 3.255 3.022 6.884 6.6a157.767 157.767 0 0 0 24.309 14.441Z"/><path fill="url(#i)" d="m164.489 234.956 2.08 1.37a46.324 46.324 0 0 1-.285-24.465 74.1 74.1 0 0 0-24.102 18.626 49.388 49.388 0 0 1 22.307 4.469Z"/><path fill="url(#j)" d="M100.913 280.951c8.855 46.449 48.821 80.489 96.087 81.841 34.902 2.078 67.592-17.162 82.719-48.683a90.665 90.665 0 0 0 3.126-67.568v-.155.168a67.399 67.399 0 0 1-26.686 60.851l-.065.129c-35.921 29.257-70.305 17.657-77.268 12.917l-1.459-.723c-18.094-7.588-29.287-25.919-27.771-45.48a25.718 25.718 0 0 1-23.702-14.919 37.767 37.767 0 0 1 36.812-1.486 49.82 49.82 0 0 0 37.588 1.486 157.966 157.966 0 0 1-24.258-14.441c-3.629-3.578-5.347-5.309-6.884-6.601a30.882 30.882 0 0 0-2.584-1.963l-2.079-1.369a49.374 49.374 0 0 0-22.307-4.469 54.866 54.866 0 0 1-3.462-25.085 18.79 18.79 0 0 0-3.333 1.783 72.17 72.17 0 0 0-9.79 8.383 88.41 88.41 0 0 0-9.352 11.212 84.473 84.473 0 0 0-13.485 30.328 75.022 75.022 0 0 0-1.847 23.844Z"/><path fill="url(#k)" d="M235.433 241.43a54.418 54.418 0 0 1 9.3 12.128c.542.414 1.059.827 1.498 1.292a48.037 48.037 0 0 1 9.92 52.61 67.4 67.4 0 0 0 26.686-60.915c-11.328-28.224-30.523-39.655-46.204-64.378-.787-1.291-1.588-2.583-2.35-3.875a21.884 21.884 0 0 1-1.111-2.04 17.506 17.506 0 0 1-1.486-3.953.283.283 0 0 0-.232-.284.321.321 0 0 0-.194 0h-.077c-17.237 20.597-15.371 51.074 4.25 69.415Z"/><path fill="url(#l)" d="M246.226 254.776c-.439-.4-.956-.814-1.498-1.291l-.633-.465a34.567 34.567 0 0 0-24.142-5.852c17.295 9.372 25.613 29.614 19.906 48.439-5.707 18.824-23.866 31.039-43.453 29.23a44.35 44.35 0 0 1-13.033-2.584 46.696 46.696 0 0 1-2.945-1.201c-.555-.258-1.124-.517-1.679-.801 6.962 4.754 41.333 16.353 77.268-12.917l.064-.129a48.037 48.037 0 0 0-9.855-52.429Z"/><path fill="url(#m)" d="M155.166 287.63s4.624-17.231 33.092-17.231a24.205 24.205 0 0 0 12.039-11.069 49.82 49.82 0 0 1-37.588-1.486 37.769 37.769 0 0 0-36.813 1.486 25.719 25.719 0 0 0 23.703 14.919c-1.514 19.55 9.666 37.872 27.745 45.467.465.219.904.465 1.395.684a42.262 42.262 0 0 1-23.573-32.77Z"/><path fill="url(#n)" d="M292.757 241.326a56.175 56.175 0 0 0-20.086-25.394 103.795 103.795 0 0 1 10.14 30.393v.168c-11.302-28.172-30.497-39.603-46.178-64.326-.787-1.291-1.588-2.583-2.35-3.875a21.884 21.884 0 0 1-1.111-2.04 17.506 17.506 0 0 1-1.486-3.953.283.283 0 0 0-.232-.284.321.321 0 0 0-.194 0h-.077a73.028 73.028 0 0 0-34.462 55.645c1.162-.077 2.325-.181 3.513-.181a50.517 50.517 0 0 1 43.917 25.614 34.569 34.569 0 0 0-24.141-5.851c17.294 9.372 25.612 29.614 19.905 48.439-5.707 18.824-23.866 31.039-43.453 29.229a44.348 44.348 0 0 1-13.033-2.583 47.554 47.554 0 0 1-2.945-1.201c-.555-.258-1.123-.517-1.679-.801l-1.459-.723c.465.219.904.465 1.395.684a42.264 42.264 0 0 1-23.574-32.666s4.625-17.231 33.093-17.231a24.207 24.207 0 0 0 12.039-11.07 157.758 157.758 0 0 1-24.258-14.441c-3.63-3.578-5.348-5.309-6.885-6.6a30.49 30.49 0 0 0-2.583-1.964 46.31 46.31 0 0 1-.284-24.464 74.104 74.104 0 0 0-24.103 18.626 54.875 54.875 0 0 1-3.462-25.084 18.712 18.712 0 0 0-3.332 1.782 72.249 72.249 0 0 0-9.791 8.383 88.718 88.718 0 0 0-9.352 11.212 84.495 84.495 0 0 0-13.485 30.329l-.129.671c-.194.879-1.046 5.348-1.162 6.316A118.3 118.3 0 0 0 100 278.049v.516c.052 51.968 39.852 95.259 91.632 99.669 51.781 4.411 98.329-31.525 107.17-82.735.168-1.292.297-2.583.452-3.875a102.923 102.923 0 0 0-6.497-50.298Z"/></g><defs><radialGradient id="d" cx="0" cy="0" r="1" gradientTransform="matrix(208.722 0 0 215.61 271.832 145.358)" gradientUnits="userSpaceOnUse"><stop offset=".129" stop-color="#FFBD4F"/><stop offset=".186" stop-color="#FFAC31"/><stop offset=".247" stop-color="#FF9D17"/><stop offset=".283" stop-color="#FF980E"/><stop offset=".403" stop-color="#FF563B"/><stop offset=".467" stop-color="#FF3750"/><stop offset=".71" stop-color="#F5156C"/><stop offset=".782" stop-color="#EB0878"/><stop offset=".86" stop-color="#E50080"/></radialGradient><radialGradient id="e" cx="0" cy="0" r="1" gradientTransform="matrix(208.722 0 0 215.61 195.558 253.731)" gradientUnits="userSpaceOnUse"><stop offset=".3" stop-color="#960E18"/><stop offset=".351" stop-color="#B11927" stop-opacity=".74"/><stop offset=".435" stop-color="#DB293D" stop-opacity=".343"/><stop offset=".497" stop-color="#F5334B" stop-opacity=".094"/><stop offset=".53" stop-color="#FF3750" stop-opacity=".01"/></radialGradient><radialGradient id="f" cx="0" cy="0" r="1" gradientTransform="matrix(629.917 0 0 650.704 199.973 109.859)" gradientUnits="userSpaceOnUse"><stop offset=".132" stop-color="#FFF44F"/><stop offset=".252" stop-color="#FFDC3E"/><stop offset=".506" stop-color="#FF9D12"/><stop offset=".526" stop-color="#FF980E"/></radialGradient><radialGradient id="g" cx="0" cy="0" r="1" gradientTransform="matrix(223.5 0 0 230.876 138.896 398.985)" gradientUnits="userSpaceOnUse"><stop offset=".353" stop-color="#3A8EE6"/><stop offset=".472" stop-color="#5C79F0"/><stop offset=".669" stop-color="#9059FF"/><stop offset="1" stop-color="#C139E6"/></radialGradient><radialGradient id="h" cx="0" cy="0" r="1" gradientTransform="rotate(-12.809 1131.776 -761.948) scale(118.111 121.632)" gradientUnits="userSpaceOnUse"><stop offset=".206" stop-color="#9059FF" stop-opacity=".01"/><stop offset=".278" stop-color="#8C4FF3" stop-opacity=".064"/><stop offset=".747" stop-color="#7716A8" stop-opacity=".45"/><stop offset=".975" stop-color="#6E008B" stop-opacity=".6"/></radialGradient><radialGradient id="i" cx="0" cy="0" r="1" gradientTransform="matrix(586.335 0 0 605.684 516.102 -42.781)" gradientUnits="userSpaceOnUse"><stop stop-color="#FFE226"/><stop offset=".121" stop-color="#FFDB27"/><stop offset=".295" stop-color="#FFC82A"/><stop offset=".502" stop-color="#FFA930"/><stop offset=".732" stop-color="#FF7E37"/><stop offset=".792" stop-color="#FF7139"/></radialGradient><radialGradient id="j" cx="0" cy="0" r="1" gradientTransform="matrix(325.795 0 0 336.546 258.564 87.645)" gradientUnits="userSpaceOnUse"><stop offset=".113" stop-color="#FFF44F"/><stop offset=".456" stop-color="#FF980E"/><stop offset=".622" stop-color="#FF5634"/><stop offset=".716" stop-color="#FF3647"/><stop offset=".904" stop-color="#E31587"/></radialGradient><radialGradient id="k" cx="0" cy="0" r="1" gradientTransform="rotate(77.763 -58.163 151.983) scale(346.995 336.922)" gradientUnits="userSpaceOnUse"><stop stop-color="#FFF44F"/><stop offset=".06" stop-color="#FFE847"/><stop offset=".168" stop-color="#FFC830"/><stop offset=".304" stop-color="#FF980E"/><stop offset=".356" stop-color="#FF8B16"/><stop offset=".455" stop-color="#FF672A"/><stop offset=".57" stop-color="#FF3647"/><stop offset=".737" stop-color="#E31587"/></radialGradient><radialGradient id="l" cx="0" cy="0" r="1" gradientTransform="matrix(469.191 0 0 484.675 130.741 83.866)" gradientUnits="userSpaceOnUse"><stop offset=".137" stop-color="#FFF44F"/><stop offset=".48" stop-color="#FF980E"/><stop offset=".592" stop-color="#FF5634"/><stop offset=".655" stop-color="#FF3647"/><stop offset=".904" stop-color="#E31587"/></radialGradient><radialGradient id="m" cx="0" cy="0" r="1" gradientTransform="matrix(560.313 0 0 578.803 410.764 79.89)" gradientUnits="userSpaceOnUse"><stop offset=".094" stop-color="#FFF44F"/><stop offset=".231" stop-color="#FFE141"/><stop offset=".509" stop-color="#FFAF1E"/><stop offset=".626" stop-color="#FF980E"/></radialGradient><linearGradient id="b" x1="0" x2="368.013" y1="550" y2="282.354" gradientUnits="userSpaceOnUse"><stop stop-color="#0290EE"/><stop offset="1" stop-color="#9059FF"/></linearGradient><linearGradient id="c" x1="201.885" x2="30.656" y1="118.187" y2="273.001" gradientUnits="userSpaceOnUse"><stop offset=".048" stop-color="#FFF44F"/><stop offset=".111" stop-color="#FFE847"/><stop offset=".225" stop-color="#FFC830"/><stop offset=".368" stop-color="#FF980E"/><stop offset=".401" stop-color="#FF8B16"/><stop offset=".462" stop-color="#FF672A"/><stop offset=".534" stop-color="#FF3647"/><stop offset=".705" stop-color="#E31587"/></linearGradient><linearGradient id="n" x1="209.061" x2="63.186" y1="130.117" y2="266.808" gradientUnits="userSpaceOnUse"><stop offset=".167" stop-color="#FFF44F" stop-opacity=".8"/><stop offset=".266" stop-color="#FFF44F" stop-opacity=".634"/><stop offset=".489" stop-color="#FFF44F" stop-opacity=".217"/><stop offset=".6" stop-color="#FFF44F" stop-opacity=".01"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h400v550H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/mr-settodefault.svg b/browser/components/newtab/data/content/assets/mr-settodefault.svg
new file mode 100644
index 0000000000..a12306e87c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/mr-settodefault.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="258" height="400" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M239.284 83.868c-5.266-12.666-15.932-26.341-24.307-30.663 6.816 13.362 10.761 26.767 12.269 36.771 0 .02.007.069.023.202-13.7-34.148-36.931-47.918-55.902-77.9-.957-1.516-1.918-3.036-2.854-4.638a37.56 37.56 0 0 1-1.334-2.507 22.018 22.018 0 0 1-1.811-4.792.315.315 0 0 0-.275-.325.415.415 0 0 0-.228 0c-.017.006-.042.026-.06.033-.027.01-.061.035-.089.05.014-.018.042-.059.05-.068-30.436 17.825-40.761 50.8-41.71 67.297a60.625 60.625 0 0 0-33.346 12.85 36 36 0 0 0-3.139-2.37 56.132 56.132 0 0 1-.34-29.61c-12.446 5.668-22.127 14.626-29.165 22.536h-.056c-4.803-6.083-4.465-26.152-4.19-30.342-.058-.26-3.584 1.83-4.046 2.145a88.266 88.266 0 0 0-11.84 10.144c-4.143 4.2-7.927 8.739-11.315 13.568 0 .006-.003.014-.006.02 0-.007.004-.014.006-.02a102.261 102.261 0 0 0-16.258 36.706c-.058.263-.107.535-.163.8-.228 1.066-1.049 6.402-1.192 7.562-.012.089-.017.175-.027.264a115.488 115.488 0 0 0-1.966 16.717c0 .206-.013.411-.013.618.002 66.909 54.25 121.148 121.164 121.148 59.928 0 109.686-43.503 119.428-100.646.205-1.551.369-3.11.55-4.674 2.408-20.777-.267-42.614-7.858-60.876Zm-139.65 94.83c.566.271 1.098.567 1.68.827.024.016.057.035.082.05a61.355 61.355 0 0 1-1.763-.877Zm127.645-88.49-.016-.118.02.13-.004-.012Z" fill="url(#b)"/><path d="M239.283 83.859c-5.266-12.667-15.932-26.341-24.307-30.664 6.816 13.363 10.761 26.768 12.269 36.772 0-.03.005.024.018.114l.02.13c11.432 30.991 5.204 62.506-3.771 81.763-13.884 29.796-47.499 60.333-100.114 58.844-56.847-1.61-106.927-43.789-116.276-99.035-1.704-8.712 0-13.135.857-20.209-1.044 5.453-1.442 7.028-1.966 16.717 0 .207-.013.411-.013.619.001 66.906 54.249 121.145 121.163 121.145 59.928 0 109.686-43.503 119.428-100.646.205-1.551.369-3.11.55-4.674 2.408-20.777-.267-42.615-7.858-60.876Z" fill="url(#c)"/><path d="M239.283 83.859c-5.266-12.667-15.932-26.341-24.307-30.664 6.816 13.363 10.761 26.768 12.269 36.772 0-.03.005.024.018.114l.02.13c11.432 30.991 5.204 62.506-3.771 81.763-13.884 29.796-47.499 60.333-100.114 58.844-56.847-1.61-106.927-43.789-116.276-99.035-1.704-8.712 0-13.135.857-20.209-1.044 5.453-1.442 7.028-1.966 16.717 0 .207-.013.411-.013.619.001 66.906 54.249 121.145 121.163 121.145 59.928 0 109.686-43.503 119.428-100.646.205-1.551.369-3.11.55-4.674 2.408-20.777-.267-42.615-7.858-60.876Z" fill="url(#d)"/><path d="M180.403 98.1c.264.186.504.37.752.555a65.859 65.859 0 0 0-11.248-14.677c-37.663-37.66-9.876-81.655-5.189-83.89.013-.018.041-.059.05-.068-30.436 17.825-40.762 50.8-41.71 67.297 1.411-.098 2.819-.216 4.256-.216 22.713 0 42.495 12.488 53.089 31Z" fill="url(#e)"/><path d="M127.389 105.636c-.198 3.014-10.847 13.407-14.57 13.407-34.454 0-40.047 20.84-40.047 20.84 1.526 17.55 13.744 32.002 28.541 39.649.675.349 1.358.664 2.042.975a67.024 67.024 0 0 0 3.559 1.455 53.837 53.837 0 0 0 15.766 3.041c60.388 2.832 72.088-72.193 28.507-93.98 11.161-1.941 22.746 2.548 29.215 7.092-10.593-18.51-30.376-30.998-53.088-30.998-1.437 0-2.844.119-4.256.216a60.626 60.626 0 0 0-33.347 12.85c1.848 1.563 3.933 3.653 8.326 7.98 8.219 8.1 29.307 16.489 29.352 17.473Z" fill="url(#f)"/><path d="M127.389 105.636c-.198 3.014-10.847 13.407-14.57 13.407-34.454 0-40.047 20.84-40.047 20.84 1.526 17.55 13.744 32.002 28.541 39.649.675.349 1.358.664 2.042.975a67.024 67.024 0 0 0 3.559 1.455 53.837 53.837 0 0 0 15.766 3.041c60.388 2.832 72.088-72.193 28.507-93.98 11.161-1.941 22.746 2.548 29.215 7.092-10.593-18.51-30.376-30.998-53.088-30.998-1.437 0-2.844.119-4.256.216a60.626 60.626 0 0 0-33.347 12.85c1.848 1.563 3.933 3.653 8.326 7.98 8.219 8.1 29.307 16.489 29.352 17.473Z" fill="url(#g)"/><path d="M84.061 76.158c.844.544 1.681 1.099 2.512 1.664a56.134 56.134 0 0 1-.34-29.611c-12.447 5.667-22.128 14.626-29.166 22.536.582-.016 18.157-.333 26.994 5.41Z" fill="url(#h)"/><path d="M7.122 131.801c9.349 55.245 59.43 97.425 116.276 99.034 52.615 1.49 86.231-29.049 100.115-58.843 8.974-19.259 15.202-50.769 3.77-81.763l-.004-.013-.016-.117c-.012-.09-.02-.144-.018-.114 0 .02.008.068.024.201 4.297 28.062-9.978 55.248-32.292 73.63l-.067.158c-43.482 35.404-85.09 21.36-93.515 15.612a72.571 72.571 0 0 1-1.764-.879c-25.35-12.114-35.823-35.21-33.577-55.016-21.406 0-28.704-18.054-28.704-18.054s19.218-13.702 44.547-1.785c23.458 11.038 45.489 1.786 45.492 1.785-.045-.984-21.133-9.372-29.354-17.472-4.393-4.328-6.479-6.414-8.326-7.98a35.98 35.98 0 0 0-3.138-2.37 142.568 142.568 0 0 0-2.512-1.663c-8.837-5.743-26.412-5.427-26.994-5.412h-.056c-4.803-6.084-4.464-26.153-4.19-30.343-.058-.26-3.584 1.83-4.046 2.145a88.266 88.266 0 0 0-11.84 10.144 106.12 106.12 0 0 0-11.315 13.572c0 .006-.003.013-.005.019 0-.007.003-.013.005-.02a102.262 102.262 0 0 0-16.257 36.706c-.058.263-4.361 19.079-2.239 28.838Z" fill="url(#i)"/><path d="M169.908 83.986a65.889 65.889 0 0 1 11.248 14.677c.667.502 1.29 1.001 1.819 1.489 27.468 25.309 13.076 61.104 12.003 63.655 22.315-18.381 36.59-45.567 32.292-73.63-13.701-34.148-36.932-47.917-55.902-77.899-.958-1.516-1.919-3.036-2.854-4.638a36.657 36.657 0 0 1-1.334-2.507 22.073 22.073 0 0 1-1.812-4.792.314.314 0 0 0-.275-.325.411.411 0 0 0-.227 0c-.018.006-.043.026-.061.033-.027.01-.06.035-.089.05-4.684 2.233-32.471 46.229 5.192 83.887Z" fill="url(#j)"/><path d="M182.974 100.158a23.914 23.914 0 0 0-1.819-1.489c-.247-.185-.489-.37-.753-.554-6.469-4.545-18.054-9.033-29.215-7.092 43.581 21.787 31.881 96.812-28.508 93.98a53.837 53.837 0 0 1-15.765-3.041 67.024 67.024 0 0 1-3.559-1.455 46.942 46.942 0 0 1-2.042-.975c.024.016.057.035.082.05 8.425 5.747 50.033 19.792 93.515-15.612l.067-.158c1.073-2.548 15.465-38.345-12.003-63.654Z" fill="url(#k)"/><path d="M72.772 139.863s5.592-20.839 40.046-20.839c3.725 0 14.374-10.394 14.571-13.407.197-3.014-22.032 9.252-45.492-1.786-25.33-11.917-44.547 1.786-44.547 1.786s7.298 18.053 28.704 18.053c-2.245 19.807 8.227 42.904 33.577 55.016.567.271 1.099.567 1.681.827-14.796-7.648-27.014-22.1-28.54-39.65Z" fill="url(#l)"/><path d="M239.282 83.868c-5.266-12.666-15.932-26.341-24.307-30.663 6.816 13.362 10.761 26.767 12.269 36.771 0 .02.007.069.024.202-13.701-34.148-36.932-47.918-55.903-77.9-.957-1.516-1.918-3.036-2.854-4.638a37.56 37.56 0 0 1-1.334-2.507 22.018 22.018 0 0 1-1.811-4.792.315.315 0 0 0-.275-.325.415.415 0 0 0-.228 0c-.017.006-.042.026-.06.033-.027.01-.061.035-.089.05.014-.018.042-.059.05-.068-30.436 17.825-40.761 50.8-41.71 67.297 1.412-.097 2.819-.216 4.256-.216 22.714 0 42.497 12.488 53.088 30.998-6.469-4.545-18.054-9.033-29.214-7.092 43.58 21.787 31.881 96.812-28.508 93.98a53.843 53.843 0 0 1-15.766-3.041 67.37 67.37 0 0 1-3.559-1.455 45.756 45.756 0 0 1-2.042-.975l.083.05a72.263 72.263 0 0 1-1.765-.879c.567.271 1.099.567 1.681.827-14.797-7.647-27.015-22.099-28.541-39.649 0 0 5.593-20.84 40.046-20.84 3.725 0 14.374-10.393 14.571-13.407-.045-.984-21.133-9.372-29.354-17.472-4.393-4.328-6.479-6.415-8.326-7.98a35.949 35.949 0 0 0-3.138-2.37 56.133 56.133 0 0 1-.34-29.61C73.779 53.864 64.098 62.823 57.06 70.733h-.056c-4.803-6.084-4.464-26.153-4.19-30.343-.058-.26-3.584 1.83-4.045 2.146a88.26 88.26 0 0 0-11.841 10.143 106.109 106.109 0 0 0-11.311 13.57c0 .006-.004.014-.006.02 0-.007.004-.014.006-.02a102.261 102.261 0 0 0-16.258 36.706c-.058.263-.107.535-.163.8-.228 1.066-1.253 6.48-1.397 7.641-.01.089.01-.089 0 0A140.934 140.934 0 0 0 6.013 128.3c0 .207-.013.412-.013.619 0 66.906 54.248 121.145 121.162 121.145 59.928 0 109.686-43.503 119.428-100.646.205-1.551.369-3.11.55-4.674 2.408-20.777-.267-42.614-7.858-60.876Zm-12.02 6.222.02.13-.004-.012-.016-.118Z" fill="url(#m)"/><path d="m82.412 64.229 2.732 13.683L101 70.242l22.965-3.281 3.281-24.086-10.391-7.121-6.013 7.121L101 40.143l-8.746 7.122h-9.842V64.24v-.011ZM142.575 171.531l16.404 9.305H144.21l-10.94-6.024h-6.013l-4.378 3.28 4.378 3.83-2.183 5.475 5.464 4.378v6.573l13.672 4.927 1.635 5.475 32.807-3.28 28.442-10.951c9.584-5.42 30.635-17.423 39.918-22.999l6.561-14.781v-17.524l-4.378-8.207-18.05 23.548-54.687 26.28-22.417-12.597-12.037-1.098.549 4.379.022.011ZM12.418 127.191 8.04 114.594H5.308L.38 132.655l9.842 26.829L40.3 183.02l39.918 17.524h6.013l4.927-2.195 7.11-1.097v-5.475l7.659-3.281 1.098-5.476 5.464-4.927v-4.378c-4.389-.537-18.442 1.568-22.966 2.184l-6.013-4.378 8.745-6.573 3.281-7.122-4.378-1.646c-5.005 1.982-19.002 8.566-24.063 10.951-11.802-5.654-29.314-17.008-39.918-24.634l-9.294-7.121-5.464-8.208v.023ZM82.96 361.502v-16.975h26.247l6.561 11.5-10.939 2.195-1.646 12.048-20.234-8.756.011-.012ZM140.929 344.527V339.6l8.745-1.097 13.672-4.378 6.013 10.402h-9.294l-6.562 7.67-12.574-7.67Z" fill="#EEC8A7"/><path d="M256.955 137.624c-.717-2.228.403-4.859-.862-6.785-1.053-1.086-2.195-2.139-2.072-3.886.023-.246-.045-.716-.168-.761-1.847-.661-1.276-2.24-1.377-3.538-1.422-13.672-4.748-27.3-10.951-39.627-5.307-13.068-15.631-23.212-27.971-29.752-.985-.66-2.038-1.052-2.833-.268-2.049 2.44 2.128 4.4 2.509 6.808 1.702 4.232 2.922 8.599 3.885 13.056.101.447.661.929-.101 1.478-5.24-7.1-11.175-13.84-17.221-20.212-8.432-8.913-15.262-19.001-22.753-28.665-4.972-6.662-10.29-13.414-11.264-21.935-.045-2.071-2.822-2.878-4.054-1.478-1.478 1.915-3.538 3.191-5.061 4.972-6.651 6.696-14.075 12.619-18.296 21.364-4.3-14.859-19.752-22.047-34.163-23.089-8.264-1.377-15.161 4.266-22.708 6.517-1.03.37-1.669.907-2.307 1.724-3.785 4.994-8.096 9.372-13.829 12.295-2.586 1.332-4.87 3.292-6.102 6.215-1.635 2.832-1.579 6.248-2.956 9.047.93.493.492 1.4.448 2.06-.224 3.594.078 7.054 1.276 10.503.515 1.478 1.478 2.923 1.355 4.546-.145 2.06-.291 4.054 1.176 5.185-1.422 1.366-2.307 3.292-3.886 4.378-2.273-5.073-2.597-10.884-3.079-16.37-.571-4.054 1.12-11.444-4.546-11.993-4.725 1.422-7.424 6.035-11.018 9.17-6.047 6.45-12.43 12.855-17.39 20.111-3.695 5.386-5.587 11.668-7.423 17.87-2.788 7.75-5.095 14.792-6.371 23.134-.448-2.15-1.803-1.847-2.587-.347-5.923 12.127-5.15 26.549-.963 39.068 4.12 8.42 5.52 17.882 8.958 26.627 7.222 27.366 29.661 46.939 54.878 57.901 2.16.985 3.639 3.124 6.248 3.392 1.108.124 3 .684.963 2.43-.27.247.078.538.123.806-.94 21.286-2.24 42.628-5.655 63.724-1.377 6.069-2.609 12.172-3.348 18.319-.224 1.814-1.175 3.762.123 5.531.616.807.717 1.725 1.109 2.71-.784.168-1.624-.784-2.116.291-.392.862.201 1.725.615 2.016 1.49.806 2.374 2.945 4.132 3.068 4.58.672 7.334 5.442 11.444 7.323.492.246.985.716.739 1.254-.605 11.69-3.28 27.668 3.639 37.735 5.52 5.744 12.25 10.738 19.73 13.571 2.485.907 5.385 1.052 7.423 2.653 2.565 1.994 5.409 2.218 8.242 2.218 12.585-.56 19.651-8.309 15.721-20.85-2.206-3.258-3.393-7.524-5.733-10.94-3.83-6.012-8.79-11.118-13.504-16.247-4.86-9.014-7.715-5.419 4.333-9.685 5.8-1.635 3.796-8.365 4.3-12.832.369-4.569.168-9.193.515-13.773.145-1.769-1.21-3.438-.123-5.162 2.116-20.457.47-41.396 2.161-61.932 5.666.011 11.365-.023 16.997-.638 5.464-.784 10.772-2.553 16.382-2.341-.023-.391-1.064-.739.145-1.153 3.415-1.153 6.943-2.038 10.257-3.516 4.714-3.896-1.904 34.32-1.422 37.589-.582 11.097-1.389 22.093-1.792 33.211-.044 3.864-.369 7.715.079 11.556.123 1.131-.079 2.016-.93 2.822-9.629 9.607-11.813 6.875-23.514 8.51-.907.246-2.262.66-3.348-.068-1.03-.694-2.217-.638-3.37-.638-1.713-.448-8.611 1.4-7.032-1.847.123-.291 0-.717 0-1.053.627-19.505 3.639-39.145 2.363-58.64-.224-.683-.247-2.262.123-2.508 1.422-1.008.862-2.408.884-3.538.079-5.017 1.232-10.033.347-15.072-.884.627-2.956-1.086-3.168.638-.829 6.551-2.005 13.403-1.422 19.987-1.131 4.02-.975 8.522-.292 12.441-1.522 1.601-.515 3.538-.761 5.285-.246 15.049-2.128 29.997-2.531 45.035-.022 1.948 1.109 2.9 3.08 3.348 14.657.638 6.964-.985 11.018 20.401 2.004 13.392 20.58 18.79 32.024 20.872 5.968 2.049 14.78-2.956 17.736-8.185.448-2.587 2.777-6.707-.414-8.264-.235-4.546-2.642-8.532-5.195-12.093-4.569-3.202-15.867-12.025-17.345-17.131-.168-.572.963-.863 1.422-1.355 1.792-2.128 4.625-3.998 4.647-7.055.101-6.024-.202-12.048.291-18.072.694-12.944 1.053-25.966 2.587-38.866 6.337-49.021-9.193-14.567 38.933-50.936 12.003-9.854 21.028-22.753 26.224-37.421.94-3.483 3.695-5.453 6.763-7.032 1.545-.515 1.523-2.486 2.362-3.684 6.999-8.689 8.309-20.771 6.618-31.543h.022l-.022.011ZM141.869 338.459c6.775-.818 12.922 1.086 19.551-1.87 1.78-1.109 2.206.839 2.956 1.937 1.948 2.295-5.7.414-7.424 6.908-.269.784-.985 1.255-1.153 2.139-.123.594-.694-.045-.963-.224-3.259-2.284-7.099-4.087-10.111-6.584-.717-1.108-1.669-1.769-2.856-2.306Zm26.616 32.841c5.487.941 10.94 1.232 16.136-1.108.268-.124.515-.247.963-.079-.045.862-.448 1.277-1.154 1.669-2.967 1.377-5.442 4.568-9.002 3.807-7.984-1.501-29.248-6.372-30.3-15.609.324-.269.638.123.907.324 2.318 1.77 4.456 3.863 6.987 5.162 1.4.717 2.362 2.363 4.423 2.184 3.415 1.747 7.188 2.788 11.04 3.639v.011ZM129.396 56.69c.828-2.328-.056-6.393 2.485-7.714 2.352-5.409 4.468-11.153 8.242-15.912 3.896-11.32 14.399-18.15 22.237-26.504 3.248 11.142 10.907 19.876 17.737 28.912 12.888 19.091 32.382 33.3 41.665 54.8.694 1.13 1.332 1.847 2.777 1.276 1.567-.616 1.332-2.162.884-2.9-1.198-4.065-2.351-7.984-3.124-12.172-.1-.84-.1-2.34-1.746-2.284-.202 0-.247-.202-.124-.37 1.736-2.81-2.385-10.156-3.079-13.963 17.669 10.57 25.384 31.364 29.348 50.601.571 7.312 4.546 15.609.862 22.473-9.652 15.385-26.436 24.399-42.012 32.696-8.89 3.594-22.943 13.492-32.046 8.454-3.595-1.355-6.696-3.74-10.257-5.185-.538-.201-.963-.739-.045-1.523 17.39-15.541 22.484-41.922 8.7-61.484-4.199-6.785-9.596-13.213-16.941-16.348 8.219-1.623 16.124 3.068 21.991 8.41 1.422 1.388 3.539-.202 2.733-1.994-5.095-8.219-13.191-14.299-21.152-19.595-8.566-6.618-18.946-9.126-29.471-10.593-2.15-.425 0-7.412.347-9.07l-.011-.01Zm-5.655 119.61c.47 1.422 2.116 3.023 3.661 3.762-4.993.515-9.965.493-15.351.022.862-.537 1.377-.884 1.915-1.209 5.408-2.586 3.516-10.033-2.34-9.809-7.547-.436-15.318 5.039-22.608 1.232-.884-.224-1.153-1.008-.1-1.646 2.16-1.299 3.74-3.27 5.385-5.061 2.139-2.307 4.379-4.669 3.93-8.353-.1-.84 1.154-1.523 1.602-2.531 1.971-4.356-.325-10.402-4.893-11.824-2.833-.862-5.017-2.195-6.45-4.815-.392-.739-.885-1.993-2.284-1.299-.045.045-.37-.19-.347-.246.414-1.355-.863-1.277-1.478-1.725-.594-.448-1.3-.739-1.915-1.175-2.038-1.523-1.915-1.893.291-3.102 2.844-1.87 5.52-3.796 8.857-4.356 6.763-.739 12.966-2.978 19.528-4.691-3.012 9.719 2.979 22.249 14.489 19.181 7.491-2.419 6.439 2.463 8.958 7.255 3.785 6.125-1.265 16.315 6.416 20.234.37.168 1.053.19.84.784-1.388 3.303 7.211 6.763 5.509 7.502-7.804 3.628-12.854-8.723-22.092-2.117-.247.247-.168.538-.224.807.112 3.068-1.926.862-1.333 3.191l.034-.011Zm-49.492-37.489c.38-1.142 3.147-8.588 4.479-6.763 1.904 2.934 5.89 2.979 7.547 6.002 3.27 7.2 9.72 3.583 10.772 9.316.638 10.469-.66 3.281-8.264 6.024-2.217.594-4.233 1.478-6.147 2.755-.638.414-.762.201-.93-.616-1.31-2.923-3.079-5.52-3.101-8.924-.101-1.546.269-3.46-1.523-4.67-1.646-1.007-3.785-.459-2.833-3.124Zm1.254 9.831c-.985-1.399-1.176-2.855-1.668-4.232 1.747.123 1.915.537 1.668 4.232Zm68.572 14.008c-2.262 1.299-3.538.392-3.807-2.183-.381-3.606-1.467-7.099-1.086-10.716-.425-3.729-3.471-6.517-3.415-10.548-.347-2.53-3.74-4.568-6.763-4.176-12.284 3.415-17.983-4.681-14.187-16.035.47-1.444 1.892-1.724 2.9-2.363 4.232-2.776 5.968-7.77 8.163-12.093 1.287-1.612 2.519-.548.963-3.101-.124 0-.247.078-.347.078a1.096 1.096 0 0 0-.023-.47c-2.116-1.579-26.65-9.137-21.846-12.362 2.408-1.332 4.725-2.855 7.278-3.908.885-.347 1.355-1.791 2.654-.963-.84 3.415.325 4.177 6.103 3.908.291.269.101.538-.045.784-2.542 3.919 1.624 6.662 3.639 9.17.291 1.131 2.016 2.094 2.217 3.371.123.101.246.224.37.392.638-.247 1.399-.862 1.455-1.131.079-.66-1.231-3.807-1.892-4.625-1.075-1.522-4.322-3.325-3.146-5.43.492-.325 1.052-.101 1.399.347.515.716 1.355.93 2.016 1.4 2.385 1.858 4.344-.56 6.248-1.87 1.747-1.176 2.094-2.755 1.377-4.67-1.198-3.505 5.811-2.183 7.603-4.11.885-.637 1.971-1.03 2.754-1.768 2.733-2.161 3.595 5.094 6.64 4.423.986-.202 1.299.447 2.094 1.052-7.804 2.452-6.998-2.194-13.336-1.825-1.063 0-2.631 2.463-2.385 4.233.202 1.578-.515 3.437 1.422 4.725 2.106 1.187 3.606-.538 5.655-.291 3.046.806 2.217-2.576 4.109-1.702 2.274 1.78 12.149 4.792 10.828 8.118-.784 1.993.146 4.132-.269 6.192-.347 1.623-.324 3.225.907 4.546.818.885 1.87 2.116 3.001 1.601 1.602-.784 4.11 0 4.815-2.53.818-1.725 3.449 4.546 3.74 5.755-3.348-3.382-10.279-2.105-8.711 3.393.47 1.444 1.298 2.575 2.9 2.922 1.108.146 4.154 2.889 1.702 3.471-1.378 1.434-1.154 2.598-3.516 1.4-2.184-1.243-5.263 2.743-4.031 4.647 4.21 5.89 8.935-.47.94 10.38-2.9 3.538-3.225 7.748-2.777 12.026.146 1.231-.616 1.87-1.086 2.138-2.687 1.523-3.348 4.255-4.3 6.763-1.276 4.591-5.587-.739-8.901 1.646l-.023-.011ZM98.178 79.085c-.415-.123-.124-.56.145-.84 2.038-2.138 4.3-3.684 7.458-3.617 1.254.023 2.485-.223 2.956-2.183 2.138 4.445 12.137-1.568 13.795 2.307.022.907-.863 1.299-1.792 1.579-2.094.593-3.762 2.037-5.677 3.023-4.356 2.374-9.014 4.3-12.989 7.256-.369.268-.492.907-1.254.448-.571-.348-.884-.616-.862-1.333.045-1.4-.414-2.654-1.355-3.684-.448-.47-.201-.761-.145-1.21.022-.537 1.175-1.354-.27-1.746h-.01Zm-2.486 3.102c-1.97-.94-3.001-3.292-5.308-3.863-.593-.202-1.03-.571-1.007-1.154 0-.616.716-.537 1.086-.683 3-1.276 5.8-3 9.271-3.516-4.053 1.938-4.031 5.61-4.031 9.216h-.011Zm35.495 4.008c.325 1.691-1.008 2.262-1.747 3.046-1.948 1.388-3.963-3.124-7.233-2.307 1.926-2.99 1.086-6.65-3.146-5.8 1.209-1.332 2.732-1.456 3.963-2.16 4.446-2.23 3.315-7.447-1.187-8.264-5.43-1.042-10.088.918-15.81.414 10.704-4.67 21.499-1.646 32.315-.023 7.917 1.31 14.837 5.465 21.107 10.224-1.254.414-2.071 2.216-3.348 1.623-2.015-.93-4.871-.515-5.8-3.594-.739-2.34-2.508-2.284-4.725-2.363-3.718-.123-6.372 2.553-9.944 2.833-3.538.269-5.139 2.8-4.456 6.371h.011Zm14.389 2.509c-1.456-.348-5.006 1.903-5.14-.538.168-.761.538-2.116 1.456-1.747 1.209.47 2.609.885 3.695 2.285h-.011Zm16.728 10.962c2.509 1.354 2.195 3.93 3.516 5.576.202.224.101 2.116-.963 2.508-4.68.795-1.623-5.453-2.564-8.084h.011Zm-7.255 64.339c1.601-1.948 1.31-5.341 3.56-6.662 0 2.709.291 5.061 3.595 6.371-.907.717-1.893 1.153-2.363 1.915-.537.884-1.232.716-1.769.47-.963-.414-1.601-1.456-2.8-1.5-.223 0-.369-.37-.223-.594Zm6.64-5.431c.806-1.276.783-2.362-.616-3.224-.493-.269 0-.594.022-.885.168-1.4.571-2.777.392-4.199-2.385-7.267 13.851-16.807 3.516-20.748-.661-.224-1.478-.101-1.355-1.232.638-.011 1.243.358 1.859.582 2.183.84 3.303-2.318 5.285-2.866 2.609-2.352-.358-7.939-3.695-8.678-1.008-.202-1.478-2.329-.37-2.341.717.325 1.131-.783 2.139.079 3.684 3.146 5.117 7.233 5.711 11.802 3.672 10.245-.739 20.502-6.517 29.034-.079-2.262.448-4.915-2.117-5.923-.962-.392-3.224-1.008-3.986 1.276 1.053 0 1.288.627.717 1.893.907.168 1.5-.415 2.43-.885-.023 3.023-1.893 5.084-2.9 7.603-.594-.47-.762-.884-.515-1.276v-.012Zm-2.218-73.364c-.078-.907 1.255-1.03 1.77-1.724.615-.807 1.063-.247 1.668.167 1.31.93 2.777 1.624 3.561 3.225-2.083.28-3.303-.806-5.14-1.209-.638-.269-1.747.739-1.87-.47l.011.01Zm-73.6-31.42c.807-11.522 4.659 1.478 15.453-10.962 4.871-5.106 8.801 3.684 13.974-2.362 6.226-9.652 8.365-2.856 11.511 4.087 2.217 1.086 1.254 2.676.593 4.154-.862 1.87-.268 4.053-1.623 5.822.862-1.892-.594-2.732-1.601-3.538-1.109-.885-1.893.37-2.184 1.053-1.847 3.661-6.225 1.31-9.372 2.138-1.4.336-1.915 3.27-.246 3.539 4.501 1.175 8.902 1.523 12.989-1.993-.471 1.746.492 7.815-1.523 7.547-1.456-.101-2.923.223-4.356-.348-2.799-1.086-5.464-.044-7.95 1.008-7.457 3.057-15.374 4.95-22.305 9.193-.806.515-1.892 1.086-2.363-.806-.391-2.452-2.687-10.033-.739-11.556.515-.145.37-.56.123-.806-1.847-1.937-.57-4.177-.369-6.17h-.011Zm-73.677 46.984c2.99-8.767 5.229-18.274 9.103-26.627C29.09 62.289 38.843 51.898 49.56 42.705c.146 3.471 1.523 36.268 8.364 29.92 5.756-8.253 14.21-14.12 22.339-19.865 1.355-1.063 2.53-.492 1.948 1.154-.739 7.379-.918 21.857 5.487 26.671 6.248 4.11 10.503 10.884 16.953 14.826 3.807 2.43 8.33 3.963 12.541 5.632 1.175.347 1.578 1.523.963 2.53-2.072 3.001 2.049 4.905.447 6.786-4.747 5.991-12.932 6.214-19.505 9.047-5.308 1.199-10.906 1.59-15.81 4.379-8.264 3.717-10.66 8.017-13.426 16.404-.907 6.449 3.93 12.507 5.755 18.531.347.806.448 1.332-.716 1.624-1.277.324-2.262 1.5-3.74 1.332-.493-.045-.616.269-.392.683.324.616-.269 1.053-.269 1.691-1.109-1.87-3.225-1.523-4.77-2.363-3.449-1.108-7.02-2.889-9.91-4.915-10.312-6.965-21.017-13.28-30.893-20.827-1.5-.627-2.172-3.986-4.154-1.915 0-.885 1.086-1.176.224-1.724-2.307-1.501-3.247-4.3-5.588-5.801-2.105-8.151-6.494-17.154-3.168-25.742l-.045.011ZM5.453 144.04a67.316 67.316 0 0 1-1.792-16.202c-.212-2.172 1.814-18.386 4.916-11.6.65 4.445 1.892 9.405 5.386 12.485.616.436-.202.806.202 1.354.716.986 1.422 1.971 2.306 2.8 8.555 8.353 18.946 14.175 28.777 20.849 5.464 3.169 18.453 13.314 24.354 12.25 3.382-1.008 6.338-3.191 9.764-4.21 1.725-.538 3.147-1.109 4.054-2.755.246-.414.929.123 1.545-.145 1.5-.695 2.833-1.77 4.479-2.217 1.668-.616 4.087-1.669 5.486-.045.515.761-.66 1.299-.985 1.993-1.836 3.113-5.027 5.095-7.457 7.748-1.478 1.602-4.994 1.176-5.756 3.225-.145 1.377 1.254 2.06 2.363 2.609 12.507 7.469 27.937-3.762 30.524 1.501.145 2.665-5.476 4.087-7.503 4.814-10.2 3.225-20.905 2.609-30.848-1.153-.806-.291-1.377.448-1.915.907-.616.594 0 1.008.291 1.5.963 1.77 2.878 1.322 4.334 1.848 4.792 1.668 9.741 2.676 14.859 2.284 3.683-.291 7.334-.761 10.995-1.175 1.03-.336 2.117.134 3.024.615-.986.392-.415 1.848-2.016 2.262-9.271 3.774-21.13 4.804-29.684-1.276-.84-.594-2.016-.347-1.97.268.078.784-1.232 2.016.694 2.632 11.51 7.256 13.056 3.023 24.746 4.3-2.934 9.047-19.036-2.811-20.077 3.739-.146 1.456-.616 1.501-1.579.639-1.355-1.232-3.169-1.4-4.77-2.016-4.434-2.452-8.958-4.658-13.627-6.539-1.792-.515-3.785-.246-5.341-1.601-16.83-10.324-40.22-22.451-47.79-41.676l.011-.012Zm80.822 53.501c-1.624.526-5.52.773-5.677-1.176.145-.269.66-.369 1.21-.145 1.376.515 2.798.862 4.478 1.332l-.011-.011Zm-.616 154.119c-.1-1.523.93-3.023 0-4.624-.123-.224.269-1.501.537-2.217.124-.37.717 0 1.008.224.806.537 1.624.66 2.856.078-.84.985-.37 1.568-.146 2.363.717 2.608 1.915 1.455 3.393 1.007a25.4 25.4 0 0 0 3.74-1.478c3.012-1.769 6.584-.156 9.764-1.299 1.299-.291 2.138-.078 2.732 1.087.515 1.377 2.027 2.709 2.071 4.075 0 1.456-1.847.863-2.833 1.355-6.46 2.867-7.994 8.824-4.478 14.747.537 1.053.123 1.131-.538 1.444-4.792 2.587-7.2-3.213-10.704-5.285-2.173-1.668-3.64-4.176-6.047-5.531-1.77-1.725-1.21-3.886-1.355-5.946Zm28.923 37.522c2.754.806 7.535-.784 8.957 2.262.325 1.299-1.332 1.422-1.646 2.385-3.504-1.411-7.636.683-10.973-1.444-2.116-1.602-5.095-1.77-6.785-4.11-1.848.717-2.038-1.791-3.886-1.814-1.5-.022-3.124-1.523-4.423-2.654-.739-.638-1.847-.246-2.34-1.276-.291-.593-.045-2.307-1.668-1.176-1.109-1.5-3.102-2.015-4.031-3.594-.784-1.389-2.14-4.311-.661-5.531.47-.045.392.47.47.783 8.062 6.584 16.897 13.101 27.008 16.18l-.022-.011Zm9.719-139.596c-2.777 12.294-.997 25.059-1.456 37.544-.728 15.475-1.579 31.028-1.971 46.57-.459 3.784-7.67 4.736-10.749 5.576-9.887 1.646-17.11 3.751-25.34-3.37a59.66 59.66 0 0 1-8.856-6.64c-1.176-1.053-1.893-2.632-3.763-2.856-1.892-.683.84-3.852.762-5.307.347-1.501.94-2.855.224-4.625.84-24.846 5.7-50.163 5.8-75.335 0-1.937.537-2.385 2.195-1.5 3.941 2.161 8.04 2.777 12.205 4.131 9.764 2.688 19.796 5.062 30.008 4.502 1.053-.023 1.154.448.93 1.299l.011.011Zm111.133-64.608c-10.291 24.107-33.357 39.616-56.692 49.637-1.5.806-2.094-2.172-4.154.885-4.121 3.628-10.235 3.93-15.352 5.509-12.641 3.404-25.854 4.915-38.91 3.807-30.714-1.725-63.32-16.74-85.547-37.836-13.236-12.619-18.341-30.434-23.347-47.454 16.203 15.576 35.473 28.363 56.603 36.089 4.58 2.307 17.994 9.473 21.274 3.146.516-1.052 1.277-.761 1.915-.66 1.948.269 3.84.168 5.632-.694 6.752-2.094 3.046-7.032 8.633-8.801 2.094-.471 3.292-2.307 4.479-3.931.392-.537.639-.817 1.333-.817 4.3.123 8.633.201 12.966.246.392 0 .963-.291.84.392-.392 2.116 1.277 3.023 2.553 3.561 1.4.616 2.385 1.993 4.087 1.937-6.046 9.338 6.517 10.861 13.157 11.432-.235 3.08 1.679 6.629 5.072 6.461 8.017.84 15.777-1.478 23.716-1.455 13.482-.941 25.239-7.402 37.22-12.978 9.293-3.415 17.445-8.801 26.369-13.448-.224 1.915-1.175 3.415-1.814 4.938l-.033.034Zm16.997-32.797c-1.467 5.274-1.702 12.093-6.102 15.855-9.339 9.865-22.574 15.755-34.734 21.633-5.509 1.971-10.649 4.759-16.012 7.256-1.131.638-2.531 1.87-4.211.862-7.535 2.318-37.824 10.503-43.512 5.061.448-2.776 9.462-1.343 11.903-1.646 2.944.84 3.168-3.437 0-3.437-4.681-.213-29.539 3.191-25.553-5.778.37-1.355 1.21-.291 1.725-.123 3.818 1.377 7.524 3.046 11.589 3.516 2.553.325 5.162.515 7.67-.806.985-.515 2.363.123 3.449-.538.873-.638 2.967-.739 2.262-2.306-.415-.885-1.333-1.232-2.117-.93-1.97.739-4.008.694-6.001.885-5.89.817-20.838-2.721-24.354-7.502 8.901-2.833 15.586 7.547 25.216 5.845 2.06-.571 8.331 1.343 7.334-2.408-.201-.784-.661-.47-1.086-.47-9.674.929-17.401-2.161-25.339-7.402-1.255-.806-2.957-.761-4.278-1.601-1.086-.66-1.847-1.769-3.079-2.239-1.109-.963 3.37-2.34 3.885-2.284 7.603 2.093 13.751 7.692 22.037 7.3 2.183-.168 4.725.146 7.032.818.862.246 1.993.929 2.508-.37 2.127-4.378-8.555-6.673-11.142-9.17-2.351-1.814-5.587-2.688-6.27-5.946-.123-.347.291-.515.806-.515 11.78-.392 26.739 17.221 37.925 12.765 21.32-7.044 40.803-18.812 58.562-32.137 1.668-1.545 3.471-3.224 3.908-5.777 1.467-3.057 4.053-5.453 5.677-8.577 2.161 6.348 2.127 13.582.269 20.188l.033-.022Zm-102.623 25.294c1.624-1.522 2.139-1.545 3.718-.224.201.146.66.168.492.56-1.019.661-2.855-.414-4.21-.347v.011Z" fill="#010101"/><path opacity=".3" d="M97.125 151.811c.101 1.254-.246 1.814-1.702 1.299-4.355-1.232-9.07.761-12.787 3.023-1.086.918-1.019-1.881-1.792-2.463-1.377-2.161-2.037-4.479-2.239-7.077.09-1.825-.112-4.658-2.631-5.184-1.826-.269-2.24-.84-1.725-2.609.381-1.142 3.147-8.589 4.48-6.763 1.455 1.869 3.493 2.9 5.53 3.907.885.448 1.523 1.131 2.016 2.094 1.601 3.247 4.4 5.14 7.827 5.778 3.863 1.12 2.867 4.893 3.023 7.995ZM122.532 74.764c.022.907-.862 1.299-1.792 1.579-2.094.593-3.762 2.037-5.677 3.023-4.355 2.374-9.013 4.3-12.988 7.256-.37.268-.493.907-1.255.448-.571-.348-.884-.616-.862-1.333.045-1.4-.414-2.654-1.355-3.684-.447-.47-.201-.761-.145-1.21.022-.537 1.175-1.354-.269-1.746-.414-.123-.123-.56.146-.84 2.038-2.139 4.299-3.684 7.457-3.617 1.254.023 2.486-.223 2.956-2.183 2.139 4.445 12.138-1.568 13.795 2.307h-.011Z" fill="#000"/><path d="M154.489 106.25c-1.086-1.523-2.956-2.116-4.132-3.471-1.332-1.545-2.833-1.377-4.154-.515-1.131.717-1.702.638-2.71-.168-1.545-1.254-3.964-.537-4.255 1.03-.537-1.915-1.747-3.437-2.855-4.938-1.948-2.183-5.386-.269-5.341 2.508-.123.616.145 1.333-.448 1.792-2.217 1.456-.067 4.86 2.195 3.807 1.108-.325 1.791.045 2.385.963 2.765 4.893 6.83.549 10.234 3.146 3.101 2.845 13.045 1.098 9.081-4.154Zm-17.837-2.038c-1.333-.862-2.901-1.5-2.285-3.639.493 1.378 2.878 1.456 2.285 3.639Zm.907.885c2.239.022 4.646-1.691 6.348.761-3.202 1.355-5.531 1.053-6.348-.761Zm12.395 3.415c-.829.347-6.047-1.456-4.031-2.363 1.03-.638 1.971-1.623 3.27-.47 1.31.918 4.624 3.046.761 2.833ZM93.385 63.645c-1.332-.448-2.956.291-4.3-.985-2.575-1.646-.929-4.423 1.669-3.539 6.718 2.217 10.156-4.736 12.127-1.008 1.422 4.703-6.148 5.465-9.518 5.554l.022-.022Z" fill="#010101"/><path opacity=".3" d="M166.066 120.191c-7.132-3.146-1.142-12.25 5.801-6.315-.258-1.142-2.912-7.469-3.74-5.755-.717 2.553-3.225 1.746-4.826 2.53-1.131.515-2.195-.716-3.001-1.601-1.232-1.333-1.254-2.923-.907-4.546.414-2.06-.515-4.199.269-6.192 1.332-3.315-8.555-6.338-10.828-8.118-1.881-.874-1.075 2.508-4.11 1.702-2.049-.247-3.549 1.478-5.654.29-1.948-1.276-1.232-3.146-1.422-4.724-.247-1.77 1.332-4.233 2.385-4.233 6.315-.38 5.531 4.266 13.336 1.814-.784-.616-1.109-1.254-2.094-1.053-3.046.672-3.908-6.584-6.64-4.422-.784.739-1.87 1.13-2.755 1.769-1.814 1.96-8.711.537-7.603 4.11.717 1.914.37 3.493-1.377 4.668-1.903 1.31-3.863 3.73-6.248 1.87-.661-.47-1.5-.683-2.015-1.4-.348-.447-.907-.66-1.4-.346-1.176 2.116 2.083 3.907 3.146 5.43.661.806 1.971 3.964 1.893 4.625-.045.268-.818.884-1.456 1.131 1.568 2.541.302 1.489-.963 3.101-2.195 4.334-3.93 9.316-8.163 12.093-1.007.639-2.441.907-2.9 2.363-3.852 11.242 2.038 19.506 14.198 16.034 8.488-.515 5.845 7.256 9.417 11.847 1.624 2.576.101 5.756 1.008 8.577.515 1.601.638 3.348.84 5.017.268 2.575 1.545 3.493 3.807 2.183 1.915-1.086 3.695-.515 5.408-.022 2.217.66 2.654.571 3.494-1.624.963-2.508 1.623-5.24 4.299-6.763 2.621-1.601-1.075-8.935 3.863-14.165a36.74 36.74 0 0 0 3.539-5.038c1.008-1.725 1.355-1.949-.986-2.677-2.597-.683-5.285-3.426-2.832-5.945 3.493-4.334 3.863 1.982 6.886-2.755 2.474-.582-.605-3.314-1.702-3.471l.033.011Zm-12.686-9.215c-5.8 2.945-7.401-2.172-11.903-1.4-5.778 1.814-5.374-3.952-8.678-3.269-2.25 1.052-4.411-2.352-2.194-3.807.593-.471.313-1.176.436-1.792-.044-2.766 3.393-4.703 5.341-2.508 1.109 1.5 2.307 3.023 2.856 4.938.291-1.579 2.71-2.284 4.255-1.03 1.008.806 1.579.884 2.71.168 1.332-.863 2.832-1.031 4.154.515 2.385 1.892 8.33 5.912 3.023 8.185Z" fill="#000"/></g><defs><radialGradient id="h" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(85.5666 0 0 85.8708 119.029 18.6)"><stop offset=".1" stop-color="#FFE226"/><stop offset=".79" stop-color="#FF7139"/></radialGradient><radialGradient id="d" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(254.002 0 0 251.98 101.828 131.939)"><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="e" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(81.3368 0 0 138.09 150.945 -11.817)"><stop offset=".13" stop-color="#FFF44F"/><stop offset=".53" stop-color="#FF980E"/></radialGradient><radialGradient id="f" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(107.63 0 0 117.964 97.269 197.007)"><stop offset=".35" stop-color="#3A8EE6"/><stop offset=".67" stop-color="#9059FF"/><stop offset="1" stop-color="#C139E6"/></radialGradient><radialGradient id="g" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(57.1516 0 0 69.5986 115.659 106.045)"><stop offset=".21" stop-color="#9059FF" stop-opacity="0"/><stop offset=".97" stop-color="#6E008B" stop-opacity=".6"/></radialGradient><radialGradient id="c" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(247.807 0 0 251.98 173.682 27.866)"><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="i" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(408.512 0 0 342.923 197.173 -37.735)"><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="j" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="rotate(77.394 -24.396 66.127) scale(129.607 560.661)"><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="k" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(234.546 0 0 230.425 119.907 49.48)"><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="l" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(281.917 0 0 252.208 180.784 62.938)"><stop offset=".09" stop-color="#FFF44F"/><stop offset=".63" stop-color="#FF980E"/></radialGradient><linearGradient id="b" x1="217.145" y1="38.76" x2="22.595" y2="226.431" 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><linearGradient id="m" x1="199.598" y1="35.009" x2="44.026" y2="204.989" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#FFF44F" stop-opacity=".8"/><stop offset=".6" stop-color="#FFF44F" stop-opacity="0"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h257.593v400H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/noodle-C.svg b/browser/components/newtab/data/content/assets/noodle-C.svg
new file mode 100644
index 0000000000..f91f5f1083
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/noodle-C.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="915" height="718" viewBox="0 0 915 718" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="1" d="M799.853 399.917C742.413 440.039 663.081 427.307 620.71 371.157L618.218 367.8C577.626 314.025 501.27 302.258 446.674 341.731C392.077 381.204 379.712 457.116 418.541 512.166L420.991 515.58C461.938 573.632 448.9 653.676 391.337 695.294C333.193 737.331 251.634 724.247 209.17 666.063C83.9763 494.522 121.467 254.982 292.903 131.034C464.34 7.08669 704.807 45.6649 830.001 217.206C872.04 274.808 859.997 355.012 803.335 397.4L801.604 398.672L799.853 399.917Z" fill="context-fill"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/noodle-outline-L.svg b/browser/components/newtab/data/content/assets/noodle-outline-L.svg
new file mode 100644
index 0000000000..d2c1f29ff6
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/noodle-outline-L.svg
@@ -0,0 +1,13 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.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="147" height="164" viewBox="0 0 147 164" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M26.0923 73.3091C13.8884 71.367 5.84156 60.0045 8.1684 47.9971C10.4712 36.1135 22.0746 28.0774 34.1527 29.9995L100.16 40.504C112.485 42.4654 120.545 54.0226 118.024 66.1182L104.519 130.898C102.048 142.752 90.3351 150.631 78.2883 148.543C66.1158 146.432 58.2353 134.956 60.7321 122.98L69.6422 80.2397L26.0923 73.3091Z" stroke="url(#paint0_linear)"/>
+<defs>
+<linearGradient id="paint0_linear" x1="52.2466" y1="163.233" x2="0.9998" y2="40.1293" gradientUnits="userSpaceOnUse">
+<stop stop-color="#9059FF"/>
+<stop offset="0.520833" stop-color="#FF4AA2"/>
+<stop offset="1" stop-color="#FFBD4F"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/noodle-solid-L.svg b/browser/components/newtab/data/content/assets/noodle-solid-L.svg
new file mode 100644
index 0000000000..7e6a52d12f
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/noodle-solid-L.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="1587" height="1303" viewBox="0 0 1587 1303" xmlns="http://www.w3.org/2000/svg">
+<path d="M446.454 1039.08C360.266 1140.41 210.738 1150.78 113.365 1062.15C16.9963 974.442 8.0789 822.76 93.3782 722.472L559.549 174.385C646.592 72.0471 797.983 62.6514 895.076 153.561L1415.08 640.444C1510.22 729.534 1517.09 881.343 1430.44 980.413C1342.88 1080.52 1193.24 1088.72 1097.1 998.699L754.019 677.469L446.454 1039.08Z" fill="context-fill"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/person-typing.svg b/browser/components/newtab/data/content/assets/person-typing.svg
new file mode 100644
index 0000000000..d05cda6a94
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/person-typing.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="191" height="186" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M65.459 185.823c3.343-1.18 6.03-1.133 6.03-1.133 15.06-.033 69.71-.134 70.647-.067 1.339.101 8.151-.157 12.216 7.169.033 0 .033.033.033.033a27.027 27.027 0 0 1 1.807 4.288c1.071 3.383 1.808 7.939 1.473 13.567-.201 2.244-.502 7.135-3.347 11.825-2.945 4.891-7.028 8.174-13.085 10.251-5.154 1.742-10.208.938-16.432.368h-.067c-.235-.033-.703-.134-1.272-.234l-1.138-.201a21.616 21.616 0 0 0-1.472-.268h-.067a1814.282 1814.282 0 0 1-15.997-2.948l-.235-.034-1.234-.241c.861 1.196 1.72 2.4 2.576 3.613a469.04 469.04 0 0 1 6.426 9.313l8.4 11.892c1.271 1.775.703 4.254-1.272 5.494l-10.341 6.431-9.37 6.231-1.841 1.173c-1.841 1.138-4.075.602-5.489-.871-3.742-3.901-10.764-13.068-19.578-23.047l-1.035-1.169C66.84 256.5 60.69 268.561 57.098 274.6c-.703 1.206-2.075 1.843-3.48 1.642l-26.573-3.953c-2.276-.335-3.615-2.781-2.644-4.891 4.92-10.82 11.178-27.871 16.499-39.327a425.233 425.233 0 0 0 3.882-8.609l.595-1.357c-1.999-2.746-3.176-4.71-4.206-7.197-1.172-2.814-2.243-5.393-2.176-8.877.1-5.159 2.678-11.021 7.832-14.17 2.878-1.775 5.689-1.876 7.362-2.01 2.242-.067 4.82-.033 7.697-.033 1.503-.012 2.634-.02 3.573.005Z" fill="#BA94FF"/><path opacity=".317" d="M64.968 185.813c-3.915 1.461-8.615 4.619-10.964 11.439-.031.063-5.219 12.567-8.756 20.675-1.92-2.653-3.069-4.586-4.077-7.019-1.172-2.813-2.242-5.393-2.175-8.877.1-5.158 2.677-11.021 7.83-14.17 2.879-1.775 5.69-1.876 7.363-2.01 2.243-.067 4.82-.033 7.698-.033 1.25-.01 2.242-.017 3.08-.005Zm38.263 42.263c.89 1.236 1.778 2.481 2.664 3.736a466.09 466.09 0 0 1 6.426 9.312l8.4 11.892c1.272 1.776.703 4.254-1.272 5.494l-10.341 6.432-9.37 6.23-1.841 1.173c-1.84 1.139-4.075.603-5.489-.871-3.742-3.901-10.764-13.068-19.578-23.047a583.92 583.92 0 0 0-1.172-1.324 317.764 317.764 0 0 1 3.397-6.202s.937-1.675 2.945-4.857c1.64-2.613 3.347-4.891 4.786-6.801a137.78 137.78 0 0 1 3.179-4.153c1.506.2 3.012.401 4.518.636 2.075.368 4.15.77 6.258 1.139 2.18.397 4.337.794 6.49 1.211Z" fill="#444"/><path d="M115.337 119.817c6.046-1.735 12.272-.216 16.788 3.54l.239.16c.693.497 1.461 1.321 2.263 2.37.578.71 1.105 1.469 1.577 2.271 3.608 5.639 7.365 14.305 7.875 17.661 0 .992-.608 1.841-1.472 2.194 0 0 3.687 10.532 5.141 17.508 1.404 6.738 1.917 11.117 2.252 17.479.223 4.241-2.129.894-6.59 1.758-5.235-.054-13.994.044-26.278.294-12.283.251-19.622-13.048-22.016-39.895-2.644-8.781 1.508-17.912 9.405-21.797l-1.002-2.913a.67.67 0 0 1 .415-.851l9.493-3.272c.35-.121.73.065.851.415l1.059 3.078Z" fill="#9871E0"/><path d="m110.463 105.85 2.818 10.53-9.375 3.231-.69-2.743-.415.214c-2.676 1.427-2.52 1.309-2.713 1.397-2.038.787-3.838.943-4.175.945-2.816.094-6.614-4.66-8.851-11.869-.196-.585-.292-1.182-.422-1.774l-.892-5.936c-.207-1.325-.08-2.686.43-3.918.213-.528.43-1.023.692-1.42 2.945-4.959 9.356-4.791 10.502-4.777.133-.014.27.005.403-.009 1.296.167 2.403-.185 3.598-.345.532-.056 1.011.332 1.1.862l1.062 8.51c.078.531 1.099.06 3.064-1.416 2.435 1.282 3.909 2.446 4.422 3.492.851 1.696.508 3.551-.402 4.825-.051.07-.103.136-.156.201ZM75.57 169.278c4.693-1.135 9.943-1.403 15.75-2.803l3.164-21.236c.044-.48.11-1.046.215-1.682.104.481.228.962.373 1.442 3.072 8.451 5.928 16.616 8.567 22.494 6.975-1.012 13.56-1.782 18.316-2.851.007-.454-.465-6.833-1.415-17.137l21.043.732.075.001c.54 3.443.726 7.678.559 12.703-.318 9.556.719 17.346-5.144 21.52-1.366.975-1.757 1.642-6.452 2.006-9.818.76-18.735.538-27.779.142 3.086.15 6.152.283 9.244.364-13.656.649-58.791 1.196-62.73 1.065-4.648-.156-6.996-1.677-7.937-3.916-.755-1.798 3.823-4.152 4.52-4.515.141-.073 7.618-.463 10.43-1.168-2.102-.344 1.631-3.939 4.166-4.665 0 0 3.816-2.743 8.786-3.442l-.114.078c1.185-.153 2.438-.171 3.8.086.755.131 1.61.392 2.563.782Zm24.145 101.676 9.244-6.147 10.342-6.431a4.266 4.266 0 0 0 1.326-1.303l6.011 7.79-20.411 14.955-6.512-8.864Zm-72.34 1.272 26.094 3.882c.196.028.392.039.585.036l-3.482 9.892H21.255l6.12-13.81Z" fill="#F3B175"/><path opacity=".2" d="M103.69 167.608c-3.028.44-6.13.925-9.187 1.5-7.34 1.382-12.96 1.456-16.86 2.221-.79-.408-1.526-1.747-2.21-2.018 4.567-.811 10.023-1.423 15.887-2.836l3.164-21.237c.044-.48.11-1.045.215-1.681.104.481.228.962.373 1.441 3.092 8.507 5.965 16.71 8.618 22.61Zm8.396 17.364c-13.656.649-58.791 1.197-62.73 1.065-4.648-.155-6.996-1.677-7.937-3.916-.756-1.798 3.823-4.152 4.52-4.515.142-.073 1.638-.467 4.488-1.182 1.58.278 3.32.177 4.45.052 3.13.308 6.226.584 9.355.893l2.95 1.165c1.627 2.771 14.233 4.879 19.128 5.24 1.501.106 2.403.184 4.469.25 7.327.306 14.248.765 21.307.948Z" fill="#8C2A00"/><path d="M88.007 105.974c.126.56.323 1.482.033 1.917-.37.645-1.563-.779-1.442-1.87.051-.476.27-.634.536-.662.4-.042.764.223.873.615Zm5.903-.823c.16.556.324 1.482.033 1.917-.37.645-1.562-.779-1.441-1.87.05-.477.27-.634.536-.662.4-.042.764.222.872.615Zm.717 8.581c.226-.091.771-.351.832-.728-.007-.066.016-.17-.024-.233-.154-.186-.576-.04-1.169.089-1.054.212-1.93.203-1.93.203s.336.639.52.788c.389.498 1.416.019 1.771-.119Z" fill="#482D1F"/><path d="M85.24 103.671c-.34-.032-.515-.417-.306-.675.271-.298.736-.684 1.398-.787 1.357-.21 2.939.432 1.524 1.052-.897.431-1.973.443-2.616.41Zm9.656-16.038c-2.6-1.392-4.426-1.778-4.727-4.64-.522-4.968 3.75-9.49 9.54-10.099 5.79-.609 10.907 2.925 11.429 7.893.315 3-1.119 4.838-3.58 6.749 1.439-.146 2.584.886 3.929 1.382.49.185 1.648.635 2.736 1.7 3.101 2.94 2.987 7.298 2.987 8.578-.134 3.854-1.905 6.533-2.61 7.516-1.64 2.329-3.152 3.584-4.537 3.766-.803-1.161-1.436-2.269-1.898-3.324.581-.26 1.395-.742 2.004-1.626.876-1.271 1.223-3.093.379-4.722-.771-1.57-2.568-2.66-4.152-2.359-.891.162-1.538.735-1.631.812-.798.749-1.282 1.713-1.45 2.084l.005-.147c-1.594-.438-4.227-1.475-6.53-3.86a14.266 14.266 0 0 1-1.9-2.394c-1.29.54-3.41 1.168-5.956.964-.903-.071-1.707-.447-2.426-.643l-.007-.01c-.044-.096.375-.68.368-.747 1.973-3.406 5.662-6.52 8.027-6.873Zm-3.199 15.359c-.34-.032-.515-.418-.273-.679a2.428 2.428 0 0 1 1.431-.791c1.358-.21 2.943.466 1.524 1.053-.93.434-2.006.447-2.682.417Z" fill="#924600"/><path d="m103.716 118.871 2.925-3.897-3.428 1.888.503 2.009Zm-13.95-11.126-.004-.049v.024l.004.025Zm-.029 3.558.002.037c.038.364.322.675.691.697.067 0 .105-.001.142-.003.355-.014.608-.037 1.514-.133a.335.335 0 1 0-.07-.666c-.89.094-1.136.116-1.47.13l-.105.003c.007-.001-.025-.036-.034-.085l.025-3.582-.004-.049-.272-1.959a.334.334 0 1 0-.663.093l.27 1.934-.026 3.583Z" fill="#482D1F"/><path d="M150.158 181.8H28.843c-.466 0-.843 1.119-.843 2.5s.377 2.5.843 2.5h121.315c.465 0 .842-1.119.842-2.5s-.377-2.5-.842-2.5Z" fill="#858585"/><path d="m54.55 175.794-4.267-33.841c-.618-4.929-1.105-10.351-3-10.351l-22.309 1.664c-1.895 0-1.461 4.758-.843 9.687l4.799 38.845h65.489c1.115 0 1.694-2.353 1.694-5.253v-.751H54.55Z" fill="url(#b)"/></g><path d="M116.856 15.754c-.968-2.33-2.93-4.842-4.465-5.636a23.12 23.12 0 0 1 2.251 6.756l.007.034c-2.516-6.27-6.784-8.804-10.271-14.311-.179-.28-.354-.563-.523-.849a7.248 7.248 0 0 1-.244-.462 4.04 4.04 0 0 1-.347-.92.055.055 0 0 0-.037-.02.081.081 0 0 0-.044 0l-.01.007-.014.01.007-.017c-5.592 3.273-7.49 9.334-7.66 12.366-2.234.153-4.37.977-6.129 2.363a6.69 6.69 0 0 0-.577-.438 10.32 10.32 0 0 1-.06-5.44 16.484 16.484 0 0 0-5.359 4.143h-.01c-.883-1.12-.822-4.808-.77-5.579-.259.106-.51.238-.74.397a15.817 15.817 0 0 0-2.177 1.865 19.452 19.452 0 0 0-2.081 2.495 18.793 18.793 0 0 0-2.988 6.743l-.028.146a32.433 32.433 0 0 0-.22 1.392l-.007.048a21.64 21.64 0 0 0-.36 3.066v.115a22.26 22.26 0 0 0 44.197 3.766l.102-.863a22.902 22.902 0 0 0-1.446-11.18l.003.003ZM91.201 33.179c.102.05.2.102.305.15l.017.01a11.36 11.36 0 0 1-.322-.16Zm23.448-16.264v-.02l.003.024h-.003v-.004Z" fill="url(#c)"/><path d="M116.856 15.754c-.968-2.326-2.93-4.842-4.465-5.637a23.121 23.121 0 0 1 2.254 6.757v.044a20.151 20.151 0 0 1-.689 15.024c-2.553 5.474-8.726 11.086-18.392 10.811-10.441-.299-19.642-8.047-21.357-18.199-.316-1.596 0-2.41.156-3.71a16.572 16.572 0 0 0-.356 3.072v.115a22.263 22.263 0 0 0 44.193 3.762c.038-.285.068-.57.102-.862a22.881 22.881 0 0 0-1.443-11.18h-.003v.003Z" fill="url(#d)"/><path d="M116.856 15.754c-.968-2.326-2.93-4.842-4.465-5.637a23.121 23.121 0 0 1 2.254 6.757v.044a20.151 20.151 0 0 1-.689 15.024c-2.553 5.474-8.726 11.086-18.392 10.811-10.441-.299-19.642-8.047-21.357-18.199-.316-1.596 0-2.41.156-3.71a16.572 16.572 0 0 0-.356 3.072v.115a22.263 22.263 0 0 0 44.193 3.762c.038-.285.068-.57.102-.862a22.881 22.881 0 0 0-1.443-11.18h-.003v.003Z" fill="url(#e)"/><path d="m106.036 18.367.135.102a12.1 12.1 0 0 0-2.064-2.7c-6.92-6.92-1.813-15-.951-15.415l.007-.013c-5.592 3.276-7.49 9.337-7.663 12.366.261-.017.52-.038.78-.038a11.233 11.233 0 0 1 9.756 5.694v.004Z" fill="url(#f)"/><path d="M96.294 19.753c-.034.55-1.993 2.462-2.676 2.462-6.328 0-7.357 3.826-7.357 3.826.278 3.226 2.526 5.884 5.242 7.283.122.068.251.123.374.18.22.099.438.187.655.269a9.947 9.947 0 0 0 2.896.556c11.096.523 13.242-13.265 5.239-17.268a7.69 7.69 0 0 1 5.365 1.303 11.236 11.236 0 0 0-9.752-5.697c-.264 0-.523.024-.78.04a11.15 11.15 0 0 0-6.13 2.36c.34.29.724.673 1.529 1.467 1.51 1.49 5.385 3.032 5.395 3.212v.007Z" fill="url(#g)"/><path d="M96.294 19.753c-.034.55-1.993 2.462-2.676 2.462-6.328 0-7.357 3.826-7.357 3.826.278 3.226 2.526 5.884 5.242 7.283.122.068.251.123.374.18.22.099.438.187.655.269a9.947 9.947 0 0 0 2.896.556c11.096.523 13.242-13.265 5.239-17.268a7.69 7.69 0 0 1 5.365 1.303 11.236 11.236 0 0 0-9.752-5.697c-.264 0-.523.024-.78.04a11.15 11.15 0 0 0-6.13 2.36c.34.29.724.673 1.529 1.467 1.51 1.49 5.385 3.032 5.395 3.212v.007Z" fill="url(#h)"/><path d="M88.334 14.335c.18.115.326.214.458.305a10.323 10.323 0 0 1-.064-5.439 16.481 16.481 0 0 0-5.358 4.143c.108-.007 3.337-.065 4.964.99Z" fill="url(#i)"/><path d="M74.199 24.557c1.718 10.149 10.92 17.9 21.36 18.196 9.666.271 15.839-5.338 18.389-10.811a20.16 20.16 0 0 0 .693-15.024v-.041l.006.034c.788 5.16-1.833 10.152-5.935 13.534l-.013.027c-7.986 6.509-15.632 3.925-17.177 2.872a11.632 11.632 0 0 1-.323-.16c-4.658-2.227-6.583-6.467-6.17-10.107a5.718 5.718 0 0 1-5.272-3.318 8.4 8.4 0 0 1 8.183-.329 11.103 11.103 0 0 0 8.359.33c-.01-.184-3.884-1.725-5.395-3.213-.805-.794-1.189-1.178-1.528-1.466a6.7 6.7 0 0 0-.577-.435 32.561 32.561 0 0 0-.459-.306c-1.623-1.052-4.852-.998-4.957-.994h-.01c-.883-1.12-.822-4.805-.77-5.575-.262.101-.51.237-.744.393a15.84 15.84 0 0 0-2.173 1.868 19.422 19.422 0 0 0-2.092 2.489 18.805 18.805 0 0 0-2.988 6.743c-.01.044-.801 3.5-.41 5.297l.003-.004Z" fill="url(#j)"/><path d="M104.103 15.77a12.114 12.114 0 0 1 2.071 2.7c.119.091.238.183.333.271 5.046 4.652 2.401 11.229 2.207 11.694 4.098-3.375 6.716-8.373 5.932-13.53-2.52-6.279-6.791-8.811-10.271-14.319-.18-.28-.354-.562-.523-.849a7.264 7.264 0 0 1-.245-.461 4.084 4.084 0 0 1-.346-.92.057.057 0 0 0-.037-.02.078.078 0 0 0-.044 0l-.011.006-.013.01c-.863.408-5.97 8.492.951 15.408v.01h-.004Z" fill="url(#k)"/><path d="M106.508 18.744a4.69 4.69 0 0 0-.336-.271l-.136-.102a7.684 7.684 0 0 0-5.368-1.304c8.006 4.003 5.857 17.788-5.24 17.269a9.9 9.9 0 0 1-2.895-.557 11.78 11.78 0 0 1-1.026-.448l.014.01c1.545 1.056 9.188 3.636 17.18-2.872l.01-.027c.197-.466 2.842-7.043-2.207-11.694l.004-.004Z" fill="url(#l)"/><path d="M86.261 26.039s1.026-3.827 7.358-3.827c.683 0 2.642-1.911 2.676-2.465-2.722.986-5.72.867-8.356-.329a8.39 8.39 0 0 0-8.183.33 5.717 5.717 0 0 0 5.27 3.317c-.411 3.64 1.514 7.877 6.169 10.108l.309.152c-2.717-1.405-4.964-4.06-5.243-7.283v-.003Z" fill="url(#m)"/><path d="M116.856 15.754c-.968-2.33-2.93-4.842-4.468-5.636a23.121 23.121 0 0 1 2.254 6.757l.007.033c-2.519-6.27-6.784-8.804-10.271-14.31-.179-.28-.354-.564-.523-.85a7.273 7.273 0 0 1-.248-.462 4.084 4.084 0 0 1-.346-.92.057.057 0 0 0-.034-.02.078.078 0 0 0-.044 0l-.01.007-.017.01.01-.017c-5.592 3.273-7.49 9.334-7.66 12.366.258-.017.516-.037.781-.037a11.23 11.23 0 0 1 9.751 5.693 7.68 7.68 0 0 0-5.364-1.303c8.003 4.006 5.857 17.788-5.24 17.272a9.899 9.899 0 0 1-2.895-.56c-.222-.083-.44-.173-.656-.269-.125-.058-.251-.112-.373-.18l.013.01a12.07 12.07 0 0 1-.322-.16l.305.15c-2.716-1.402-4.96-4.057-5.242-7.28 0 0 1.029-3.83 7.358-3.83.686 0 2.645-1.91 2.679-2.464-.01-.18-3.885-1.722-5.396-3.209-.804-.794-1.188-1.178-1.528-1.467a6.756 6.756 0 0 0-.577-.434 10.321 10.321 0 0 1-.06-5.443 16.48 16.48 0 0 0-5.359 4.142h-.01c-.883-1.12-.818-4.804-.767-5.575-.262.102-.51.238-.747.394a16.233 16.233 0 0 0-2.173 1.864c-.76.77-1.46 1.606-2.081 2.496v.003-.003a18.801 18.801 0 0 0-2.988 6.743l-.028.146c-.044.197-.23 1.188-.258 1.405A26.351 26.351 0 0 0 74 23.92v.115a22.263 22.263 0 0 0 44.197 3.762l.102-.859a22.896 22.896 0 0 0-1.446-11.184h.003Zm-2.207 1.144v.02-.023.003Z" fill="url(#n)"/><path fill-rule="evenodd" clip-rule="evenodd" d="M145.735 41.46a3.502 3.502 0 0 1 4.053-2.839 3.502 3.502 0 0 1 2.838 4.053l-.738 4.185-6.891-1.215.738-4.185Zm-4.183 3.577.738-4.185a7.004 7.004 0 0 1 8.106-5.676 7.005 7.005 0 0 1 5.676 8.106l-.738 4.185 2.659.469a1.545 1.545 0 0 1 1.243 1.19c.044.199.049.404.013.604l-2.586 14.67a1.55 1.55 0 0 1-1.795 1.256l-19.099-3.368a1.547 1.547 0 0 1-1.257-1.794l2.587-14.669a1.55 1.55 0 0 1 1.795-1.257l2.658.469Zm6.216 9.167a2.231 2.231 0 0 0 1.865-1.814 2.236 2.236 0 0 0-1.82-2.565 2.237 2.237 0 0 0-2.587 1.788 2.23 2.23 0 0 0 1.132 2.342l-2.172 3.94a1.228 1.228 0 0 0 .862 1.801l1.988.35a1.228 1.228 0 0 0 1.426-1.398l-.694-4.444Z" fill="url(#o)"/><path fill-rule="evenodd" clip-rule="evenodd" d="m34.653 37.223 10.72-3.14a4.482 4.482 0 0 1 5.545 3.033l7.535 25.73-8.975-2.027-6.25 6.486-7.534-25.731-4.074 1.193a4.482 4.482 0 0 1 3.033-5.544Zm17.675 13.656c.278-.446-.093-1.037-.626-.947l-2.318.464a.546.546 0 0 1-.596-.238l-1.407-1.879a.606.606 0 0 0-1.09.293l-.276 2.331a.625.625 0 0 1-.395.505l-2.232.785c-.507.19-.556.894-.067 1.134l2.215 1.13a.668.668 0 0 1 .334.548l.1 2.548c.016.553.7.821 1.065.404l1.542-1.768a.626.626 0 0 1 .644-.173l2.222.757c.519.152.982-.397.718-.884l-1.19-2.255a.668.668 0 0 1 .013-.641l1.344-2.114Z" fill="url(#p)"/><path d="m180.376 80.545-2.14-1.846-3.269 3.79a1.412 1.412 0 1 0 2.14 1.846l3.269-3.79Z" fill="#B8B8B8"/><path d="m180.264 77.535.971.837-1.441 1.671-.972-.838 1.442-1.67Z" fill="#B8B8B8"/><path opacity=".2" d="M179.663 79.767c.543-.564.681-1.364.399-2l.203-.234.972.839-1.44 1.67-.219-.19c.024-.028.056-.057.085-.085Z" fill="#000"/><path fill-rule="evenodd" clip-rule="evenodd" d="M180.212 77.597a6.041 6.041 0 0 1-.092-8.15 6.036 6.036 0 0 1 7.936-.933 6.035 6.035 0 1 1-7.844 9.083Zm.183-3.813a4.235 4.235 0 1 0 8.448-.622 4.235 4.235 0 0 0-8.448.622Z" fill="url(#q)"/><path d="M178.237 78.698a1.41 1.41 0 0 0 .195 1.986 1.415 1.415 0 0 0 1.944-.14l-2.139-1.846Z" fill="#B8B8B8"/><path d="M4.364 73.733h.681c.17-.725.427-1.364.81-1.96l-.469-.47c-.511-.51-.511-1.363 0-1.917.512-.511 1.364-.511 1.918 0l.469.47c.596-.384 1.278-.683 1.96-.81v-.682c0-.725.596-1.364 1.364-1.364.724 0 1.363.597 1.363 1.364v.681c.724.17 1.364.427 1.96.81l.512-.469c.511-.511 1.363-.511 1.917 0 .512.512.512 1.364 0 1.918l-.468.469c.383.596.681 1.278.81 1.96h.68c.725 0 1.364.596 1.364 1.364 0 .724-.596 1.363-1.363 1.363h-.682a6.146 6.146 0 0 1-.81 1.96l.427.512c.51.511.51 1.363 0 1.917-.512.512-1.364.512-1.918 0l-.469-.469c-.596.384-1.278.682-1.96.81v.682c0 .724-.597 1.364-1.364 1.364a1.373 1.373 0 0 1-1.363-1.364v-.682a6.146 6.146 0 0 1-1.96-.81l-.47.47c-.51.51-1.363.51-1.917 0-.511-.512-.511-1.364 0-1.918l.47-.47c-.384-.596-.683-1.278-.81-1.96h-.682A1.373 1.373 0 0 1 3 75.14c0-.767.597-1.406 1.364-1.406Zm6.733 5.625a4.274 4.274 0 0 0 4.26-4.261 4.274 4.274 0 0 0-4.26-4.262 4.274 4.274 0 0 0-4.262 4.262 4.274 4.274 0 0 0 4.262 4.26Z" fill="url(#r)"/><path d="M11.096 79.358a4.274 4.274 0 0 0 4.262-4.262 4.274 4.274 0 0 0-4.262-4.261 4.274 4.274 0 0 0-4.26 4.261 4.274 4.274 0 0 0 4.26 4.261Zm0-7.245a2.965 2.965 0 0 1 2.983 2.983 2.965 2.965 0 0 1-2.983 2.983 2.965 2.965 0 0 1-2.982-2.983 2.965 2.965 0 0 1 2.982-2.983Z" fill="#9F9FAD"/><defs><radialGradient id="d" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(112.479 5.513) scale(46.4065)"><stop offset=".129" stop-color="#FFBD4F"/><stop offset=".186" stop-color="#FFAC31"/><stop offset=".247" stop-color="#FF9D17"/><stop offset=".283" stop-color="#FF980E"/><stop offset=".403" stop-color="#FF563B"/><stop offset=".467" stop-color="#FF3750"/><stop offset=".71" stop-color="#F5156C"/><stop offset=".782" stop-color="#EB0878"/><stop offset=".86" stop-color="#E50080"/></radialGradient><radialGradient id="e" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(95.248 24.466) scale(46.4065)"><stop offset=".3" stop-color="#960E18"/><stop offset=".351" stop-color="#B11927" stop-opacity=".74"/><stop offset=".435" stop-color="#DB293D" stop-opacity=".343"/><stop offset=".497" stop-color="#F5334B" stop-opacity=".094"/><stop offset=".53" stop-color="#FF3750" stop-opacity="0"/></radialGradient><radialGradient id="f" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(100.993 -4.827) scale(33.6161)"><stop offset=".132" stop-color="#FFF44F"/><stop offset=".252" stop-color="#FFDC3E"/><stop offset=".506" stop-color="#FF9D12"/><stop offset=".526" stop-color="#FF980E"/></radialGradient><radialGradient id="g" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(90.08 36.526) scale(22.0949)"><stop offset=".353" stop-color="#3A8EE6"/><stop offset=".472" stop-color="#5C79F0"/><stop offset=".669" stop-color="#9059FF"/><stop offset="1" stop-color="#C139E6"/></radialGradient><radialGradient id="h" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(11.38846 -2.75348 3.22363 13.33303 97.495 20.483)"><stop offset=".206" stop-color="#9059FF" stop-opacity="0"/><stop offset=".278" stop-color="#8C4FF3" stop-opacity=".064"/><stop offset=".747" stop-color="#7716A8" stop-opacity=".45"/><stop offset=".975" stop-color="#6E008B" stop-opacity=".6"/></radialGradient><radialGradient id="i" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(94.673 3.789) scale(15.8977)"><stop stop-color="#FFE226"/><stop offset=".121" stop-color="#FFDB27"/><stop offset=".295" stop-color="#FFC82A"/><stop offset=".502" stop-color="#FFA930"/><stop offset=".732" stop-color="#FF7E37"/><stop offset=".792" stop-color="#FF7139"/></radialGradient><radialGradient id="j" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(107.307 -6.551) scale(67.8295)"><stop offset=".113" stop-color="#FFF44F"/><stop offset=".456" stop-color="#FF980E"/><stop offset=".622" stop-color="#FF5634"/><stop offset=".716" stop-color="#FF3647"/><stop offset=".904" stop-color="#E31587"/></radialGradient><radialGradient id="k" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="rotate(83.976 52.385 55.089) scale(49.7065 32.622)"><stop stop-color="#FFF44F"/><stop offset=".06" stop-color="#FFE847"/><stop offset=".168" stop-color="#FFC830"/><stop offset=".304" stop-color="#FF980E"/><stop offset=".356" stop-color="#FF8B16"/><stop offset=".455" stop-color="#FF672A"/><stop offset=".57" stop-color="#FF3647"/><stop offset=".737" stop-color="#E31587"/></radialGradient><radialGradient id="l" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(94.675 9.533) scale(42.3403)"><stop offset=".137" stop-color="#FFF44F"/><stop offset=".48" stop-color="#FF980E"/><stop offset=".592" stop-color="#FF5634"/><stop offset=".655" stop-color="#FF3647"/><stop offset=".904" stop-color="#E31587"/></radialGradient><radialGradient id="m" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(105.588 11.833) scale(46.3434)"><stop offset=".094" stop-color="#FFF44F"/><stop offset=".231" stop-color="#FFE141"/><stop offset=".509" stop-color="#FFAF1E"/><stop offset=".626" stop-color="#FF980E"/></radialGradient><linearGradient id="b" x1="24" y1="132" x2="22.896" y2="176.973" gradientUnits="userSpaceOnUse"><stop stop-color="#E0E0E0"/><stop offset="1" stop-color="#A9A9A9"/></linearGradient><linearGradient id="c" x1="113.909" y1="7.456" x2="76.954" y2="43.11" gradientUnits="userSpaceOnUse"><stop offset=".048" stop-color="#FFF44F"/><stop offset=".111" stop-color="#FFE847"/><stop offset=".225" stop-color="#FFC830"/><stop offset=".368" stop-color="#FF980E"/><stop offset=".401" stop-color="#FF8B16"/><stop offset=".462" stop-color="#FF672A"/><stop offset=".534" stop-color="#FF3647"/><stop offset=".705" stop-color="#E31587"/></linearGradient><linearGradient id="n" x1="113.461" y1="7.269" x2="82.02" y2="38.713" gradientUnits="userSpaceOnUse"><stop offset=".167" stop-color="#FFF44F" stop-opacity=".8"/><stop offset=".266" stop-color="#FFF44F" stop-opacity=".634"/><stop offset=".489" stop-color="#FFF44F" stop-opacity=".217"/><stop offset=".6" stop-color="#FFF44F" stop-opacity="0"/></linearGradient><linearGradient id="o" x1="137.223" y1="44.267" x2="159.641" y2="52.954" gradientUnits="userSpaceOnUse"><stop stop-color="#E3C6FF"/><stop offset="1" stop-color="#BC9BFF"/></linearGradient><linearGradient id="p" x1="40.013" y1="35.653" x2="48.804" y2="65.672" gradientUnits="userSpaceOnUse"><stop stop-color="#D7C1FF"/><stop offset=".583" stop-color="#C09BFF"/></linearGradient><linearGradient id="q" x1="184.174" y1="67.454" x2="185.061" y2="79.489" gradientUnits="userSpaceOnUse"><stop stop-color="#B8B8B8"/><stop offset="1" stop-color="#939393"/></linearGradient><linearGradient id="r" x1="11.118" y1="67" x2="11.118" y2="83.236" gradientUnits="userSpaceOnUse"><stop stop-color="#E0E0E6"/><stop offset="1" stop-color="#AFAFBA"/></linearGradient><clipPath id="a"><path fill="#fff" transform="translate(6 72)" d="M0 0h181v114H0z"/></clipPath></defs></svg>
diff --git a/browser/components/newtab/data/content/assets/pocket-onboarding.avif b/browser/components/newtab/data/content/assets/pocket-onboarding.avif
new file mode 100644
index 0000000000..9bd1b3e524
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/pocket-onboarding.avif
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/pocket-onboarding@2x.avif b/browser/components/newtab/data/content/assets/pocket-onboarding@2x.avif
new file mode 100644
index 0000000000..6817e85f2f
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/pocket-onboarding@2x.avif
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/pocket-swoosh.svg b/browser/components/newtab/data/content/assets/pocket-swoosh.svg
new file mode 100644
index 0000000000..0d81c7c453
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/pocket-swoosh.svg
@@ -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/. -->
+<svg width="272" height="221" viewBox="0 0 272 221" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M198.149 217.506C197.027 216.807 149.258 224.525 138.051 218.986C128.922 214.474 157.583 197.26 145.113 191.397C117.229 178.287 84.755 163.892 64.5172 157.556C4.66231 138.817 -3.24386 110.107 0.935229 88.348C5.11432 66.5887 18.2486 80.7262 34.9152 65.6889C51.5819 50.6516 104.716 18.9837 151.432 20.6766C198.149 22.3695 221.034 23.4152 223.074 41.0915C225.114 58.7678 212.726 69.4233 186.059 64.4441C159.393 59.4649 125.96 54.8342 131.034 48.6101C136.109 42.3363 137.092 40.245 145.898 41.0915C149.707 41.4576 140.907 45.1279 146.728 43.0367C152.549 40.9454 143.027 37.6002 138.051 37.1521C133.076 36.7537 146.728 39.6303 120.639 48.6101C93.2259 62.3528 76.5072 66.4358 72.7758 83.166C69.0445 99.8963 94.0196 132.46 127.85 149.838C161.681 167.216 210.686 192.51 208.547 196.742C206.457 200.975 198.149 217.506 198.149 217.506Z" fill="#F9BFD1"/>
+<path d="M205.746 200.389C205.945 200.041 90.7455 153.648 52.4781 140.797C14.2106 127.945 -1.18287 102.054 4.62425 81.3135C10.4314 60.573 24.4848 48.7046 69.0061 31.8343C113.527 14.9639 191.105 8.46391 207.781 22.7044C224.458 36.945 242.624 58.1321 222.324 66.4184C222.324 66.4184 153.234 65.6741 144.201 60.2161C135.168 54.8077 122.459 48.2869 127.522 44.5655C132.584 40.8441 161.225 49.3992 180.582 50.6397C199.939 51.8802 214.929 45.3801 191.253 38.4335C167.578 31.4869 141.024 31.8839 119.682 38.4335C103.7 43.3458 89.8521 52.2771 74.9125 61.8535C59.9728 71.4299 45.4301 82.1475 47.9118 100.01C50.3935 117.873 94.7162 117.923 122.61 128.342C150.504 138.762 213.291 185.404 213.291 185.404L205.746 200.389Z" fill="#EF4056"/>
+<path d="M209.225 191.228C207.134 188.504 145.073 153.09 82.9625 136.052C20.8518 119.064 -2.24359 101.58 8.1082 70.5247C15.8223 47.3945 10.0023 68.8903 27.9189 55.2201C45.8354 41.55 83.0621 7.86999 143.929 10.4455C204.795 13.021 229.132 17.4787 236.647 29.5144C244.162 41.55 253.717 58.9348 236.647 62.2533C219.576 65.5718 183.594 68.1473 163.438 63.8878C140.096 58.9844 114.225 47.2717 117.211 45.5877C117.211 45.5877 160.932 53.89 169.509 55.2021C178.087 56.5142 210.369 60.5693 215.794 52.2979C221.219 44.0265 207.035 31.9908 183.295 29.5144C159.556 27.0379 131.238 22.7783 95.9023 37.6867C73.208 47.1964 56.2868 60.5693 41.7047 70.5247C23.7383 82.808 25.4305 101.481 48.3736 100.738C71.3168 99.9947 145.72 133.576 163.488 138.974C181.255 144.373 218.929 173.546 218.929 173.546L209.225 191.228Z" fill="#FCB643"/>
+<path d="M213.615 176.342C213.615 176.342 159 138.263 118.647 129.929C78.2938 121.594 19.2055 116.205 10.5087 89.3049C1.21562 60.5587 20.8951 78.0759 20.8951 78.0759C23.9266 76.429 20.8951 66.4976 43.4073 48.3316C66.9134 29.3671 94.3952 17.8886 136.14 17.0901C177.884 16.2916 210.634 18.737 223.654 29.6166C233.692 38.0009 241.942 60.5587 210.335 61.8064C178.729 63.054 133.624 51.4307 123.139 45.9908C112.603 40.551 109.227 51.1025 155.819 67.6454C179.574 73.4845 232.053 80.6211 243.681 66.3978C255.31 52.1744 267.784 21.6815 218.684 11.251C169.585 0.820553 107.266 -2.12393 69.597 11.251C31.9276 24.626 17.5158 48.0322 15.8759 65.1501C14.2359 82.2681 27.6538 98.9368 41.7674 101.632C55.9307 104.327 121.181 104.826 139.519 110.266C157.857 115.705 199.353 147.745 205.515 155.88C211.677 164.015 218.635 173.547 218.635 173.547L213.615 176.342Z" fill="#1CB0A8"/>
+<path d="M202.82 146.773C190.024 133.777 166.02 102.605 122.971 90.7038C80.7161 79.0517 51.7524 81.9896 39.6015 81.5414C-11.5313 79.5496 2.55382 51.0168 9.29879 41.5059C16.0438 31.995 44.2139 5.20501 128.476 0.673622C213.185 -3.90756 273.791 15.2637 271.311 46.4356C268.831 77.6076 212.342 88.214 176.633 80.2966C122.971 68.3983 104.917 48.7908 107.149 45.9026C109.331 42.9647 121.033 49.2374 138.241 57.6725C155.449 66.1076 244.331 84.8777 250.134 51.5148C255.936 18.1518 198.654 9.83599 147.62 8.98946C100.604 8.24253 54.5793 27.3142 31.3191 44.4438C21.1025 51.9629 -8.55554 95.9821 54.5793 106.987C117.714 117.992 137.255 109.078 169.145 130.341C201.034 151.604 215.891 172.154 217.153 170.526C218.415 168.898 215.615 159.77 202.82 146.773Z" fill="#95D2FF"/>
+<path d="M138.128 44.9027C124.799 45.702 103.087 55.76 93.8965 60.689C93.8965 58.4909 95.1659 53.0556 100.244 48.8992C106.591 43.7037 120.079 35.1111 138.128 35.5108C156.178 35.9104 154.79 43.9035 138.128 44.9027Z" fill="#FFC0D1"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/remote/mountain.svg b/browser/components/newtab/data/content/assets/remote/mountain.svg
new file mode 100644
index 0000000000..4511148820
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/remote/mountain.svg
@@ -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/. -->
+<svg width="115" height="89" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M86.676 83.103c15.377 0 27.842-12.465 27.842-27.842 0-15.376-12.465-27.842-27.842-27.842-15.377 0-27.842 12.466-27.842 27.842 0 15.377 12.465 27.842 27.842 27.842z" fill="#FFEA80"/>
+ <path d="M84.457 41.839l-25.25 43.159a2.59 2.59 0 002.232 3.898h50.484a2.589 2.589 0 002.591-2.6 2.594 2.594 0 00-.354-1.298L88.914 41.84a2.586 2.586 0 00-4.457 0z" fill="#7542E5"/>
+ <path d="M114.16 85.031L95.432 52.967l-4.084 4.084-4.653-4.657-4.656 4.657-4.085-4.085L59.21 85.03a2.591 2.591 0 002.233 3.904h50.48a2.59 2.59 0 002.236-3.904z" fill="#7542E5"/>
+ <path d="M86.68 52.394l3.923 3.922a1.037 1.037 0 001.465 0l3.34-3.34-6.493-11.142a2.587 2.587 0 00-4.467 0l-6.509 11.132 3.34 3.34a1.037 1.037 0 001.466 0l3.936-3.912z" fill="#B48EFF"/>
+ <path d="M41.036 17.67L.368 85.014a2.586 2.586 0 002.3 3.893h81.346a2.586 2.586 0 002.295-3.893L45.636 17.67a2.706 2.706 0 00-4.6 0z" fill="#AB71FF"/>
+ <path d="M56.329 35.373L45.635 17.671a2.706 2.706 0 00-4.594 0L30.347 35.373l-.954 1.58 5.56 7.635a1.032 1.032 0 001.67 0l6.68-9.214 6.704 9.214a1.03 1.03 0 001.67 0l5.583-7.663-.931-1.551z" fill="#D9BFFF"/>
+ <path d="M41.086 1.131v14.41a1.13 1.13 0 001.13 1.131h26.507a1.12 1.12 0 001.044-.697 1.14 1.14 0 00-.242-1.236l-6.409-6.403 6.39-6.404c.322-.325.417-.811.243-1.235A1.135 1.135 0 0068.723 0H42.216c-.624 0-1.13.507-1.13 1.131z" fill="#FFA266"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/remote/umbrella.png b/browser/components/newtab/data/content/assets/remote/umbrella.png
new file mode 100644
index 0000000000..3488d135c6
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/remote/umbrella.png
Binary files differ
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..cc004ed607
--- /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 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..2964a31731
--- /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"><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 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/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..fdc021cfeb
--- /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..3ad20825c1
--- /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..d1c3f3f8b1
--- /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..eb187398c7
--- /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.svg b/browser/components/newtab/data/content/tippytop/images/bing-com@2x.svg
new file mode 100644
index 0000000000..1afdee989a
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/bing-com@2x.svg
@@ -0,0 +1,106 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 24.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
+ viewBox="0 0 48 48" enable-background="new 0 0 48 48" xml:space="preserve">
+<g>
+
+ <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="20.4168" y1="-3.0325" x2="39.7202" y2="-14.1773" gradientTransform="matrix(1 0 0 -1 0 18)">
+ <stop offset="0" style="stop-color:#37BDFF"/>
+ <stop offset="0.1832" style="stop-color:#33BFFD"/>
+ <stop offset="0.3576" style="stop-color:#28C5F5"/>
+ <stop offset="0.528" style="stop-color:#15D0E9"/>
+ <stop offset="0.5468" style="stop-color:#12D1E7"/>
+ <stop offset="0.5903" style="stop-color:#1CD2E5"/>
+ <stop offset="0.7679" style="stop-color:#42D8DC"/>
+ <stop offset="0.9107" style="stop-color:#59DBD6"/>
+ <stop offset="1" style="stop-color:#62DCD4"/>
+ </linearGradient>
+ <path fill="url(#SVGID_1_)" d="M39.002,30.234c0,0.437-0.024,0.871-0.071,1.299c-0.282,2.61-1.412,4.969-3.112,6.795
+ c0.214-0.238,0.407-0.493,0.577-0.767c0.131-0.208,0.247-0.425,0.345-0.651c0.036-0.074,0.068-0.152,0.095-0.229
+ c0.032-0.074,0.059-0.152,0.083-0.229c0.027-0.071,0.051-0.146,0.071-0.22c0.021-0.077,0.042-0.154,0.059-0.232
+ c0.003-0.009,0.006-0.018,0.009-0.027c0.018-0.077,0.032-0.154,0.047-0.232c0.015-0.08,0.03-0.161,0.042-0.24
+ c0-0.003,0-0.003,0-0.006c0.012-0.074,0.021-0.149,0.027-0.226c0.018-0.176,0.027-0.35,0.027-0.529
+ c0-1.004-0.277-1.947-0.761-2.749c-0.11-0.187-0.232-0.365-0.365-0.535c-0.157-0.202-0.327-0.392-0.511-0.568
+ c-0.458-0.443-0.993-0.806-1.584-1.061c-0.255-0.113-0.523-0.205-0.796-0.274c-0.003,0-0.009-0.003-0.012-0.003l-0.095-0.032
+ l-1.385-0.475V29.04l-3.623-1.245c-0.012-0.003-0.027-0.003-0.036-0.006l-0.226-0.083c-0.728-0.285-1.332-0.82-1.709-1.501
+ l-1.322-3.374l-1.516-3.864l-0.291-0.746l-0.074-0.152c-0.083-0.202-0.128-0.422-0.128-0.651c0-0.059,0-0.119,0.006-0.172
+ c0.086-0.85,0.808-1.516,1.682-1.516c0.232,0,0.455,0.047,0.657,0.134l6.751,3.462l1.332,0.681
+ c0.705,0.419,1.361,0.913,1.961,1.468c2.176,1.998,3.602,4.797,3.816,7.927C38.99,29.679,39.002,29.955,39.002,30.234z"/>
+
+ <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="9.1031" y1="-19.7528" x2="37.1978" y2="-19.7528" gradientTransform="matrix(1 0 0 -1 0 18)">
+ <stop offset="0" style="stop-color:#39D2FF"/>
+ <stop offset="0.1501" style="stop-color:#38CEFE"/>
+ <stop offset="0.2931" style="stop-color:#35C3FA"/>
+ <stop offset="0.4327" style="stop-color:#2FB0F3"/>
+ <stop offset="0.5468" style="stop-color:#299AEB"/>
+ <stop offset="0.5827" style="stop-color:#2692EC"/>
+ <stop offset="0.7635" style="stop-color:#1A6CF1"/>
+ <stop offset="0.909" style="stop-color:#1355F4"/>
+ <stop offset="1" style="stop-color:#104CF5"/>
+ </linearGradient>
+ <path fill="url(#SVGID_2_)" d="M37.198,34.74c0,0.345-0.032,0.678-0.092,1.002c-0.018,0.086-0.036,0.172-0.056,0.259
+ c-0.039,0.154-0.08,0.303-0.131,0.452c-0.027,0.077-0.054,0.154-0.083,0.229c-0.03,0.077-0.062,0.152-0.095,0.229
+ c-0.098,0.226-0.214,0.443-0.345,0.651c-0.169,0.274-0.363,0.529-0.577,0.767c-0.984,1.088-4.325,3.028-5.556,3.816l-2.733,1.67
+ c-2.003,1.234-3.896,2.107-6.283,2.167c-0.113,0.003-0.223,0.006-0.333,0.006c-0.154,0-0.306-0.003-0.458-0.009
+ c-4.042-0.154-7.567-2.324-9.6-5.531c-0.93-1.465-1.545-3.147-1.753-4.954c0.437,2.47,2.589,4.342,5.184,4.342
+ c0.909,0,1.763-0.229,2.508-0.633c0.006-0.003,0.012-0.006,0.018-0.009l0.267-0.161l1.088-0.642l1.385-0.82v-0.039l0.179-0.107
+ l12.391-7.341l0.954-0.565l0.095,0.032c0.003,0,0.009,0.003,0.012,0.003c0.274,0.068,0.541,0.161,0.796,0.274
+ c0.592,0.255,1.126,0.618,1.584,1.061c0.184,0.176,0.354,0.365,0.511,0.568c0.134,0.169,0.255,0.348,0.365,0.535
+ C36.921,32.793,37.198,33.736,37.198,34.74L37.198,34.74z"/>
+
+ <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="14.2883" y1="-22.2219" x2="14.2883" y2="15.3467" gradientTransform="matrix(1 0 0 -1 0 18)">
+ <stop offset="0" style="stop-color:#1B48EF"/>
+ <stop offset="0.1221" style="stop-color:#1C51F0"/>
+ <stop offset="0.3212" style="stop-color:#1E69F5"/>
+ <stop offset="0.5676" style="stop-color:#2190FB"/>
+ <stop offset="1" style="stop-color:#26B8F4"/>
+ </linearGradient>
+ <path fill="url(#SVGID_3_)" d="M19.557,10.241l-0.004,27.328l-1.385,0.821l-1.089,0.641l-0.268,0.162
+ c-0.004,0-0.012,0.004-0.016,0.008c-0.747,0.402-1.6,0.634-2.51,0.634c-2.595,0-4.744-1.873-5.183-4.342
+ c-0.021-0.114-0.036-0.232-0.049-0.345c-0.016-0.215-0.028-0.427-0.032-0.642V3.749c0-0.971,0.788-1.763,1.763-1.763
+ c0.365,0,0.706,0.114,0.987,0.3l5.39,3.522c0.029,0.024,0.061,0.045,0.094,0.065C18.647,6.824,19.557,8.425,19.557,10.241z"/>
+
+ <linearGradient id="SVGID_4_" gradientUnits="userSpaceOnUse" x1="14.6872" y1="-26.6866" x2="32.0255" y2="-9.3483" gradientTransform="matrix(1 0 0 -1 0 18)">
+ <stop offset="0" style="stop-color:#FFFFFF"/>
+ <stop offset="0.3726" style="stop-color:#FDFDFD"/>
+ <stop offset="0.5069" style="stop-color:#F6F6F6"/>
+ <stop offset="0.6026" style="stop-color:#EBEBEB"/>
+ <stop offset="0.68" style="stop-color:#DADADA"/>
+ <stop offset="0.7463" style="stop-color:#C4C4C4"/>
+ <stop offset="0.805" style="stop-color:#A8A8A8"/>
+ <stop offset="0.8581" style="stop-color:#888888"/>
+ <stop offset="0.9069" style="stop-color:#626262"/>
+ <stop offset="0.9523" style="stop-color:#373737"/>
+ <stop offset="0.9926" style="stop-color:#090909"/>
+ <stop offset="1" style="stop-color:#000000"/>
+ </linearGradient>
+ <path opacity="0.15" fill="url(#SVGID_4_)" enable-background="new " d="M37.198,34.74c0,0.345-0.032,0.678-0.092,1.002
+ c-0.018,0.086-0.036,0.172-0.056,0.259c-0.039,0.154-0.08,0.303-0.131,0.452c-0.027,0.077-0.054,0.154-0.083,0.229
+ c-0.03,0.077-0.062,0.152-0.095,0.229c-0.098,0.226-0.214,0.443-0.345,0.651c-0.169,0.274-0.362,0.529-0.577,0.767
+ c-0.984,1.088-4.325,3.028-5.556,3.816l-2.733,1.67c-2.003,1.234-3.896,2.107-6.283,2.167c-0.113,0.003-0.223,0.006-0.333,0.006
+ c-0.154,0-0.306-0.003-0.458-0.009c-4.042-0.154-7.567-2.324-9.6-5.531c-0.93-1.465-1.545-3.147-1.753-4.954
+ c0.437,2.47,2.589,4.342,5.184,4.342c0.909,0,1.763-0.229,2.508-0.633c0.006-0.003,0.012-0.006,0.018-0.009l0.267-0.161
+ l1.088-0.642l1.385-0.82v-0.039l0.179-0.107l12.391-7.341l0.954-0.565l0.095,0.032c0.003,0,0.009,0.003,0.012,0.003
+ c0.274,0.068,0.541,0.161,0.796,0.274c0.592,0.255,1.126,0.618,1.584,1.061c0.184,0.176,0.354,0.365,0.511,0.568
+ c0.134,0.169,0.255,0.348,0.365,0.535C36.921,32.793,37.198,33.736,37.198,34.74L37.198,34.74z"/>
+
+ <linearGradient id="SVGID_5_" gradientUnits="userSpaceOnUse" x1="14.2883" y1="16.0132" x2="14.2883" y2="-21.8356" gradientTransform="matrix(1 0 0 -1 0 18)">
+ <stop offset="0" style="stop-color:#FFFFFF"/>
+ <stop offset="0.3726" style="stop-color:#FDFDFD"/>
+ <stop offset="0.5069" style="stop-color:#F6F6F6"/>
+ <stop offset="0.6026" style="stop-color:#EBEBEB"/>
+ <stop offset="0.68" style="stop-color:#DADADA"/>
+ <stop offset="0.7463" style="stop-color:#C4C4C4"/>
+ <stop offset="0.805" style="stop-color:#A8A8A8"/>
+ <stop offset="0.8581" style="stop-color:#888888"/>
+ <stop offset="0.9069" style="stop-color:#626262"/>
+ <stop offset="0.9523" style="stop-color:#373737"/>
+ <stop offset="0.9926" style="stop-color:#090909"/>
+ <stop offset="1" style="stop-color:#000000"/>
+ </linearGradient>
+ <path opacity="0.1" fill="url(#SVGID_5_)" enable-background="new " d="M19.557,10.241l-0.004,27.328l-1.385,0.821l-1.089,0.641
+ l-0.268,0.162c-0.004,0-0.012,0.004-0.016,0.008c-0.747,0.402-1.6,0.634-2.51,0.634c-2.595,0-4.744-1.873-5.183-4.342
+ c-0.021-0.114-0.036-0.232-0.049-0.345c-0.016-0.215-0.028-0.427-0.032-0.642V3.749c0-0.971,0.788-1.763,1.763-1.763
+ c0.365,0,0.706,0.114,0.987,0.3l5.39,3.522c0.029,0.024,0.061,0.045,0.094,0.065C18.647,6.824,19.557,8.425,19.557,10.241z"/>
+</g>
+</svg>
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.svg b/browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.svg
new file mode 100644
index 0000000000..a28cc833cd
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.svg
@@ -0,0 +1,12 @@
+<svg fill="none" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg">
+ <path fill="#DE5833" fill-rule="evenodd" d="M64 128c35.346 0 64-28.654 64-64 0-35.346-28.654-64-64-64C28.654 0 0 28.654 0 64c0 35.346 28.654 64 64 64Z" clip-rule="evenodd"/>
+ <path fill="#DDD" fill-rule="evenodd" d="M73 111.75c0-.5.123-.614-1.466-3.782-4.224-8.459-8.47-20.384-6.54-28.075.353-1.397-3.978-51.744-7.04-53.365-3.402-1.813-7.588-4.69-11.418-5.33-1.943-.31-4.49-.164-6.482.105-.353.047-.368.683-.03.798 1.308.443 2.895 1.212 3.83 2.375.178.22-.06.566-.342.577-.882.032-2.482.402-4.593 2.195-.244.207-.041.592.273.53 4.536-.897 9.17-.455 11.9 2.027.177.16.084.45-.147.512-23.694 6.44-19.003 27.05-12.696 52.344 5.619 22.53 7.733 29.792 8.4 32.004a.718.718 0 0 0 .423.467C55.228 118.38 73 118.524 73 113v-1.25Z" clip-rule="evenodd"/>
+ <path fill="#fff" fill-rule="evenodd" d="M122.75 64c0 32.447-26.303 58.75-58.75 58.75S5.25 96.447 5.25 64 31.553 5.25 64 5.25 122.75 31.553 122.75 64Zm-72.46 51.986c-1.624-5.016-6.161-19.551-10.643-37.92l-.447-1.828-.003-.016c-5.425-22.155-9.855-40.252 14.427-45.937.222-.052.33-.317.183-.492-2.786-3.305-8.005-4.388-14.604-2.111-.27.093-.506-.18-.338-.412 1.294-1.784 3.823-3.155 5.072-3.756.258-.124.242-.502-.031-.588a27.848 27.848 0 0 0-3.771-.9c-.37-.059-.404-.693-.032-.743 9.356-1.259 19.125 1.55 24.028 7.726a.325.325 0 0 0 .185.114c17.953 3.855 19.239 32.235 17.17 33.528-.407.255-1.714.108-3.438-.085-6.985-.781-20.818-2.329-9.401 18.948.113.21-.037.488-.272.525-6.416.997 1.755 21.034 7.812 34.323 23.815-5.52 41.563-26.868 41.563-52.362 0-29.685-24.065-53.75-53.75-53.75S10.25 34.315 10.25 64c0 24.947 16.995 45.924 40.04 51.986Z" clip-rule="evenodd"/>
+ <path fill="#3CA82B" d="M84.28 90.698c-1.367-.633-6.621 3.135-10.11 6.028-.728-1.031-2.103-1.78-5.203-1.242-2.713.472-4.211 1.126-4.88 2.254-4.283-1.623-11.488-4.13-13.229-1.71-1.902 2.646.476 15.161 3.003 16.786 1.32.849 7.63-3.208 10.926-6.005.532.749 1.388 1.178 3.148 1.137 2.662-.062 6.979-.681 7.649-1.921.04-.075.075-.164.105-.266 3.388 1.266 9.35 2.606 10.682 2.406 3.47-.521-.484-16.723-2.09-17.467Z"/>
+ <path fill="#4CBA3C" d="M74.49 97.097c.144.256.26.526.358.8.483 1.352 1.27 5.648.674 6.709-.595 1.062-4.459 1.574-6.843 1.615-2.384.041-2.92-.831-3.403-2.181-.387-1.081-.577-3.621-.572-5.075-.098-2.158.69-2.916 4.334-3.506 2.696-.436 4.121.071 4.944.94 3.828-2.857 10.215-6.889 10.838-6.152 3.106 3.674 3.499 12.42 2.826 15.939-.22 1.151-10.505-1.139-10.505-2.38 0-5.152-1.337-6.565-2.65-6.71Zm-22.53-1.609c.843-1.333 7.674.325 11.424 1.993 0 0-.77 3.491.456 7.604.359 1.203-8.627 6.558-9.8 5.637-1.355-1.065-3.85-12.432-2.08-15.234Z"/>
+ <path fill="#FC3" fill-rule="evenodd" d="M55.269 68.406c.553-2.403 3.127-6.932 12.321-6.822 4.648-.019 10.422-.002 14.25-.436a51.312 51.312 0 0 0 12.726-3.095c3.98-1.519 5.392-1.18 5.887-.272.544.999-.097 2.722-1.488 4.309-2.656 3.03-7.431 5.38-15.865 6.076-8.433.698-14.02-1.565-16.425 2.118-1.038 1.589-.236 5.333 7.92 6.512 11.02 1.59 20.072-1.917 21.19.201 1.119 2.118-5.323 6.428-16.362 6.518-11.039.09-17.934-3.865-20.379-5.83-3.102-2.495-4.49-6.133-3.775-9.279Z" clip-rule="evenodd"/>
+ <g fill="#14307E" opacity=".8">
+ <path d="M69.327 42.127c.616-1.008 1.981-1.786 4.216-1.786 2.234 0 3.285.889 4.013 1.88.148.202-.076.44-.306.34a59.869 59.869 0 0 1-.168-.073c-.817-.357-1.82-.795-3.54-.82-1.838-.026-2.997.435-3.727.831-.246.134-.634-.133-.488-.372Zm-25.157 1.29c2.17-.907 3.876-.79 5.081-.504.254.06.43-.213.227-.377-.935-.755-3.03-1.692-5.76-.674-2.437.909-3.585 2.796-3.592 4.038-.002.292.6.317.756.07.42-.67 1.12-1.646 3.289-2.553Z"/>
+ <path fill-rule="evenodd" d="M75.44 55.92a3.47 3.47 0 0 1-3.474-3.462 3.47 3.47 0 0 1 3.475-3.46 3.47 3.47 0 0 1 3.474 3.46 3.47 3.47 0 0 1-3.475 3.462Zm2.447-4.608a.899.899 0 0 0-1.799 0c0 .494.405.895.9.895.499 0 .9-.4.9-.895Zm-25.464 3.542a4.042 4.042 0 0 1-4.049 4.037 4.045 4.045 0 0 1-4.05-4.037 4.045 4.045 0 0 1 4.05-4.037 4.045 4.045 0 0 1 4.05 4.037Zm-1.193-1.338a1.05 1.05 0 0 0-2.097 0 1.048 1.048 0 0 0 2.097 0Z" clip-rule="evenodd"/>
+ </g>
+</svg> \ No newline at end of file
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..744e2442ff
--- /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..ebea409306
--- /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..3d4ffd15c3
--- /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..82764a0527
--- /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.cn", "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.svg",
+ "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.svg",
+ "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..51a9eb4f8c
--- /dev/null
+++ b/browser/components/newtab/docs/index.rst
@@ -0,0 +1,110 @@
+======================
+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 ``.scss``) 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`` or ``.sys.mjs`` files (system modules)
+---------------------------------------------------
+
+No build step is necessary. Use ``mach`` and run mochitests according to your regular Firefox workflow.
+
+For ``.js``, ``.jsx``, ``.scss``, 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.
+(Using ``mach`` to call ``npm`` and ``node`` commands will ensure you're using the correct versions of Node and npm.)
+
+.. code-block:: shell
+
+ (cd browser/components/newtab && ../../../mach npm install)
+
+
+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 ``.scss`` source files
+in ``browser/components/newtab/content-src`` directory. These files will be compiled into the ``.js`` and ``.css`` files.
+
+
+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
+
+ ./mach npm run bundle --prefix=browser/components/newtab && ./mach build && ./mach run
+
+Continuous development / debugging
+----------------------------------
+Running ``./mach npm run watchmc --prefix=browser/components/newtab`` 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
+`stylelint <https://stylelint.io>`_. 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
+
+ ./mach npm test --prefix=browser/components/newtab
+
+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>`_.
+
+Windows isn't currently supported by ``npm test``
+(`path/invocation difference <https://bugzilla.mozilla.org/show_bug.cgi?id=1737419>`_).
+To run newtab specific tests that aren't covered by ``mach lint`` and
+``mach test``:
+
+.. code-block:: shell
+
+ ./mach npm run lint:stylelint --prefix=browser/components/newtab
+ ./mach npm run testmc:build --prefix=browser/components/newtab
+ ./mach npm run testmc:unit --prefix=browser/components/newtab
+
+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
+
+ ./mach npm test --prefix=browser/components/newtab &&
+ ./mach npm run debugcoverage --prefix=browser/components/newtab
+
+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..35bb084f38
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/data_dictionary.md
@@ -0,0 +1,360 @@
+# 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,
+ "window_inner_width": 1000,
+ "window_inner_height" 900
+}
+```
+
+```js
+{
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "pocket",
+ "page": "unknown",
+ "user_prefs": 7,
+ "window_inner_width": 1000,
+ "window_inner_height" 900,
+
+ // "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: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``advertiser`` | [Optional] An identifier for the advertiser used by the sponsored TopSites telemetry pings. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``client_id`` | [Required] An identifier for this client. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``card_type`` | [Optional] ("bookmark", "pocket", "trending", "pinned", "search", "spoc", "organic") | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``context_id`` | [Optional] An identifier used by the sponsored TopSites telemetry pings. | :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: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``position`` | [Optional] An integer indicating the placement (1-based) of the sponsored TopSites tile. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``recommender_type`` | [Optional] The type of recommendation that is being shown, if any. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``reporting_url`` | [Optional] A URL used by Mozilla services for impression and click reporting for the sponsored TopSites. | :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`` (AS) | [Required] Either ("recent\_links", "recent\_bookmarks", "frecent\_links", "top\_sites", "spotlight", "sidebar") and indicates what ``action``. | :two: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``source`` (CS) | [Optional] Either "newtab" or "urlbar" indicating the location of the TopSites pings for Contextual Services. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``received_at`` | [Auto populated by Onyx] The time in ms since epoch. | :three: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``tile_id`` | [Optional] An integer identifier for a sponsored TopSites tile. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``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", "card\_type" and "pocket\_logged\_in\_status" 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: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| 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: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``window_inner_width`` | [Optional] Amount of vertical space in pixels available to the window. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``window_inner_height`` | [Optional] Amount of horizontal space in pixels available to the window. | :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) |
++-------------------+------------------------+
+| `showSponsoredTopSites` | 256 (100000000) |
++-------------------+------------------------+
+```
+
+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 | 256 = 511`
+- 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 | 256 = 503`
+
+Likewise, one can use bitwise AND (`&`) for decoding.
+
+- Check if everything is shown, `user_prefs & (1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256)` or `user_prefs == 511`
+- 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..5805f8bf9d
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/data_events.md
@@ -0,0 +1,1417 @@
+# 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 discrete 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.js.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",
+ "IMPRESSION",
+ "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" | "CARDGRID_WIDGET"],
+ "action_position": 2,
+ "value": {
+ // "spoc" for sponsored stories, "organic" for regular stories.
+ "card_type": ["organic" | "spoc" | "topics_widget"],
+ // topic and position only exists if its card_type = "topics_widget"
+ "topic": "entertainment"
+ // The index position of the topic link within the card
+ "position_in_card": 0
+ }
+
+ // 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
+4. Refreshing
+5. 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:
+
+```js
+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,
+ "window_inner_width": 1000,
+ "window_inner_height" 900,
+ "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,
+ "window_inner_width": 1000,
+ "window_inner_height" 900,
+
+ // "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": ["recs_learn_more" | "view_list" | "home_view_list" | "home_topic" | "home_discover" | "save_button" | "home_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"
+}
+```
+
+## Toolbar Badge interaction pings
+
+This reports when a user has seen or clicked a badge/notification in the browser toolbar in a non-PBM window
+
+```js
+{
+ "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.
+
+```js
+{
+ "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.
+
+```js
+{
+ ...
+ "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.
+
+```js
+// 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.
+
+```js
+{
+ "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"
+}
+```
+
+## Spotlight pings
+
+This reports when the user interacts with the Messaging System Spotlight component
+Similar policy applied as for the Infobar messages: client_id is reported in all
+the channels. Currently this is only used in experiments.
+
+```js
+{
+ "experiments": {
+ "exp1": {
+ "branch": "treatment-a"
+ }
+ },
+ "addon_version": "20210115035053",
+ "release_channel": "release",
+ "locale": "en-US",
+ "event": ["IMPRESSION" | "CLICK" | "DISMISS"],
+ "client_id": "c4beb4bf-4feb-9c4e-9587-9323b28c2e50",
+ "version": "93",
+ "message_id": "SPOTLIGHT_MESSAGE_93",
+ "browser_session_id": "93714e76-9919-ca49-b697-5e7c09a1394f"
+}
+```
+
+## ToastNotification pings
+
+This reports when the user interacts with a toast notification: an OS-level
+toast notification UI affordance or a pop-up OS-level window. Similar policy
+applied as for the What's New panel: client_id is reported in all the
+channels. Currently this is only used in experiments.
+
+```js
+{
+ "experiments": {
+ "exp1": {
+ "branch": "treatment-a"
+ }
+ },
+ "addon_version": "20210115035053",
+ "release_channel": "release",
+ "locale": "en-US",
+ "event": ["IMPRESSION"],
+ "client_id": "c4beb4bf-4feb-9c4e-9587-9323b28c2e50",
+ "version": "86",
+ "message_id": "TOAST_NOTIFICATION_EXAMPLE_ID",
+ "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. An attribute
+is a variable inside the JEXL targeting expression that is evaluated client side by the browser.
+
+```js
+{
+ "messaging_experiments",
+ "targeting",
+ "attribute_error", // event
+ "foo", // attribute,
+ "extra_keys": {
+ "source": "message id or experiment slug",
+ },
+},
+{
+ "messaging_experiments",
+ "targeting",
+ "attribute_timeout", // event
+ "bar", // attribute,
+ "extra_keys": {
+ "source": "message id or experiment slug",
+ },
+}
+```
+
+## 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 embedded migration interactions
+
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "experiments": {},
+ "release_channel": "default",
+ "addon_version": "20200330194034",
+ "message_id": "MR_WELCOME_DEFAULT_0_AW_IMPORT_SETTINGS_EMBEDDED",
+ "event": "CLICK_BUTTION",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "event_context": {
+ "page": "about:welcome",
+ "source": ["primary_button" | "migrate_close"],
+ }
+}
+```
+
+### 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"
+ ]
+ },
+ "attribution": {
+ "source": "mozilla.org",
+ "medium": "referral",
+ "campaign": "Firefox-Brand-US-Mozilla-Org",
+ "content": "test-addon@github.io",
+ "experiment": "ua-onboarding",
+ "variation": "chrome",
+ "ua": "firefox"
+ }
+}
+```
+
+## Feature Callout pings
+
+Most interactions and impressions in Feature Callouts are handled by the Onboarding pings above, but since Feature Callouts are inserted into other content, they have some additional capabilities.
+
+### Page event ping for Feature Callouts
+
+Feature Callout messages can include properties to listen for specific events on the host page and perform an action when fired. For example, Feature Callouts pointing to a button can be dismissed when that button is clicked. This metric records the event type, event target, and action.
+
+```js
+{
+ "experiments": {},
+ "locale": "en-US",
+ "version": "107.0a1",
+ "release_channel": "default",
+ "event": "PAGE_EVENT",
+ "event_context": {
+ "action": "DISMISS",
+ "reason": "CLICK",
+ "source": "button.primary#some-button",
+ "page": "about:firefoxview"
+ },
+ "message_id": "FIREFOX_VIEW_TAB_PICKUP_REMINDER",
+ "addon_version": "20221013100028",
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3"
+}
+```
+
+### Feature Callout dismissal
+
+A Feature Callout can be dismissed by clicking its dismiss button directly or pressing the Escape key. With a page event listener, it can also be configured to dismiss the callout when an event in the page happens, such as clicking the target of the callout (see the page event ping above).
+
+```js
+{
+ "experiments": {},
+ "locale": "en-US",
+ "version": "108.0a1",
+ "release_channel": "default",
+ "event": "DISMISS",
+ "event_context": {
+ "source": [
+ "dismiss_button",
+ "KEY_Escape",
+ "PAGE_EVENT:button.primary#some-button"
+ ],
+ "page": ["about:firefoxview", "chrome://browser/content/browser.xhtml"]
+ },
+ "message_id": "some_feature_callout_id",
+ "addon_version": "20221013100028",
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3"
+}
+```
+
+## Sponsored TopSites pings
+
+These record the impression and click pings for the Sponsored TopSites.
+
+### Impression ping for the sponsored TopSites
+
+```js
+{
+ "context_id": "{94642acb-4996-034b-916c-147da723cc41}",
+ "advertiser": "test-advertiser",
+ "tile_id": 42,
+ "source": "newtab",
+ "position": 1,
+ "reporting_url": "https://test.reporting.net/static?id=7RHzfOIWHG7kJnEYgGeuJm7vJ%3DEkiFXwxYIZjF8XgClWfC 8%2B7R4dHQ8zjmENj%3DNwxwz%2FJmdw7R4dHQfz4Z2ZfplnHG3Z5FwqgCfX4ZLafC2mfBINI9HuiF2 z4Z2ZfplnHmcux%3DcvImauiF2zfQlWfpDX7R3%2Bx%3DDuiF2zfLyy",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "release_channel": "default",
+ "experiments": {
+ "exp_id_foo": {
+ "branch": "control"
+ },
+ "exp_id_bar": {
+ "branch": "treatment"
+ }
+ }
+}
+```
+
+### Click ping for the sponsored TopSites
+
+```js
+{
+ "context_id": "{94642acb-4996-034b-916c-147da723cc41}",
+ "tile_id": 42,
+ "source": "newtab",
+ "position": 1,
+ "advertiser": "test-advertiser",
+ "reporting_url": "https://test.reporting.net/ctp?version=16.0.0&key=1598991514900100001.1&ci=15 98991514792.12747&ctag=1598291839300100006&aespFlag=altinst",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "release_channel": "default",
+ "experiments": {
+ "exp_id_foo": {
+ "branch": "control"
+ },
+ "exp_id_bar": {
+ "branch": "treatment"
+ }
+ }
+}
+```
+
+## Glean "newtab" ping
+
+Unlike the other data collections, this is a
+[Glean Ping](https://mozilla.github.io/glean/book/user/pings/index.html)
+that batches events and metadata about newtab sessions.
+
+You can find full documentation about this ping and its contents in
+[its Glean Dictionary entry](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/newtab).
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..c0b1b7b2a6
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/mochitests.md
@@ -0,0 +1,28 @@
+# Mochitests
+
+We use [mochitests](https://firefox-source-docs.mozilla.org/testing/mochitest-plain/) 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://firefox-source-docs.mozilla.org/testing/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://firefox-source-docs.mozilla.org/testing/intermittent/)!
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..cda103b421
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/preferences.md
@@ -0,0 +1,278 @@
+# 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 :searchfox:`toolkit/modules/Preferences.sys.mjs <source/toolkit/modules/Preferences.sys.mjs>`
+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:
+ ```json
+ {
+ "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.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..6f3ef344ee
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/remote_cfr.md
@@ -0,0 +1,82 @@
+# 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 to set up a dev environment.
+
+## Using a dev server for Remote CFR
+
+> Note: Since Novembre 2021, Remote Settings has a proper DEV instance, which is
+> reachable without VPN, but has the same config (openid, multi-signoff, ...)
+> and collections as STAGE/PROD.
+
+**1. Obtain your Bearer Token**
+
+Until [Bug 1630651](https://bugzilla.mozilla.org/show_bug.cgi?id=1630651) happens, the easiest way to obtain your OpenID credentials is to use the admin interface.
+
+1. [Login on the Admin UI](https://remote-settings-dev.allizom.org/v1/admin/) using your LDAP identity
+2. Copy the authentication header (📋 icon in the top bar)
+3. Test your credentials with ``curl``. When reaching out the server root URL with this bearer token you should see a ``user`` entry whose ``id`` field is ``ldap:<you>@mozilla.com``.
+
+```bash
+SERVER=https://settings.dev.mozaws.net/v1
+BEARER_TOKEN="Bearer uLdb-Yafefe....2Hyl5_w"
+
+curl -s ${SERVER}/ -H "Authorization:${BEARER_TOKEN}" | jq .user
+```
+
+**2. Create/Update/Delete CFR entries**
+
+> The messages can also be created manually using the [admin interface](https://settings.dev.mozaws.net/v1/admin/).
+
+In following example, we will create a new entry using the REST API (reusing `SERVER` and `BEARER_TOKEN` from previous step).
+
+```bash
+CID=cfr
+
+# post a message
+curl -X POST ${SERVER}/buckets/main-workspace/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' \
+ -H "Authorization:${BEARER_TOKEN}"
+```
+
+The collection was modified and now with pending changes in the workspace. We will now request a review, so that the changes become visible in the **preview** bucket.
+
+```bash
+# request review
+curl -X PATCH ${SERVER}/buckets/main-workspace/collections/${CID} \
+ -H 'Content-Type:application/json' \
+ -d '{"data": {"status": "to-review"}}' \
+ -H "Authorization:${BEARER_TOKEN}"
+```
+
+Now this new record should be listed here: https://settings.dev.mozaws.net/v1/buckets/main-preview/collections/cfr/records
+
+**3. Set Remote Settings prefs to use the dev server.**
+
+Until [support for the DEV environment](https://github.com/mozilla-extensions/remote-settings-devtools/issues/66) is added to the [Remote Settings dev tools](https://github.com/mozilla-extensions/remote-settings-devtools/), we'll change the preferences manually.
+
+> These are critical preferences, you should use a dedicated Firefox profile for development.
+
+```javascript
+ Services.prefs.setCharPref("services.settings.loglevel", "debug");
+ Services.prefs.setCharPref("services.settings.server", "https://settings.dev.mozaws.net/v1");
+ // Pull data from the preview bucket.
+ RemoteSettings.enablePreviewMode(true);
+```
+
+**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","collection":"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..fae2a6508f
--- /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..37111135c7
--- /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://remote-settings.mozilla.org/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..d1e2a51851
--- /dev/null
+++ b/browser/components/newtab/jar.mn
@@ -0,0 +1,46 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.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/schemas/BackgroundTaskMessagingExperiment.schema.json (./content-src/asrouter/schemas/BackgroundTaskMessagingExperiment.schema.json)
+ res/activity-stream/schemas/MessagingExperiment.schema.json (./content-src/asrouter/schemas/MessagingExperiment.schema.json)
+ 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..83cc6e1219
--- /dev/null
+++ b/browser/components/newtab/karma.mc.config.js
@@ -0,0 +1,346 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { ResourceUriPlugin } = require("./tools/resourceUriPlugin");
+
+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: ["lcov", "text-summary"], // for some reason "lcov" reallys means "lcov" and "html"
+ "report-config": {
+ // so the full m-c path gets printed; needed for https://coverage.moz.tools/ integration
+ lcov: {
+ projectRoot: "../../..",
+ },
+ },
+ 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: 94,
+ 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: 78,
+ branches: 63,
+ },
+ "lib/TelemetryFeed.jsm": {
+ statements: 99,
+ lines: 99,
+ functions: 100,
+ branches: 95,
+ },
+ "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.sys.mjs": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 75,
+ },
+ "lib/TopSitesFeed.jsm": {
+ statements: 70,
+ lines: 75,
+ functions: 80,
+ branches: 60,
+ },
+ "lib/Screenshots.jsm": {
+ statements: 94,
+ lines: 94,
+ functions: 75,
+ branches: 84,
+ },
+ "lib/*.jsm": {
+ statements: 100,
+ lines: 100,
+ functions: 99,
+ 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: 50,
+ branches: 0,
+ },
+ "content-src/lib/link-menu-options.js": {
+ statements: 96,
+ lines: 96,
+ functions: 96,
+ branches: 70,
+ },
+ "content-src/aboutwelcome/components/LanguageSwitcher.jsx": {
+ // This file is covered by the mochitest: browser_aboutwelcome_multistage_languageSwitcher.js
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/aboutwelcome/components/EmbeddedMigrationWizard.jsx": {
+ // This file is covered by the mochitest: browser_aboutwelcome_multistage_mr.js
+ // Can't be unit tested because it relies on the migration-wizard custom element
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/aboutwelcome/**/*.jsx": {
+ statements: 62,
+ lines: 60,
+ functions: 50,
+ branches: 50,
+ },
+ "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"],
+ fallback: {
+ stream: require.resolve("stream-browserify"),
+ buffer: require.resolve("buffer"),
+ },
+ },
+ plugins: [
+ // The ResourceUriPlugin handles translating resource URIs in import
+ // statements in .mjs files, in a similar way to what
+ // babel-jsm-to-commonjs does for jsm files.
+ new ResourceUriPlugin({
+ resourcePathRegEx: PATHS.resourcePathRegEx,
+ }),
+ new webpack.DefinePlugin({
+ "process.env.NODE_ENV": JSON.stringify("development"),
+ }),
+ ],
+ 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
+ [
+ "./tools/babel-jsm-to-commonjs.js",
+ {
+ basePath: PATHS.resourcePathRegEx,
+ removeOtherImports: true,
+ replace: true,
+ },
+ ],
+ "@babel/plugin-proposal-nullish-coalescing-operator",
+ "@babel/plugin-proposal-optional-chaining",
+ "@babel/plugin-proposal-class-properties",
+ ],
+ },
+ },
+ ],
+ },
+ {
+ test: /\.js$/,
+ exclude: [/node_modules\/(?!@fluent\/).*/, /test/],
+ loader: "babel-loader",
+ options: {
+ // This is a workaround for bug 1787278. It can be removed once
+ // that bug is fixed.
+ plugins: ["@babel/plugin-proposal-optional-chaining"],
+ },
+ },
+ {
+ test: /\.jsx$/,
+ exclude: /node_modules/,
+ loader: "babel-loader",
+ options: {
+ presets: ["@babel/preset-react"],
+ plugins: [
+ "@babel/plugin-proposal-nullish-coalescing-operator",
+ "@babel/plugin-proposal-optional-chaining",
+ ],
+ },
+ },
+ {
+ test: /\.md$/,
+ use: "raw-loader",
+ },
+ {
+ enforce: "post",
+ test: /\.js[mx]?$/,
+ loader: "@jsdevtools/coverage-istanbul-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.sys.mjs"),
+ 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..231c1dfbb9
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouter.jsm
@@ -0,0 +1,2101 @@
+/* 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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ Downloader: "resource://services-settings/Attachments.sys.mjs",
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ MacAttribution: "resource:///modules/MacAttribution.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PanelTestProvider: "resource://activity-stream/lib/PanelTestProvider.sys.mjs",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.sys.mjs",
+ SnippetsTestMessageProvider:
+ "resource://activity-stream/lib/SnippetsTestMessageProvider.sys.mjs",
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
+ TargetingContext: "resource://messaging-system/targeting/Targeting.sys.mjs",
+ Utils: "resource://services-settings/Utils.sys.mjs",
+ setTimeout: "resource://gre/modules/Timer.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ Spotlight: "resource://activity-stream/lib/Spotlight.jsm",
+ ToastNotification: "resource://activity-stream/lib/ToastNotification.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",
+ KintoHttpClient: "resource://services-common/kinto-http-client.js",
+});
+
+XPCOMUtils.defineLazyServiceGetters(lazy, {
+ BrowserHandler: ["@mozilla.org/browser/clh;1", "nsIBrowserHandler"],
+});
+const { actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+const { AttributionCode } = ChromeUtils.importESModule(
+ "resource:///modules/AttributionCode.sys.mjs"
+);
+
+// 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_MAIN_BUCKET = "main";
+const RS_COLLECTION_L10N = "ms-language-packs"; // "ms" stands for Messaging System
+const RS_PROVIDERS_WITH_L10N = ["cfr"];
+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";
+const TOPIC_EXPERIMENT_ENROLLMENT_CHANGED = "nimbus:enrollments-updated";
+// 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";
+
+const MESSAGING_EXPERIMENTS_DEFAULT_FEATURES = [
+ "cfr",
+ "fxms-message-1",
+ "fxms-message-2",
+ "fxms-message-3",
+ "fxms-message-4",
+ "fxms-message-5",
+ "fxms-message-6",
+ "fxms-message-7",
+ "fxms-message-8",
+ "fxms-message-9",
+ "fxms-message-10",
+ "fxms-message-11",
+ "infobar",
+ "moments-page",
+ "pbNewtab",
+ "spotlight",
+];
+
+// 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", "infobar", "spotlight"];
+const REACH_EVENT_CATEGORY = "messaging_experiments";
+const REACH_EVENT_METHOD = "reach";
+
+const MessageLoaderUtils = {
+ STARTPAGE_VERSION,
+ REMOTE_LOADER_CACHE_KEY: "RemoteLoaderCache",
+ _errors: [],
+
+ reportError(e) {
+ console.error(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 _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). The "cfr" provider requires 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 {object} provider An AS router provider
+ * @param {string} provider.id The id of the provider
+ * @param {string} provider.collection Remote Settings collection name
+ * @param {object} options
+ * @param {function} options.dispatchCFRAction Action handler function
+ * @returns {Promise<object[]>} Resolves with an array of messages, or an
+ * empty array if none could be fetched
+ */
+ async _remoteSettingsLoader(provider, options) {
+ let messages = [];
+ if (provider.collection) {
+ try {
+ messages = await MessageLoaderUtils._getRemoteSettingsMessages(
+ provider.collection
+ );
+ if (!messages.length) {
+ MessageLoaderUtils._handleRemoteSettingsUndesiredEvent(
+ "ASR_RS_NO_MESSAGES",
+ provider.id,
+ options.dispatchCFRAction
+ );
+ } else if (
+ RS_PROVIDERS_WITH_L10N.includes(provider.id) &&
+ lazy.RemoteL10n.isLocaleSupported(MessageLoaderUtils.locale)
+ ) {
+ const recordId = `${RS_FLUENT_RECORD_PREFIX}-${MessageLoaderUtils.locale}`;
+ const kinto = new lazy.KintoHttpClient(lazy.Utils.SERVER_URL);
+ const record = await kinto
+ .bucket(RS_MAIN_BUCKET)
+ .collection(RS_COLLECTION_L10N)
+ .getRecord(recordId);
+ if (record && record.data) {
+ const downloader = new lazy.Downloader(
+ RS_MAIN_BUCKET,
+ RS_COLLECTION_L10N,
+ "browser",
+ "newtab"
+ );
+ // Await here in order to capture the exceptions for reporting.
+ await downloader.downloadToDisk(record.data, {
+ retries: RS_DOWNLOAD_MAX_RETRIES,
+ });
+ lazy.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;
+ },
+
+ /**
+ * Fetch messages from a given collection in Remote Settings.
+ *
+ * @param {string} collection The remote settings collection identifier
+ * @returns {Promise<object[]>} Resolves with an array of messages
+ */
+ _getRemoteSettingsMessages(collection) {
+ return RemoteSettings(collection).get();
+ },
+
+ /**
+ * Return messages from active Nimbus experiments and rollouts.
+ *
+ * @param {object} provider A messaging experiments provider.
+ * @param {string[]?} provider.featureIds
+ * An optional array of Nimbus feature IDs to check for
+ * enrollments. If not provided, we will fall back to the
+ * set of default features. Otherwise, if provided and
+ * empty, we will not ingest messages from any features.
+ *
+ * @return {object[]} The list of messages from active enrollments, as well as
+ * the messages defined in unenrolled branches so that they
+ * reach events can be recorded (if we record reach events
+ * for that feature).
+ */
+ async _experimentsAPILoader(provider) {
+ // Allow tests to override the set of featureIds
+ const featureIds = Array.isArray(provider.featureIds)
+ ? provider.featureIds
+ : MESSAGING_EXPERIMENTS_DEFAULT_FEATURES;
+ let experiments = [];
+ for (const featureId of featureIds) {
+ const featureAPI = lazy.NimbusFeatures[featureId];
+ const experimentData = lazy.ExperimentAPI.getExperimentMetaData({
+ featureId,
+ });
+
+ // We are not enrolled in any experiment or rollout for this feature, so
+ // we can skip the feature.
+ if (
+ !experimentData &&
+ !lazy.ExperimentAPI.getRolloutMetaData({ featureId })
+ ) {
+ continue;
+ }
+
+ const featureValue = featureAPI.getAllVariables();
+
+ // If the value is a multi-message config, add each message in the
+ // messages array. Cache the Nimbus feature ID on each message, because
+ // there is not a 1-1 correspondance between templates and features.
+ // This is used when recording expose events (see |sendTriggerMessage|).
+ const messages =
+ featureValue?.template === "multi" &&
+ Array.isArray(featureValue.messages)
+ ? featureValue.messages
+ : [featureValue];
+ for (const message of messages) {
+ if (message?.id) {
+ message._nimbusFeature = featureId;
+ experiments.push(message);
+ }
+ }
+
+ // Add Reach messages from unenrolled sibling branches, provided we are
+ // recording Reach events for this feature. If we are in a rollout, we do
+ // not have sibling branches.
+ if (!REACH_EVENT_GROUPS.includes(featureId) || !experimentData) {
+ 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 be used to record the Reach event.
+ const branches =
+ (await lazy.ExperimentAPI.getAllBranches(experimentData.slug)) || [];
+ for (const branch of branches) {
+ let branchValue = branch[featureId].value;
+ if (!branchValue || branch.slug === experimentData.branch.slug) {
+ continue;
+ }
+ const branchMessages =
+ branchValue?.template === "multi" &&
+ Array.isArray(branchValue.messages)
+ ? branchValue.messages
+ : [branchValue];
+ for (const message of branchMessages) {
+ if (!message?.trigger) {
+ continue;
+ }
+ experiments.push({
+ forReachEvent: { sent: false, group: featureId },
+ experimentSlug: experimentData.slug,
+ branchSlug: branch.slug,
+ ...message,
+ });
+ }
+ }
+ }
+
+ 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 "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,
+ };
+
+ 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);
+ }
+ },
+
+ /**
+ * The locale to use for RemoteL10n.
+ *
+ * This may map the app's actual locale into something that RemoteL10n
+ * supports.
+ */
+ get locale() {
+ const localeMap = {
+ "ja-JP-macos": "ja-JP-mac",
+
+ // 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.
+ und: "en-US",
+ };
+
+ const locale = Services.locale.appLocaleAsBCP47;
+ return localeMap[locale] ?? locale;
+ },
+};
+
+/**
+ * @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: {},
+ screenImpressions: {},
+ messages: [],
+ groups: [],
+ errors: [],
+ localeInUse: Services.locale.appLocaleAsBCP47,
+ };
+ this._experimentChangedListeners = new Map();
+ 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.addScreenImpression = this.addScreenImpression.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);
+ this._onExperimentEnrollmentsUpdated =
+ this._onExperimentEnrollmentsUpdated.bind(this);
+ this.forcePBWindow = this.forcePBWindow.bind(this);
+ Services.telemetry.setEventRecordingEnabled(REACH_EVENT_CATEGORY, true);
+ }
+
+ async onPrefChange(prefName) {
+ if (lazy.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 lazy.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() {
+ lazy.ASRouterPreferences.console.debug("entering 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
+ ...lazy.ASRouterPreferences.providers.filter(
+ p =>
+ p.enabled &&
+ lazy.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);
+ }
+ if (provider.id === "messaging-experiments") {
+ // By default, the messaging-experiments provider lacks a featureIds
+ // property, so fall back to the list of default features.
+ if (!provider.featureIds) {
+ provider.featureIds = MESSAGING_EXPERIMENTS_DEFAULT_FEATURES;
+ }
+ }
+ // 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.initializing = false;
+ this.waitForInitialized = new Promise(resolve => {
+ this._finishInitializing = () => {
+ this.initialized = true;
+ this.initializing = false;
+ 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 =>
+ lazy.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
+ * @param toUpdate An optional list of providers to update. This overrides
+ * the checks to determine which providers to update.
+ * @memberof _ASRouter
+ */
+ async loadMessagesFromAllProviders(toUpdate = undefined) {
+ const needsUpdate = Array.isArray(toUpdate)
+ ? toUpdate
+ : this.state.providers.filter(provider =>
+ MessageLoaderUtils.shouldProviderUpdate(provider)
+ );
+ lazy.ASRouterPreferences.console.debug(
+ "entering loadMessagesFromAllProviders"
+ );
+
+ 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(lazy.ASRouterTriggerListeners.keys());
+ for (const { trigger } of newState.messages) {
+ if (trigger && lazy.ASRouterTriggerListeners.has(trigger.id)) {
+ lazy.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) {
+ lazy.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();
+ }
+
+ await this._fireMessagesLoadedTrigger();
+
+ return this.state;
+ }
+
+ async _fireMessagesLoadedTrigger() {
+ const win = Services.wm.getMostRecentBrowserWindow() ?? null;
+ const browser = win?.gBrowser?.selectedBrowser ?? null;
+ // pass skipLoadingMessages to avoid infinite recursion. pass browser and
+ // window into context so messages that may need a window or browser can
+ // target accordingly.
+ await this.sendTriggerMessage(
+ {
+ id: "messagesLoaded",
+ browser,
+ context: { browser, browserWindow: win },
+ },
+ true
+ );
+ }
+
+ 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,
+ }) {
+ if (this.initializing || this.initialized) {
+ return null;
+ }
+ this.initializing = true;
+ 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);
+
+ lazy.ASRouterPreferences.init();
+ lazy.ASRouterPreferences.addListener(this.onPrefChange);
+ lazy.ToolbarBadgeHub.init(this.waitForInitialized, {
+ handleMessageRequest: this.handleMessageRequest,
+ addImpression: this.addImpression,
+ blockMessageById: this.blockMessageById,
+ unblockMessageById: this.unblockMessageById,
+ sendTelemetry: this.sendTelemetry,
+ });
+ lazy.ToolbarPanelHub.init(this.waitForInitialized, {
+ getMessages: this.handleMessageRequest,
+ sendTelemetry: this.sendTelemetry,
+ });
+ lazy.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 screenImpressions =
+ (await this._storage.get("screenImpressions")) || {};
+ const previousSessionEnd =
+ (await this._storage.get("previousSessionEnd")) || 0;
+
+ await this.setState({
+ messageBlockList,
+ groupImpressions,
+ messageImpressions,
+ screenImpressions,
+ previousSessionEnd,
+ ...(lazy.ASRouterPreferences.specialConditions || {}),
+ initialized: false,
+ });
+ await this._updateMessageProviders();
+ await this.loadMessagesFromAllProviders();
+ await MessageLoaderUtils.cleanupCache(this.state.providers, storage);
+
+ lazy.SpecialMessageActions.blockMessageById = this.blockMessageById;
+ Services.obs.addObserver(this._onLocaleChanged, TOPIC_INTL_LOCALE_CHANGED);
+ Services.obs.addObserver(
+ this._onExperimentEnrollmentsUpdated,
+ TOPIC_EXPERIMENT_ENROLLMENT_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;
+
+ lazy.ASRouterPreferences.removeListener(this.onPrefChange);
+ lazy.ASRouterPreferences.uninit();
+ lazy.ToolbarPanelHub.uninit();
+ lazy.ToolbarBadgeHub.uninit();
+ lazy.MomentsPageHub.uninit();
+
+ // Uninitialise all trigger listeners
+ for (const listener of lazy.ASRouterTriggerListeners.values()) {
+ listener.uninit();
+ }
+ Services.obs.removeObserver(
+ this._onLocaleChanged,
+ TOPIC_INTL_LOCALE_CHANGED
+ );
+ Services.obs.removeObserver(
+ this._onExperimentEnrollmentsUpdated,
+ TOPIC_EXPERIMENT_ENROLLMENT_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) {
+ lazy.ASRouterPreferences.console.debug(
+ "in setState, callbackOrObj = ",
+ callbackOrObj
+ );
+ lazy.ASRouterPreferences.console.trace();
+ const newState =
+ typeof callbackOrObj === "function"
+ ? callbackOrObj(this.state)
+ : callbackOrObj;
+ this._state = {
+ ...this.state,
+ ...newState,
+ };
+ if (lazy.ASRouterPreferences.devtoolsEnabled) {
+ return this.updateTargetingParameters().then(state => {
+ this.updateAdminState(state);
+ return state;
+ });
+ }
+ return Promise.resolve(this.state);
+ }
+
+ updateTargetingParameters() {
+ return this.getTargetingParameters(
+ lazy.ASRouterTargeting.Environment,
+ this._getMessagesContext()
+ ).then(targetingParameters => ({
+ ...this.state,
+ providerPrefs: lazy.ASRouterPreferences.providers,
+ userPrefs: lazy.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 (lazy.ASRouterPreferences.devtoolsEnabled) {
+ this._localProviders = {
+ ...this._localProviders,
+ SnippetsTestMessageProvider: lazy.SnippetsTestMessageProvider,
+ PanelTestProvider: lazy.PanelTestProvider,
+ };
+ }
+ }
+
+ /**
+ * Used by ASRouter Admin returns all ASRouterTargeting.Environment
+ * and ASRouter._getMessagesContext parameters and values
+ */
+ async getTargetingParameters(environment, localContext) {
+ // Resolve objects that may contain promises.
+ async function resolve(object) {
+ if (typeof object === "object" && object !== null) {
+ if (Array.isArray(object)) {
+ return Promise.all(object.map(async item => resolve(await item)));
+ }
+
+ if (object instanceof Date) {
+ return object;
+ }
+
+ const target = {};
+ const promises = Object.entries(object).map(async ([key, value]) => [
+ key,
+ await resolve(await value),
+ ]);
+ for (const [key, value] of await Promise.all(promises)) {
+ target[key] = value;
+ }
+ return target;
+ }
+
+ return object;
+ }
+
+ const targetingParameters = {
+ ...(await resolve(environment)),
+ ...(await resolve(localContext)),
+ };
+
+ return targetingParameters;
+ }
+
+ _handleTargetingError(error, message) {
+ console.error(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, screenImpressions } =
+ this.state;
+
+ return {
+ get messageImpressions() {
+ return messageImpressions;
+ },
+ get previousSessionEnd() {
+ return previousSessionEnd;
+ },
+ get screenImpressions() {
+ return screenImpressions;
+ },
+ };
+ }
+
+ async evaluateExpression({ expression, context }) {
+ const targetingContext = new lazy.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) {
+ const { 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];
+
+ const _belowItemFrequencyCap = this._isBelowItemFrequencyCap(
+ message,
+ impressionsForMessage,
+ MAX_MESSAGE_LIFETIME_CAP
+ );
+ if (!_belowItemFrequencyCap) {
+ lazy.ASRouterPreferences.console.debug(
+ `isBelowFrequencyCaps: capped by item: `,
+ message,
+ "impressions =",
+ impressionsForMessage
+ );
+ }
+
+ const _belowGroupFrequencyCaps = message.groups.every(messageGroup => {
+ const belowThisGroupCap = this._isBelowItemFrequencyCap(
+ this.state.groups.find(({ id }) => id === messageGroup),
+ groupImpressions[messageGroup]
+ );
+
+ if (!belowThisGroupCap) {
+ lazy.ASRouterPreferences.console.debug(
+ `isBelowFrequencyCaps: ${message.id} capped by group ${messageGroup}`
+ );
+ } else {
+ lazy.ASRouterPreferences.console.debug(
+ `isBelowFrequencyCaps: ${message.id} allowed by group ${messageGroup}, groupImpressions = `,
+ groupImpressions
+ );
+ }
+
+ return belowThisGroupCap;
+ });
+
+ return _belowItemFrequencyCap && _belowGroupFrequencyCaps;
+ }
+
+ // 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)
+ ) {
+ lazy.ASRouterPreferences.console.debug(
+ `${item.id} capped by lifetime (${item.frequency.lifetime})`
+ );
+
+ 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) {
+ lazy.ASRouterPreferences.console.debug(
+ `${item.id} capped by impressions (${impressionsInPeriod.length}) in period (${period}) >= ${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) {
+ lazy.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 "toolbar_badge":
+ lazy.ToolbarBadgeHub.registerBadgeNotificationListener(message, {
+ force,
+ });
+ break;
+ case "update_action":
+ lazy.MomentsPageHub.executeAction(message);
+ break;
+ case "infobar":
+ lazy.InfoBar.showInfoBarMessage(
+ browser,
+ message,
+ this.dispatchCFRAction
+ );
+ break;
+ case "spotlight":
+ lazy.Spotlight.showSpotlightDialog(
+ browser,
+ message,
+ this.dispatchCFRAction
+ );
+ break;
+ case "toast_notification":
+ lazy.ToastNotification.showToastNotification(
+ message,
+ this.dispatchCFRAction
+ );
+ break;
+ }
+
+ return { message };
+ }
+
+ addScreenImpression(screen) {
+ lazy.ASRouterPreferences.console.debug(
+ `entering addScreenImpression for ${screen.id}`
+ );
+
+ const time = Date.now();
+
+ let screenImpressions = { ...this.state.screenImpressions };
+ screenImpressions[screen.id] = time;
+
+ this.setState({ screenImpressions });
+ lazy.ASRouterPreferences.console.debug(
+ screen.id,
+ `screen impression added, screenImpressions[screen.id]: `,
+ screenImpressions[screen.id]
+ );
+ this._storage.set("screenImpressions", screenImpressions);
+ }
+
+ addImpression(message) {
+ lazy.ASRouterPreferences.console.debug(
+ `entering addImpression for ${message.id}`
+ );
+
+ 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.messageImpressions,
+ message,
+ "messageImpressions",
+ time
+ );
+ // Initialize this with state.groupImpressions, and then assign the
+ // newly-updated copy to it during each iteration so that
+ // all the changes get captured and either returned or passed into the
+ // _addImpressionsForItem call on the next iteration.
+ let { groupImpressions } = state;
+ for (const group of groupsWithFrequency) {
+ groupImpressions = this._addImpressionForItem(
+ groupImpressions,
+ 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(currentImpressions, item, impressionsString, time) {
+ // The destructuring here is to avoid mutating passed parameters
+ // (see https://redux.js.org/recipes/structuring-reducers/prerequisite-concepts#immutable-data-management)
+ const impressions = { ...currentImpressions };
+ if (item.frequency) {
+ impressions[item.id] = [...(impressions[item.id] ?? []), time];
+
+ lazy.ASRouterPreferences.console.debug(
+ item.id,
+ "impression added, impressions[item.id]: ",
+ impressions[item.id]
+ );
+
+ 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])) {
+ lazy.ASRouterPreferences.console.debug(
+ "_cleanupImpressionsForItem: removing impressions for deleted or changed item: ",
+ item
+ );
+ lazy.ASRouterPreferences.console.trace();
+ 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) {
+ lazy.ASRouterPreferences.console.debug(
+ "_cleanupImpressionsForItem: removing impressions older than longest period for item: ",
+ item
+ );
+ 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;
+ lazy.ASRouterPreferences.console.debug(
+ "in handleMessageRequest, arguments = ",
+ Array.from(arguments) // eslint-disable-line prefer-rest-params
+ );
+ lazy.ASRouterPreferences.console.trace();
+ const messages =
+ candidates ||
+ this.state.messages.filter(m => {
+ if (provider && m.provider !== provider) {
+ lazy.ASRouterPreferences.console.debug(m.id, " filtered by provider");
+ return false;
+ }
+ if (template && m.template !== template) {
+ lazy.ASRouterPreferences.console.debug(m.id, " filtered by template");
+ return false;
+ }
+ if (triggerId && !m.trigger) {
+ lazy.ASRouterPreferences.console.debug(m.id, " filtered by trigger");
+ return false;
+ }
+ if (triggerId && m.trigger.id !== triggerId) {
+ lazy.ASRouterPreferences.console.debug(
+ m.id,
+ " filtered by triggerId"
+ );
+ return false;
+ }
+ if (!this.isUnblockedMessage(m)) {
+ lazy.ASRouterPreferences.console.debug(
+ m.id,
+ " filtered because blocked"
+ );
+ return false;
+ }
+ if (!this.isBelowFrequencyCaps(m)) {
+ lazy.ASRouterPreferences.console.debug(
+ m.id,
+ " filtered because capped"
+ );
+ 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 lazy.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) {
+ lazy.ASRouterPreferences.console.debug(
+ "blockMessageById called, idOrIds = ",
+ idOrIds
+ );
+ lazy.ASRouterPreferences.console.trace();
+
+ 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,
+ }));
+ }
+
+ resetMessageState() {
+ const newMessageImpressions = {};
+ for (let { id } of this.state.messages) {
+ newMessageImpressions[id] = [];
+ }
+ // Update storage
+ this._storage.set("messageImpressions", newMessageImpressions);
+ return this.setState(() => ({
+ messageImpressions: newMessageImpressions,
+ }));
+ }
+
+ _validPreviewEndpoint(url) {
+ try {
+ const endpoint = new URL(url);
+ if (!this.ALLOWLIST_HOSTS[endpoint.host]) {
+ console.error(
+ `The preview URL host ${endpoint.host} is not in the list of allowed hosts.`
+ );
+ }
+ if (endpoint.protocol !== "https:") {
+ console.error("The URL protocol is not https.");
+ }
+ return (
+ endpoint.protocol === "https:" && this.ALLOWLIST_HOSTS[endpoint.host]
+ );
+ } catch (e) {
+ return false;
+ }
+ }
+
+ _loadSnippetsAllowHosts() {
+ let additionalHosts = [];
+ const allowPrefValue = Services.prefs.getStringPref(
+ SNIPPETS_ENDPOINT_ALLOWLIST,
+ ""
+ );
+ try {
+ additionalHosts = JSON.parse(allowPrefValue);
+ } catch (e) {
+ if (allowPrefValue) {
+ console.error(
+ `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 (lazy.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 = lazy.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
+ Services.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 sendPBNewTabMessage({ tabId, hideDefault }) {
+ let message = null;
+ const PromoInfo = {
+ FOCUS: { enabledPref: "browser.promo.focus.enabled" },
+ VPN: { enabledPref: "browser.vpn_promo.enabled" },
+ PIN: { enabledPref: "browser.promo.pin.enabled" },
+ COOKIE_BANNERS: { enabledPref: "browser.promo.cookiebanners.enabled" },
+ };
+ await this.loadMessagesFromAllProviders();
+
+ // If message has hideDefault property set to true
+ // remove from state all pb_newtab messages with type default
+ if (hideDefault) {
+ await this.setState(state => ({
+ messages: state.messages.filter(
+ m => !(m.template === "pb_newtab" && m.type === "default")
+ ),
+ }));
+ }
+
+ // Remove from state pb_newtab messages with PromoType disabled
+ await this.setState(state => ({
+ messages: state.messages.filter(
+ m =>
+ !(
+ m.template === "pb_newtab" &&
+ !Services.prefs.getBoolPref(
+ PromoInfo[m.content?.promoType]?.enabledPref,
+ true
+ )
+ )
+ ),
+ }));
+
+ const telemetryObject = { tabId };
+ TelemetryStopwatch.start("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ message = await this.handleMessageRequest({
+ template: "pb_newtab",
+ });
+ TelemetryStopwatch.finish("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+
+ // Format urls if any are defined
+ ["infoLinkUrl"].forEach(key => {
+ if (message?.content?.[key]) {
+ message.content[key] = Services.urlFormatter.formatURL(
+ message.content[key]
+ );
+ }
+ });
+
+ return { message };
+ }
+
+ 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
+ );
+ }
+
+ /**
+ * Fire a trigger, look for a matching message, and route it to the
+ * appropriate message handler/messaging surface.
+ * @param {object} trigger
+ * @param {string} trigger.id the name of the trigger, e.g. "openURL"
+ * @param {object} [trigger.param] an object with host, url, type, etc. keys
+ * whose values are used to match against the message's trigger params
+ * @param {object} [trigger.context] an object with data about the source of
+ * the trigger, matched against the message's targeting expression
+ * @param {MozBrowser} trigger.browser the browser to route messages to
+ * @param {number} [trigger.tabId] identifier used only for exposure testing
+ * @param {boolean} [skipLoadingMessages=false] pass true to skip looking for
+ * new messages. use when calling from loadMessagesFromAllProviders to avoid
+ * recursion. we call this from loadMessagesFromAllProviders in order to
+ * fire the messagesLoaded trigger.
+ * @returns {Promise<object>}
+ * @resolves {message} an object with the routed message
+ */
+ async sendTriggerMessage(
+ { tabId, browser, ...trigger },
+ skipLoadingMessages = false
+ ) {
+ if (!skipLoadingMessages) {
+ 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);
+ }
+ }
+
+ if (nonReachMessages.length) {
+ let featureId = nonReachMessages[0]._nimbusFeature;
+ if (featureId) {
+ lazy.NimbusFeatures[featureId].recordExposureEvent({ once: true });
+ }
+ }
+
+ return this.routeCFRMessage(
+ nonReachMessages[0] || null,
+ browser,
+ trigger,
+ false
+ );
+ }
+
+ async forceWNPanel(browser) {
+ let win = browser.ownerGlobal;
+ await lazy.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 lazy.ToolbarPanelHub._hideToolbarButton(win);
+ }
+
+ async _onExperimentEnrollmentsUpdated() {
+ const experimentProvider = this.state.providers.find(
+ p => p.id === "messaging-experiments"
+ );
+ if (!experimentProvider?.enabled) {
+ return;
+ }
+ await this.loadMessagesFromAllProviders([experimentProvider]);
+ }
+
+ async forcePBWindow(browser, msg) {
+ const privateBrowserOpener = await new Promise(
+ (
+ resolveOnContentBrowserCreated // wrap this in a promise to give back the right browser
+ ) =>
+ browser.ownerGlobal.openTrustedLinkIn(
+ "about:privatebrowsing?debug",
+ "window",
+ {
+ private: true,
+ triggeringPrincipal:
+ Services.scriptSecurityManager.getSystemPrincipal({}),
+ csp: null,
+ resolveOnContentBrowserCreated,
+ opener: "devtools",
+ }
+ )
+ );
+
+ lazy.setTimeout(() => {
+ // setTimeout is necessary to make sure the private browsing window has a chance to open before the message is sent
+ privateBrowserOpener.browsingContext.currentWindowGlobal
+ .getActor("AboutPrivateBrowsing")
+ .sendAsyncMessage("ShowDevToolsMessage", msg);
+ }, 100);
+
+ return privateBrowserOpener;
+ }
+}
+
+/**
+ * ASRouter - singleton instance of _ASRouter that controls all messages
+ * in the new tab page.
+ */
+const 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..84ccad5200
--- /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.importESModule(
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs"
+);
+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.sys.mjs b/browser/components/newtab/lib/ASRouterNewTabHook.sys.mjs
new file mode 100644
index 0000000000..d0fdbfdae4
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterNewTabHook.sys.mjs
@@ -0,0 +1,117 @@
+/* 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/. */
+
+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,
+ });
+ }
+ }
+
+ destroy() {
+ if (this._router?.initialized) {
+ 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.
+ */
+ 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;
+ }
+}
+
+export 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..dca79b29d0
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm
@@ -0,0 +1,179 @@
+/* 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 { ASRouterPreferences } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterPreferences.jsm"
+);
+
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/ActorConstants.sys.mjs"
+);
+
+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:
+ case msg.SPOTLIGHT_TELEMETRY:
+ case msg.TOAST_NOTIFICATION_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: {
+ ASRouterPreferences.console.debug(
+ "handleMesssage(): about to block, data = ",
+ data
+ );
+ ASRouterPreferences.console.trace();
+
+ // 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: {
+ 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.PBNEWTAB_MESSAGE_REQUEST: {
+ return this._router.sendPBNewTabMessage({
+ ...data,
+ 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_PRIVATE_BROWSING_WINDOW: {
+ return this._router.forcePBWindow(browser, data.message);
+ }
+ 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.routeCFRMessage(data.content, browser, data, true);
+ }
+ 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..c2fc071fbd
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterPreferences.jsm
@@ -0,0 +1,259 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const PROVIDER_PREF_BRANCH =
+ "browser.newtabpage.activity-stream.asrouter.providers.";
+const DEVTOOLS_PREF =
+ "browser.newtabpage.activity-stream.asrouter.devtoolsEnabled";
+
+/**
+ * Use `ASRouterPreferences.console.debug()` and friends from ASRouter files to
+ * log messages during development. See LOG_LEVELS in ConsoleAPI.jsm for the
+ * available methods as well as the available values for this pref.
+ */
+const DEBUG_PREF = "browser.newtabpage.activity-stream.asrouter.debugLogLevel";
+
+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.defineLazyGetter(this, "console", () => {
+ let { ConsoleAPI } = ChromeUtils.importESModule(
+ "resource://gre/modules/Console.sys.mjs"
+ );
+ let consoleOptions = {
+ maxLogLevel: "error",
+ maxLogLevelPref: DEBUG_PREF,
+ prefix: "ASRouter",
+ };
+ return new ConsoleAPI(consoleOptions);
+ });
+ }
+
+ _transformPersonalizedCfrScores(value) {
+ let result = {};
+ try {
+ result = JSON.parse(value);
+ } catch (e) {
+ console.error(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) {
+ console.error(
+ `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) {
+ console.error(
+ `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]);
+ }
+ }
+
+ /**
+ * Bug 1800087 - Migrate the ASRouter message provider prefs' values to the
+ * current format (provider.bucket -> provider.collection).
+ *
+ * TODO (Bug 1800937): Remove migration code after the next watershed release.
+ */
+ _migrateProviderPrefs() {
+ const prefList = Services.prefs.getChildList(this._providerPrefBranch);
+ for (const pref of prefList) {
+ if (!Services.prefs.prefHasUserValue(pref)) {
+ continue;
+ }
+ try {
+ let value = JSON.parse(Services.prefs.getStringPref(pref, ""));
+ if (value && "bucket" in value && !("collection" in value)) {
+ const { bucket, ...rest } = value;
+ Services.prefs.setStringPref(
+ pref,
+ JSON.stringify({
+ ...rest,
+ collection: bucket,
+ })
+ );
+ }
+ } catch (e) {
+ Services.prefs.clearUserPref(pref);
+ }
+ }
+ }
+
+ 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;
+ }
+ this._migrateProviderPrefs();
+ 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();
+ }
+}
+
+const ASRouterPreferences = new _ASRouterPreferences();
+
+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..3e5d969f32
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterTargeting.jsm
@@ -0,0 +1,1225 @@
+/* This Source Code Form is subject to the terms of the Mozilla PublicddonMa
+ * License, v. 2.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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const { NewTabUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/NewTabUtils.sys.mjs"
+);
+const { ShellService } = ChromeUtils.importESModule(
+ "resource:///modules/ShellService.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
+ AttributionCode: "resource:///modules/AttributionCode.sys.mjs",
+ ClientEnvironment: "resource://normandy/lib/ClientEnvironment.sys.mjs",
+ CustomizableUI: "resource:///modules/CustomizableUI.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ProfileAge: "resource://gre/modules/ProfileAge.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+ TargetingContext: "resource://messaging-system/targeting/Targeting.sys.mjs",
+ TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.sys.mjs",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ ASRouterPreferences: "resource://activity-stream/lib/ASRouterPreferences.jsm",
+ HomePage: "resource:///modules/HomePage.jsm",
+ AboutNewTab: "resource:///modules/AboutNewTab.jsm",
+ BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(lazy, "fxAccounts", () => {
+ return ChromeUtils.importESModule(
+ "resource://gre/modules/FxAccounts.sys.mjs"
+ ).getFxAccountsSingleton();
+});
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "cfrFeaturesUserPref",
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "cfrAddonsUserPref",
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "isWhatsNewPanelEnabled",
+ "browser.messaging-system.whatsNewPanel.enabled",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "hasAccessedFxAPanel",
+ "identity.fxaccounts.toolbar.accessed",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "clientsDevicesDesktop",
+ "services.sync.clients.devices.desktop",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "clientsDevicesMobile",
+ "services.sync.clients.devices.mobile",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "syncNumClients",
+ "services.sync.numClients",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "devtoolsSelfXSSCount",
+ "devtools.selfxss.count",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "isFxAEnabled",
+ FXA_ENABLED_PREF,
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "isXPIInstallEnabled",
+ "xpinstall.enabled",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "snippetsUserPref",
+ "browser.newtabpage.activity-stream.feeds.snippets",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "hasMigratedBookmarks",
+ "browser.migrate.interactions.bookmarks",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "hasMigratedHistory",
+ "browser.migrate.interactions.history",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "hasMigratedPasswords",
+ "browser.migrate.interactions.passwords",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "useEmbeddedMigrationWizard",
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "default",
+ null,
+ behaviorString => {
+ return behaviorString === "embedded";
+ }
+);
+
+XPCOMUtils.defineLazyServiceGetters(lazy, {
+ AUS: ["@mozilla.org/updates/update-service;1", "nsIApplicationUpdateService"],
+ BrowserHandler: ["@mozilla.org/browser/clh;1", "nsIBrowserHandler"],
+ TrackingDBService: [
+ "@mozilla.org/tracking-db-service;1",
+ "nsITrackingDBService",
+ ],
+ UpdateCheckSvc: ["@mozilla.org/updates/update-checker;1", "nsIUpdateChecker"],
+});
+
+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
+ * @param options {any=} Options passed to the method
+ * @param updateInterval {number?} Update interval for query. Defaults to FRECENT_SITES_UPDATE_INTERVAL
+ */
+function CachedTargetingGetter(
+ property,
+ options = null,
+ updateInterval = FRECENT_SITES_UPDATE_INTERVAL,
+ getter = asProvider
+) {
+ 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 getter[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 => {
+ lazy.fxAccounts
+ .listAttachedOAuthClients()
+ .then(clients => {
+ resolve(clients);
+ })
+ .catch(() => resolve([]));
+ });
+ this._lastUpdated = now;
+ }
+ return this._value;
+ },
+ };
+}
+
+function CheckBrowserNeedsUpdate(
+ updateInterval = FRECENT_SITES_UPDATE_INTERVAL
+) {
+ 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;
+ },
+ async get() {
+ const now = Date.now();
+ if (
+ !AppConstants.MOZ_UPDATER ||
+ now - this._lastUpdated < updateInterval
+ ) {
+ return this._value;
+ }
+ if (!lazy.AUS.canCheckForUpdates) {
+ return false;
+ }
+ this._lastUpdated = now;
+ let check = lazy.UpdateCheckSvc.checkForUpdates(
+ lazy.UpdateCheckSvc.FOREGROUND_CHECK
+ );
+ let result = await check.result;
+ if (!result.succeeded) {
+ throw result.request;
+ }
+ checker._value = !!result.updates.length;
+ return checker._value;
+ },
+ };
+
+ return checker;
+}
+
+const QueryCache = {
+ expireAll() {
+ Object.keys(this.queries).forEach(query => {
+ this.queries[query].expire();
+ });
+ Object.keys(this.getters).forEach(key => {
+ this.getters[key].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(),
+ UserMonthlyActivity: new CachedTargetingGetter("getUserMonthlyActivity"),
+ },
+ getters: {
+ doesAppNeedPin: new CachedTargetingGetter(
+ "doesAppNeedPin",
+ null,
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ doesAppNeedPrivatePin: new CachedTargetingGetter(
+ "doesAppNeedPin",
+ true,
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ isDefaultBrowser: new CachedTargetingGetter(
+ "isDefaultBrowser",
+ null,
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ currentThemes: new CachedTargetingGetter(
+ "getAddonsByTypes",
+ ["theme"],
+ FRECENT_SITES_UPDATE_INTERVAL,
+ lazy.AddonManager // eslint-disable-line mozilla/valid-lazy
+ ),
+ isDefaultHTMLHandler: new CachedTargetingGetter(
+ "isDefaultHandlerFor",
+ [".html"],
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ isDefaultPDFHandler: new CachedTargetingGetter(
+ "isDefaultHandlerFor",
+ [".pdf"],
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ defaultPDFHandler: new CachedTargetingGetter(
+ "getDefaultPDFHandler",
+ null,
+ FRECENT_SITES_UPDATE_INTERVAL,
+ ShellService
+ ),
+ },
+};
+
+/**
+ * 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;
+
+ if (!ordered) {
+ result = sortMessagesByWeightedRank(result);
+ }
+
+ result.sort((a, b) => {
+ // 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;
+ });
+
+ 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;
+}
+
+/**
+ * Get the number of records in autofill storage, e.g. credit cards/addresses.
+ *
+ * @param {Object} [data]
+ * @param {string} [data.collectionName]
+ * The name used to specify which collection to retrieve records.
+ * @param {string} [data.searchString]
+ * The typed string for filtering out the matched records.
+ * @param {string} [data.info]
+ * The input autocomplete property's information.
+ * @returns {Promise<number>} The number of matched records.
+ * @see FormAutofillParent._getRecords
+ */
+async function getAutofillRecords(data) {
+ let actor;
+ try {
+ const win = Services.wm.getMostRecentBrowserWindow();
+ actor =
+ win.gBrowser.selectedBrowser.browsingContext.currentWindowGlobal.getActor(
+ "FormAutofill"
+ );
+ } catch (error) {
+ // If the actor is not available, we can't get the records. We could import
+ // the records directly from FormAutofillStorage to avoid the messiness of
+ // JSActors, but that would import a lot of code for a targeting attribute.
+ return 0;
+ }
+ let records = await actor?.receiveMessage({
+ name: "FormAutofill:GetRecords",
+ data,
+ });
+ return records?.length ?? 0;
+}
+
+// Attribution data can be encoded multiple times so we need this function to
+// get a cleartext value.
+function decodeAttributionValue(value) {
+ if (!value) {
+ return null;
+ }
+
+ let decodedValue = value;
+
+ while (decodedValue.includes("%")) {
+ try {
+ const result = decodeURIComponent(decodedValue);
+ if (result === decodedValue) {
+ break;
+ }
+ decodedValue = result;
+ } catch (e) {
+ break;
+ }
+ }
+
+ return decodedValue;
+}
+
+const TargetingGetters = {
+ get locale() {
+ return Services.locale.appLocaleAsBCP47;
+ },
+ get localeLanguageCode() {
+ return (
+ Services.locale.appLocaleAsBCP47 &&
+ Services.locale.appLocaleAsBCP47.substr(0, 2)
+ );
+ },
+ get browserSettings() {
+ const { settings } = lazy.TelemetryEnvironment.currentEnvironment;
+ return {
+ update: settings.update,
+ };
+ },
+ get attributionData() {
+ // Attribution is determined at startup - so we can use the cached attribution at this point
+ return lazy.AttributionCode.getCachedAttributionData();
+ },
+ get currentDate() {
+ return new Date();
+ },
+ get profileAgeCreated() {
+ return lazy.ProfileAge().then(times => times.created);
+ },
+ get profileAgeReset() {
+ return lazy.ProfileAge().then(times => times.reset);
+ },
+ get usesFirefoxSync() {
+ return Services.prefs.prefHasUserValue(FXA_USERNAME_PREF);
+ },
+ get isFxAEnabled() {
+ return lazy.isFxAEnabled;
+ },
+ get isFxASignedIn() {
+ return new Promise(resolve => {
+ if (!lazy.isFxAEnabled) {
+ resolve(false);
+ }
+ if (Services.prefs.getStringPref(FXA_USERNAME_PREF, "")) {
+ resolve(true);
+ }
+ lazy.fxAccounts
+ .getSignedInUser()
+ .then(data => resolve(!!data))
+ .catch(e => resolve(false));
+ });
+ },
+ get sync() {
+ return {
+ desktopDevices: lazy.clientsDevicesDesktop,
+ mobileDevices: lazy.clientsDevicesMobile,
+ totalDevices: lazy.syncNumClients,
+ };
+ },
+ get xpinstallEnabled() {
+ // This is needed for all add-on recommendations, to know if we allow xpi installs in the first place
+ return lazy.isXPIInstallEnabled;
+ },
+ get addonsInfo() {
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ if (bts?.isBackgroundTaskMode) {
+ return { addons: {}, isFullData: true };
+ }
+
+ return lazy.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() {
+ const NONE = { installed: [], current: "" };
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ if (bts?.isBackgroundTaskMode) {
+ return Promise.resolve(NONE);
+ }
+ 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(NONE));
+ });
+ },
+ get isDefaultBrowser() {
+ return QueryCache.getters.isDefaultBrowser.get().catch(() => null);
+ },
+ get devToolsOpenedCount() {
+ return lazy.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 lazy.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 lazy.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 lazy.hasAccessedFxAPanel;
+ },
+ get isWhatsNewPanelEnabled() {
+ return lazy.isWhatsNewPanelEnabled;
+ },
+ get userPrefs() {
+ return {
+ cfrFeatures: lazy.cfrFeaturesUserPref,
+ cfrAddons: lazy.cfrAddonsUserPref,
+ snippets: lazy.snippetsUserPref,
+ };
+ },
+ get totalBlockedCount() {
+ return lazy.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 lazy.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 isChinaRepack() {
+ return (
+ Services.prefs
+ .getDefaultBranch(null)
+ .getCharPref(DISTRIBUTION_ID_PREF, "default") ===
+ DISTRIBUTION_ID_CHINA_REPACK
+ );
+ },
+ get userId() {
+ return lazy.ClientEnvironment.userId;
+ },
+ get profileRestartCount() {
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ if (bts?.isBackgroundTaskMode) {
+ return 0;
+ }
+ // Counter starts at 1 when a profile is created, substract 1 so the value
+ // returned matches expectations
+ return (
+ lazy.TelemetrySession.getMetadata("targeting").profileSubsessionCounter -
+ 1
+ );
+ },
+ get homePageSettings() {
+ const url = lazy.HomePage.get();
+ const { isWebExt, isCustomUrl, urls } = parseAboutPageURL(url);
+
+ return {
+ isWebExt,
+ isCustomUrl,
+ urls,
+ isDefault: lazy.HomePage.isDefault,
+ isLocked: lazy.HomePage.locked,
+ };
+ },
+ get newtabSettings() {
+ const url = lazy.AboutNewTab.newTabURL;
+ const { isWebExt, isCustomUrl, urls } = parseAboutPageURL(url);
+
+ return {
+ isWebExt,
+ isCustomUrl,
+ isDefault: lazy.AboutNewTab.activityStreamEnabled,
+ url: urls[0].url,
+ host: urls[0].host,
+ };
+ },
+ get activeNotifications() {
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ if (bts?.isBackgroundTaskMode) {
+ // This might need to hook into the alert service to enumerate relevant
+ // persistent native notifications.
+ return false;
+ }
+
+ let window = lazy.BrowserWindowTracker.getTopWindow();
+
+ // Technically this doesn't mean we have active notifications,
+ // but because we use !activeNotifications to check for conflicts, this should return true
+ if (!window) {
+ return true;
+ }
+
+ if (
+ window.gURLBar?.view.isOpen ||
+ window.gNotificationBox?.currentNotification ||
+ window.gBrowser.getNotificationBox()?.currentNotification
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+
+ get isMajorUpgrade() {
+ return lazy.BrowserHandler.majorUpgrade;
+ },
+
+ get hasActiveEnterprisePolicies() {
+ return Services.policies.status === Services.policies.ACTIVE;
+ },
+
+ get userMonthlyActivity() {
+ return QueryCache.queries.UserMonthlyActivity.get();
+ },
+
+ get doesAppNeedPin() {
+ return QueryCache.getters.doesAppNeedPin.get();
+ },
+
+ get doesAppNeedPrivatePin() {
+ return QueryCache.getters.doesAppNeedPrivatePin.get();
+ },
+
+ /**
+ * Is this invocation running in background task mode?
+ *
+ * @return {boolean} `true` if running in background task mode.
+ */
+ get isBackgroundTaskMode() {
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ return !!bts?.isBackgroundTaskMode;
+ },
+
+ /**
+ * A non-empty task name if this invocation is running in background
+ * task mode, or `null` if this invocation is not running in
+ * background task mode.
+ *
+ * @return {string|null} background task name or `null`.
+ */
+ get backgroundTaskName() {
+ let bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
+ Ci.nsIBackgroundTasks
+ );
+ return bts?.backgroundTaskName();
+ },
+
+ get userPrefersReducedMotion() {
+ let window = Services.appShell.hiddenDOMWindow;
+ return window?.matchMedia("(prefers-reduced-motion: reduce)")?.matches;
+ },
+
+ /**
+ * Whether or not the user is in the Major Release 2022 holdback study.
+ */
+ get inMr2022Holdback() {
+ return (
+ lazy.NimbusFeatures.majorRelease2022.getVariable("onboarding") === false
+ );
+ },
+
+ /**
+ * The distribution id, if any.
+ * @return {string}
+ */
+ get distributionId() {
+ return Services.prefs
+ .getDefaultBranch(null)
+ .getCharPref("distribution.id", "");
+ },
+
+ /** Where the Firefox View button is shown, if at all.
+ * @return {string} container of the button if it is shown in the toolbar/overflow menu
+ * @return {string} `null` if the button has been removed
+ */
+ get fxViewButtonAreaType() {
+ let button = lazy.CustomizableUI.getWidget("firefox-view-button");
+ return button.areaType;
+ },
+
+ isDefaultHandler: {
+ get html() {
+ return QueryCache.getters.isDefaultHTMLHandler.get();
+ },
+ get pdf() {
+ return QueryCache.getters.isDefaultPDFHandler.get();
+ },
+ },
+
+ get defaultPDFHandler() {
+ return QueryCache.getters.defaultPDFHandler.get();
+ },
+
+ get creditCardsSaved() {
+ return getAutofillRecords({ collectionName: "creditCards" });
+ },
+
+ get addressesSaved() {
+ return getAutofillRecords({ collectionName: "addresses" });
+ },
+
+ /**
+ * Has the user ever used the Migration Wizard to migrate bookmarks?
+ * @return {boolean} `true` if bookmark migration has occurred.
+ */
+ get hasMigratedBookmarks() {
+ return lazy.hasMigratedBookmarks;
+ },
+
+ /**
+ * Has the user ever used the Migration Wizard to migrate history?
+ * @return {boolean} `true` if history migration has occurred.
+ */
+ get hasMigratedHistory() {
+ return lazy.hasMigratedHistory;
+ },
+
+ /**
+ * Has the user ever used the Migration Wizard to migrate passwords?
+ * @return {boolean} `true` if password migration has occurred.
+ */
+ get hasMigratedPasswords() {
+ return lazy.hasMigratedPasswords;
+ },
+
+ /**
+ * Returns true if the user is configured to use the embedded migration
+ * wizard in about:welcome by having
+ * "browser.migrate.content-modal.about-welcome-behavior" be equal to
+ * "embedded".
+ * @return {boolean} `true` if the embedded migration wizard is enabled.
+ */
+ get useEmbeddedMigrationWizard() {
+ return lazy.useEmbeddedMigrationWizard;
+ },
+
+ /**
+ * Whether the user installed Firefox via the RTAMO flow.
+ * @return {boolean} `true` when RTAMO has been used to download Firefox,
+ * `false` otherwise.
+ */
+ get isRTAMO() {
+ const { attributionData } = this;
+
+ return (
+ attributionData?.source === "addons.mozilla.org" &&
+ !!decodeAttributionValue(attributionData?.content)?.startsWith("rta:")
+ );
+ },
+
+ /**
+ * Whether the user installed via the device migration flow.
+ * @return {boolean} `true` when the link to download the browser was part
+ * of guidance for device migration. `false` otherwise.
+ */
+ get isDeviceMigration() {
+ const { attributionData } = this;
+
+ return attributionData?.campaign === "migration";
+ },
+};
+
+const ASRouterTargeting = {
+ Environment: TargetingGetters,
+
+ /**
+ * Snapshot the current targeting environment.
+ *
+ * Asynchronous getters are handled. Getters that throw or reject
+ * are ignored.
+ *
+ * @param {object} target - the environment to snapshot.
+ * @return {object} snapshot of target with `environment` object and `version`
+ * integer.
+ */
+ async getEnvironmentSnapshot(target = ASRouterTargeting.Environment) {
+ async function resolve(object) {
+ if (typeof object === "object" && object !== null) {
+ if (Array.isArray(object)) {
+ return Promise.all(object.map(async item => resolve(await item)));
+ }
+
+ if (object instanceof Date) {
+ return object;
+ }
+
+ // One promise for each named property. Label promises with property name.
+ const promises = Object.keys(object).map(async key => {
+ // Each promise needs to check if we're shutting down when it is evaluated.
+ if (Services.startup.shuttingDown) {
+ throw new Error(
+ "shutting down, so not querying targeting environment"
+ );
+ }
+
+ const value = await resolve(await object[key]);
+
+ return [key, value];
+ });
+
+ const resolved = {};
+ for (const result of await Promise.allSettled(promises)) {
+ // Ignore properties that are rejected.
+ if (result.status === "fulfilled") {
+ const [key, value] = result.value;
+ resolved[key] = value;
+ }
+ }
+
+ return resolved;
+ }
+
+ return object;
+ }
+
+ const environment = await resolve(target);
+
+ // Should we need to migrate in the future.
+ const snapshot = { environment, version: 1 };
+
+ return snapshot;
+ },
+
+ 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) {
+ lazy.ASRouterPreferences.console.debug(
+ "in checkMessageTargeting, arguments = ",
+ Array.from(arguments) // eslint-disable-line prefer-rest-params
+ );
+
+ // 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;
+ }
+ }
+ // Used to report the source of the targeting error in the case of
+ // undesired events
+ targetingContext.setTelemetrySource(message.id);
+ result = await targetingContext.evalWithDefault(message.targeting);
+ if (shouldCache) {
+ jexlEvaluationCache.set(message.targeting, {
+ timestamp: Date.now(),
+ value: result,
+ });
+ }
+ } catch (error) {
+ if (onError) {
+ onError(error, message);
+ }
+ console.error(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 });
+ lazy.ASRouterPreferences.console.debug(
+ "in findMatchingMessage, sortedMessages = ",
+ sortedMessages
+ );
+ const matching = returnAll ? [] : null;
+ const targetingContext = new lazy.TargetingContext(
+ lazy.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;
+ },
+};
+
+const 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..6f3ddd32ca
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterTriggerListeners.jsm
@@ -0,0 +1,1087 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AboutReaderParent: "resource:///actors/AboutReaderParent.sys.mjs",
+ BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ clearTimeout: "resource://gre/modules/Timer.sys.mjs",
+ setTimeout: "resource://gre/modules/Timer.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(lazy, "log", () => {
+ const { Logger } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/Logger.sys.mjs"
+ );
+ return new Logger("ASRouterTriggerListeners");
+});
+
+const FEW_MINUTES = 15 * 60 * 1000; // 15 mins
+
+function isPrivateWindow(win) {
+ return (
+ !(win instanceof Ci.nsIDOMWindow) ||
+ win.closed ||
+ lazy.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) {
+ console.error(e);
+ }
+ return new MatchPatternSet([]);
+}
+
+/**
+ * A Map from trigger IDs to singleton trigger listeners. Each listener must
+ * have idempotent `init` and `uninit` methods.
+ */
+const 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);
+ lazy.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) {
+ lazy.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);
+ lazy.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) {
+ lazy.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);
+ lazy.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) {
+ lazy.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}`);
+ }
+ }
+ },
+ },
+ ],
+ [
+ "formAutofill",
+ {
+ id: "formAutofill",
+ _initialized: false,
+ _triggerHandler: null,
+ _triggerDelay: 10000, // 10 second delay before triggering
+ _topic: "formautofill-storage-changed",
+ _events: ["add", "update", "notifyUsed"] /** @see AutofillRecords */,
+ _collections: ["addresses", "creditCards"] /** @see AutofillRecords */,
+
+ init(triggerHandler) {
+ if (!this._initialized) {
+ Services.obs.addObserver(this, this._topic);
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ },
+
+ uninit() {
+ if (this._initialized) {
+ Services.obs.removeObserver(this, this._topic);
+ this._initialized = false;
+ this._triggerHandler = null;
+ }
+ },
+
+ observe(subject, topic, data) {
+ const browser =
+ Services.wm.getMostRecentBrowserWindow()?.gBrowser.selectedBrowser;
+ if (
+ !browser ||
+ topic !== this._topic ||
+ !subject.wrappedJSObject ||
+ // Ignore changes caused by manual edits in the credit card/address
+ // managers in about:preferences.
+ browser.contentWindow?.gSubDialog?.dialogs.length
+ ) {
+ return;
+ }
+ let { sourceSync, collectionName } = subject.wrappedJSObject;
+ // Ignore changes from sync and changes to untracked collections.
+ if (sourceSync || !this._collections.includes(collectionName)) {
+ return;
+ }
+ if (this._events.includes(data)) {
+ let event = data;
+ let type = collectionName;
+ if (event === "notifyUsed") {
+ event = "use";
+ }
+ if (type === "creditCards") {
+ type = "card";
+ }
+ if (type === "addresses") {
+ type = "address";
+ }
+ lazy.setTimeout(() => {
+ if (
+ this._initialized &&
+ // Make sure the browser still exists and is still selected.
+ browser.isConnectedAndReady &&
+ browser ===
+ Services.wm.getMostRecentBrowserWindow()?.gBrowser
+ .selectedBrowser
+ ) {
+ this._triggerHandler(browser, {
+ id: this.id,
+ context: { event, type },
+ });
+ }
+ }, this._triggerDelay);
+ }
+ },
+ },
+ ],
+
+ [
+ "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);
+ lazy.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"
+ );
+ lazy.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;
+ }
+ },
+ },
+ ],
+
+ [
+ "captivePortalLogin",
+ {
+ id: "captivePortalLogin",
+ _initialized: false,
+ _triggerHandler: null,
+
+ _shouldShowCaptivePortalVPNPromo() {
+ return lazy.BrowserUtils.shouldShowVPNPromo();
+ },
+
+ init(triggerHandler) {
+ if (!this._initialized) {
+ Services.obs.addObserver(this, "captive-portal-login-success");
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ },
+
+ observe(aSubject, aTopic, aData) {
+ switch (aTopic) {
+ case "captive-portal-login-success":
+ const browser = Services.wm.getMostRecentBrowserWindow();
+ // The check is here rather than in init because some
+ // folks leave their browsers running for a long time,
+ // eg from before leaving on a plane trip to after landing
+ // in the new destination, and the current region may have
+ // changed since init time.
+ if (browser && this._shouldShowCaptivePortalVPNPromo()) {
+ this._triggerHandler(browser.gBrowser.selectedBrowser, {
+ id: this.id,
+ });
+ }
+ break;
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ this._triggerHandler = null;
+ this._initialized = false;
+ Services.obs.removeObserver(this, "captive-portal-login-success");
+ }
+ },
+ },
+ ],
+
+ [
+ "preferenceObserver",
+ {
+ id: "preferenceObserver",
+ _initialized: false,
+ _triggerHandler: null,
+ _observedPrefs: [],
+
+ init(triggerHandler, prefs) {
+ if (!this._initialized) {
+ this._triggerHandler = triggerHandler;
+ this._initialized = true;
+ }
+ prefs.forEach(pref => {
+ this._observedPrefs.push(pref);
+ Services.prefs.addObserver(pref, this);
+ });
+ },
+
+ observe(aSubject, aTopic, aData) {
+ switch (aTopic) {
+ case "nsPref:changed":
+ const browser = Services.wm.getMostRecentBrowserWindow();
+ if (browser && this._observedPrefs.includes(aData)) {
+ this._triggerHandler(browser.gBrowser.selectedBrowser, {
+ id: this.id,
+ param: {
+ type: aData,
+ },
+ });
+ }
+ break;
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ this._observedPrefs.forEach(pref =>
+ Services.prefs.removeObserver(pref, this)
+ );
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._observedPrefs = [];
+ }
+ },
+ },
+ ],
+ [
+ "nthTabClosed",
+ {
+ id: "nthTabClosed",
+ _initialized: false,
+ _triggerHandler: null,
+ // Number of tabs the user closed this session
+ _closedTabs: 0,
+
+ init(triggerHandler) {
+ this._triggerHandler = triggerHandler;
+ if (!this._initialized) {
+ lazy.EveryWindow.registerCallback(
+ this.id,
+ win => {
+ win.addEventListener("TabClose", this);
+ },
+ win => {
+ win.removeEventListener("TabClose", this);
+ }
+ );
+ this._initialized = true;
+ }
+ },
+ handleEvent(event) {
+ if (this._initialized) {
+ if (!event.target.ownerGlobal.gBrowser) {
+ return;
+ }
+ const { gBrowser } = event.target.ownerGlobal;
+ this._closedTabs++;
+ this._triggerHandler(gBrowser.selectedBrowser, {
+ id: this.id,
+ context: { tabsClosedCount: this._closedTabs },
+ });
+ }
+ },
+ uninit() {
+ if (this._initialized) {
+ lazy.EveryWindow.unregisterCallback(this.id);
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._closedTabs = 0;
+ }
+ },
+ },
+ ],
+ [
+ "activityAfterIdle",
+ {
+ id: "activityAfterIdle",
+ _initialized: false,
+ _triggerHandler: null,
+ _idleService: null,
+ // Optimization - only report idle state after one minute of idle time.
+ // This represents a minimum idleForMilliseconds of 60000.
+ _idleThreshold: 60,
+ _idleSince: null,
+ _quietSince: null,
+ _awaitingVisibilityChange: false,
+ // Fire the trigger 2 seconds after activity resumes to ensure user is
+ // actively using the browser when it fires.
+ _triggerDelay: 2000,
+ _triggerTimeout: null,
+ // We may get an idle notification immediately after waking from sleep.
+ // The idle time in such a case will be the amount of time since the last
+ // user interaction, which was before the computer went to sleep. We want
+ // to ignore them in that case, so we ignore idle notifications that
+ // happen within 1 second of the last wake notification.
+ _wakeDelay: 1000,
+ _lastWakeTime: null,
+ _listenedEvents: ["visibilitychange", "TabClose", "TabAttrModified"],
+ // When the OS goes to sleep or the process is suspended, we want to drop
+ // the idle time, since the time between sleep and wake is expected to be
+ // very long (e.g. overnight). Otherwise, this would trigger on the first
+ // activity after waking/resuming, counting sleep as idle time. This
+ // basically means each session starts with a fresh idle time.
+ _observedTopics: [
+ "sleep_notification",
+ "suspend_process_notification",
+ "wake_notification",
+ "resume_process_notification",
+ "mac_app_activate",
+ ],
+
+ get _isVisible() {
+ return [...Services.wm.getEnumerator("navigator:browser")].some(
+ win => !win.closed && !win.document?.hidden
+ );
+ },
+ get _soundPlaying() {
+ return [...Services.wm.getEnumerator("navigator:browser")].some(win =>
+ win.gBrowser?.tabs.some(tab => tab.soundPlaying)
+ );
+ },
+ init(triggerHandler) {
+ this._triggerHandler = triggerHandler;
+ // Instantiate this here instead of with a lazy service getter so we can
+ // stub it in tests (otherwise we'd have to wait up to 6 minutes for an
+ // idle notification in certain test environments).
+ if (!this._idleService) {
+ this._idleService = Cc[
+ "@mozilla.org/widget/useridleservice;1"
+ ].getService(Ci.nsIUserIdleService);
+ }
+ if (
+ !this._initialized &&
+ !lazy.PrivateBrowsingUtils.permanentPrivateBrowsing
+ ) {
+ this._idleService.addIdleObserver(this, this._idleThreshold);
+ for (let topic of this._observedTopics) {
+ Services.obs.addObserver(this, topic);
+ }
+ lazy.EveryWindow.registerCallback(
+ this.id,
+ win => {
+ for (let ev of this._listenedEvents) {
+ win.addEventListener(ev, this);
+ }
+ },
+ win => {
+ for (let ev of this._listenedEvents) {
+ win.removeEventListener(ev, this);
+ }
+ }
+ );
+ if (!this._soundPlaying) {
+ this._quietSince = Date.now();
+ }
+ this._initialized = true;
+ this.log("Initialized: ", {
+ idleTime: this._idleService.idleTime,
+ quietSince: this._quietSince,
+ });
+ }
+ },
+ observe(subject, topic, data) {
+ if (this._initialized) {
+ this.log("Heard observer notification: ", {
+ subject,
+ topic,
+ data,
+ idleTime: this._idleService.idleTime,
+ idleSince: this._idleSince,
+ quietSince: this._quietSince,
+ lastWakeTime: this._lastWakeTime,
+ });
+ switch (topic) {
+ case "idle":
+ const now = Date.now();
+ // If the idle notification is within 1 second of the last wake
+ // notification, ignore it. We do this to avoid counting time the
+ // computer spent asleep as "idle time"
+ const isImmediatelyAfterWake =
+ this._lastWakeTime &&
+ now - this._lastWakeTime < this._wakeDelay;
+ if (!isImmediatelyAfterWake) {
+ this._idleSince = now - subject.idleTime;
+ }
+ break;
+ case "active":
+ // Trigger when user returns from being idle.
+ if (this._isVisible) {
+ this._onActive();
+ this._idleSince = null;
+ this._lastWakeTime = null;
+ } else if (this._idleSince) {
+ // If the window is not visible, we want to wait until it is
+ // visible before triggering.
+ this._awaitingVisibilityChange = true;
+ }
+ break;
+ // OS/process notifications
+ case "wake_notification":
+ case "resume_process_notification":
+ case "mac_app_activate":
+ this._lastWakeTime = Date.now();
+ // Fall through to reset idle time.
+ default:
+ this._idleSince = null;
+ }
+ }
+ },
+ handleEvent(event) {
+ if (this._initialized) {
+ switch (event.type) {
+ case "visibilitychange":
+ if (this._awaitingVisibilityChange && this._isVisible) {
+ this._onActive();
+ this._idleSince = null;
+ this._lastWakeTime = null;
+ this._awaitingVisibilityChange = false;
+ }
+ break;
+ case "TabAttrModified":
+ // Listen for DOMAudioPlayback* events.
+ if (!event.detail?.changed?.includes("soundplaying")) {
+ break;
+ }
+ // fall through
+ case "TabClose":
+ this.log("Tab sound changed: ", {
+ event,
+ idleTime: this._idleService.idleTime,
+ idleSince: this._idleSince,
+ quietSince: this._quietSince,
+ });
+ // Maybe update time if a tab closes with sound playing.
+ if (this._soundPlaying) {
+ this._quietSince = null;
+ } else if (!this._quietSince) {
+ this._quietSince = Date.now();
+ }
+ }
+ }
+ },
+ _onActive() {
+ this.log("User is active: ", {
+ idleTime: this._idleService.idleTime,
+ idleSince: this._idleSince,
+ quietSince: this._quietSince,
+ lastWakeTime: this._lastWakeTime,
+ });
+ if (this._idleSince && this._quietSince) {
+ const win = Services.wm.getMostRecentBrowserWindow();
+ if (win && !isPrivateWindow(win) && !this._triggerTimeout) {
+ // Number of ms since the last user interaction/audio playback
+ const idleForMilliseconds =
+ Date.now() - Math.min(this._idleSince, this._quietSince);
+ this._triggerTimeout = lazy.setTimeout(() => {
+ this._triggerHandler(win.gBrowser.selectedBrowser, {
+ id: this.id,
+ context: { idleForMilliseconds },
+ });
+ this._triggerTimeout = null;
+ }, this._triggerDelay);
+ }
+ }
+ },
+ uninit() {
+ if (this._initialized) {
+ this._idleService.removeIdleObserver(this, this._idleThreshold);
+ for (let topic of this._observedTopics) {
+ Services.obs.removeObserver(this, topic);
+ }
+ lazy.EveryWindow.unregisterCallback(this.id);
+ lazy.clearTimeout(this._triggerTimeout);
+ this._triggerTimeout = null;
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._idleSince = null;
+ this._quietSince = null;
+ this._lastWakeTime = null;
+ this._awaitingVisibilityChange = false;
+ this.log("Uninitialized");
+ }
+ },
+ log(...args) {
+ lazy.log.debug("Idle trigger :>>", ...args);
+ },
+
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIObserver",
+ "nsISupportsWeakReference",
+ ]),
+ },
+ ],
+ [
+ "cookieBannerDetected",
+ {
+ id: "cookieBannerDetected",
+ _initialized: false,
+ _triggerHandler: null,
+
+ init(triggerHandler) {
+ this._triggerHandler = triggerHandler;
+ if (!this._initialized) {
+ lazy.EveryWindow.registerCallback(
+ this.id,
+ win => {
+ win.addEventListener("cookiebannerdetected", this);
+ },
+ win => {
+ win.removeEventListener("cookiebannerdetected", this);
+ }
+ );
+ this._initialized = true;
+ }
+ },
+ handleEvent(event) {
+ if (this._initialized) {
+ const win = event.target || Services.wm.getMostRecentBrowserWindow();
+ if (!win) {
+ return;
+ }
+ this._triggerHandler(win.gBrowser.selectedBrowser, {
+ id: this.id,
+ });
+ }
+ },
+ uninit() {
+ if (this._initialized) {
+ lazy.EveryWindow.unregisterCallback(this.id);
+ this._initialized = false;
+ this._triggerHandler = null;
+ }
+ },
+ },
+ ],
+]);
+
+const EXPORTED_SYMBOLS = ["ASRouterTriggerListeners"];
diff --git a/browser/components/newtab/lib/AWScreenUtils.jsm b/browser/components/newtab/lib/AWScreenUtils.jsm
new file mode 100644
index 0000000000..93da92f630
--- /dev/null
+++ b/browser/components/newtab/lib/AWScreenUtils.jsm
@@ -0,0 +1,79 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ ASRouter: "resource://activity-stream/lib/ASRouter.jsm",
+ ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm",
+});
+
+const AWScreenUtils = {
+ /**
+ * Filter the given screens in place with a predicate.
+ *
+ * @param {object[]} screens - The screens to filter.
+ * @param {Function} callback - The predicate for filtering the screens.
+ */
+ async removeScreens(screens, callback) {
+ for (let i = 0; i < screens?.length; i++) {
+ if (await callback(screens[i], i)) {
+ screens.splice(i--, 1);
+ }
+ }
+ },
+ /**
+ * Given a JEXL expression, returns the evaluation of the expression or returns
+ * true if the expression did not evaluate successfully
+ * @param {string} targeting - The JEXL expression that will be evaluated
+ * @returns {boolean}
+ */
+ async evaluateScreenTargeting(targeting) {
+ const result = await lazy.ASRouter.evaluateExpression({
+ expression: targeting,
+ context: lazy.ASRouterTargeting.Environment,
+ });
+ if (result?.evaluationStatus?.success) {
+ return result.evaluationStatus.result;
+ }
+
+ return true;
+ },
+ /**
+ * Filter out screens whose targeting do not match.
+ *
+ * Given an array of screens, each screen will have it's `targeting` property
+ * evaluated, and removed if it's targeting evaluates to false
+ *
+ * @param {object[]} screens - An array of screens that will be looped
+ * through to be evaluated for removal
+ * @returns {object[]} - A new array containing the screens that were not removed
+ */
+ async evaluateTargetingAndRemoveScreens(screens) {
+ const filteredScreens = [...screens];
+ await this.removeScreens(filteredScreens, async screen => {
+ if (screen.targeting === undefined) {
+ // Don't remove the screen if we don't have a targeting property
+ return false;
+ }
+
+ const result = await this.evaluateScreenTargeting(screen.targeting);
+ // Flipping the value because a true evaluation means we
+ // don't want to remove the screen, while false means we do
+ return !result;
+ });
+
+ return filteredScreens;
+ },
+
+ async addScreenImpression(screen) {
+ await lazy.ASRouter.addScreenImpression(screen);
+ },
+};
+
+const EXPORTED_SYMBOLS = ["AWScreenUtils"];
diff --git a/browser/components/newtab/lib/AboutPreferences.jsm b/browser/components/newtab/lib/AboutPreferences.jsm
new file mode 100644
index 0000000000..26eb4d5efe
--- /dev/null
+++ b/browser/components/newtab/lib/AboutPreferences.jsm
@@ -0,0 +1,312 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const HTML_NS = "http://www.w3.org/1999/xhtml";
+const PREFERENCES_LOADED_EVENT = "home-pane-loaded";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+});
+
+// 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://global/skin/icons/search-glass.svg",
+ },
+ {
+ id: "topsites",
+ pref: {
+ feed: "feeds.topsites",
+ titleString: "home-prefs-shortcuts-header",
+ descString: "home-prefs-shortcuts-description",
+ get nestedPrefs() {
+ return Services.prefs.getBoolPref("browser.topsites.useRemoteSetting")
+ ? [
+ {
+ name: "showSponsoredTopSites",
+ titleString: "home-prefs-shortcuts-by-option-sponsored",
+ eventSource: "SPONSORED_TOP_SITES",
+ },
+ ]
+ : [];
+ },
+ },
+ icon: "chrome://browser/skin/topsites.svg",
+ maxRows: 4,
+ rowsPref: "topSitesRows",
+ eventSource: "TOP_SITES",
+ },
+];
+
+const PREFS_AFTER_SECTIONS = () => [
+ {
+ id: "snippets",
+ pref: {
+ feed: "feeds.snippets",
+ titleString: "home-prefs-snippets-header",
+ descString: "home-prefs-snippets-description-new",
+ },
+ icon: "chrome://global/skin/icons/info.svg",
+ eventSource: "SNIPPETS",
+ },
+];
+
+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);
+ }
+
+ const featureConfig = lazy.NimbusFeatures.newtab.getAllVariables() || {};
+
+ this.renderPreferences(window, [
+ ...PREFS_BEFORE_SECTIONS(featureConfig),
+ ...sections,
+ ...PREFS_AFTER_SECTIONS(featureConfig),
+ ]);
+ }
+
+ /**
+ * 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-header2");
+
+ const homeDescription = createAppend("description", contentsGroup);
+ document.l10n.setAttributes(
+ homeDescription,
+ "home-prefs-content-description2"
+ );
+
+ // 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();
+ }
+}
+
+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..bbfe6b3c72
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStream.jsm
@@ -0,0 +1,758 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ DEFAULT_SITES: "resource://activity-stream/lib/DefaultSites.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+});
+
+// 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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "AboutPreferences",
+ "resource://activity-stream/lib/AboutPreferences.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "DefaultPrefs",
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "NewTabInit",
+ "resource://activity-stream/lib/NewTabInit.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "SectionsFeed",
+ "resource://activity-stream/lib/SectionsManager.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "RecommendationProvider",
+ "resource://activity-stream/lib/RecommendationProvider.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "PlacesFeed",
+ "resource://activity-stream/lib/PlacesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "PrefsFeed",
+ "resource://activity-stream/lib/PrefsFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "Store",
+ "resource://activity-stream/lib/Store.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "SystemTickFeed",
+ "resource://activity-stream/lib/SystemTickFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "TelemetryFeed",
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "FaviconFeed",
+ "resource://activity-stream/lib/FaviconFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "TopSitesFeed",
+ "resource://activity-stream/lib/TopSitesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "TopStoriesFeed",
+ "resource://activity-stream/lib/TopStoriesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "HighlightsFeed",
+ "resource://activity-stream/lib/HighlightsFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "DiscoveryStreamFeed",
+ "resource://activity-stream/lib/DiscoveryStreamFeed.jsm"
+);
+
+const REGION_BASIC_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.region-basic-config";
+
+// Determine if spocs should be shown for a geo/locale
+function showSpocs({ geo }) {
+ const spocsGeoString =
+ lazy.NimbusFeatures.pocketNewtab.getVariable("regionSpocsConfig") || "";
+ 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 }) =>
+ lazy.DEFAULT_SITES.get(lazy.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: "chrome://global/skin/icons/pocket.svg",
+ 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}`,
+ show_spocs: showSpocs(args),
+ }),
+ },
+ ],
+ [
+ "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,
+ }),
+ },
+ ],
+ [
+ "showSearch",
+ {
+ title: "Show the Search bar",
+ value: true,
+ },
+ ],
+ [
+ "feeds.snippets",
+ {
+ title: "Show snippets on activity stream",
+ value: false,
+ },
+ ],
+ [
+ "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: [],
+ }),
+ },
+ ],
+ // 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,
+ // 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://firefox-api-proxy.cdn.mozilla.net/,https://spocs.getpocket.com/",
+ },
+ ],
+ [
+ "discoverystream.isCollectionDismissible",
+ {
+ title: "Allows Pocket story collections to be dismissed",
+ value: false,
+ },
+ ],
+ [
+ "discoverystream.onboardingExperience.dismissed",
+ {
+ title: "Allows the user to dismiss the new Pocket onboarding experience",
+ skipBroadcast: true,
+ alsoToPreloaded: true,
+ 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: "{}",
+ },
+ ],
+ [
+ "showRecentSaves",
+ {
+ title: "Control whether a user wants recent saves visible on Newtab",
+ value: true,
+ },
+ ],
+]);
+
+// Array of each feed's FEEDS_CONFIG factory and values to add to PREFS_CONFIG
+const FEEDS_DATA = [
+ {
+ name: "aboutpreferences",
+ factory: () => new lazy.AboutPreferences(),
+ title: "about:preferences rendering",
+ value: true,
+ },
+ {
+ name: "newtabinit",
+ factory: () => new lazy.NewTabInit(),
+ title: "Sends a copy of the state to each new tab that is opened",
+ value: true,
+ },
+ {
+ name: "places",
+ factory: () => new lazy.PlacesFeed(),
+ title: "Listens for and relays various Places-related events",
+ value: true,
+ },
+ {
+ name: "prefs",
+ factory: () => new lazy.PrefsFeed(PREFS_CONFIG),
+ title: "Preferences",
+ value: true,
+ },
+ {
+ name: "sections",
+ factory: () => new lazy.SectionsFeed(),
+ title: "Manages sections",
+ value: true,
+ },
+ {
+ name: "section.highlights",
+ factory: () => new lazy.HighlightsFeed(),
+ title: "Fetches content recommendations from places db",
+ value: false,
+ },
+ {
+ name: "system.topstories",
+ factory: () =>
+ new lazy.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 =
+ lazy.NimbusFeatures.pocketNewtab.getVariable("regionStoriesBlock") ||
+ "";
+ const preffedRegionsString =
+ lazy.NimbusFeatures.pocketNewtab.getVariable("regionStoriesConfig") ||
+ "";
+ const preffedLocaleListString =
+ lazy.NimbusFeatures.pocketNewtab.getVariable("localeListConfig") || "";
+ 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-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 lazy.SystemTickFeed(),
+ title: "Produces system tick events to periodically check for data expiry",
+ value: true,
+ },
+ {
+ name: "telemetry",
+ factory: () => new lazy.TelemetryFeed(),
+ title: "Relays telemetry-related actions to PingCentre",
+ value: true,
+ },
+ {
+ name: "favicon",
+ factory: () => new lazy.FaviconFeed(),
+ title: "Fetches tippy top manifests from remote service",
+ value: true,
+ },
+ {
+ name: "system.topsites",
+ factory: () => new lazy.TopSitesFeed(),
+ title: "Queries places and gets metadata for Top Sites section",
+ value: true,
+ },
+ {
+ name: "recommendationprovider",
+ factory: () => new lazy.RecommendationProvider(),
+ title: "Handles setup and interaction for the personality provider",
+ value: true,
+ },
+ {
+ name: "discoverystreamfeed",
+ factory: () => new lazy.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);
+}
+
+class ActivityStream {
+ /**
+ * constructor - Initializes an instance of ActivityStream
+ */
+ constructor() {
+ this.initialized = false;
+ this.store = new lazy.Store();
+ this.feeds = FEEDS_CONFIG;
+ this._defaultPrefs = new lazy.DefaultPrefs(PREFS_CONFIG);
+ }
+
+ init() {
+ try {
+ this._updateDynamicPrefs();
+ this._defaultPrefs.init();
+ Services.obs.addObserver(this, "intl:app-locales-changed");
+
+ // 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, lazy.Region.REGION_TOPIC);
+ }
+
+ Services.obs.removeObserver(this, "intl:app-locales-changed");
+
+ this.store.uninit();
+ this.initialized = false;
+ }
+
+ _updateDynamicPrefs() {
+ // Save the geo pref if we have it
+ if (lazy.Region.home) {
+ this.geo = lazy.Region.home;
+ } else if (this.geo !== "") {
+ // Watch for geo changes and use a dummy value for now
+ Services.obs.addObserver(this, lazy.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 "intl:app-locales-changed":
+ case lazy.Region.REGION_TOPIC:
+ 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..c4dafc4fa7
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamMessageChannel.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";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AboutHomeStartupCache: "resource:///modules/BrowserGlue.sys.mjs",
+ AboutNewTabParent: "resource:///actors/AboutNewTabParent.sys.mjs",
+});
+
+const {
+ actionCreators: ac,
+ actionTypes: at,
+ actionUtils: au,
+} = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const ABOUT_NEW_TAB_URL = "about:newtab";
+
+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",
+};
+
+class ActivityStreamMessageChannel {
+ /**
+ * ActivityStreamMessageChannel - This module connects a Redux store to the new tab page actor.
+ * You should use the BroadcastToContent, AlsoToOneContent, and AlsoToMain action creators
+ * in common/Actions.sys.mjs 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 the channel is attached, such as about:newtab.
+ * @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.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);
+ }
+
+ /**
+ * Get an iterator over the loaded tab objects.
+ */
+ get loadedTabs() {
+ // In the test, AboutNewTabParent is not defined.
+ return lazy.AboutNewTabParent?.loadedTabs || new Map();
+ }
+
+ /**
+ * 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 (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.
+ lazy.AboutHomeStartupCache.onPreloadedNewTabMessage();
+
+ for (let { actor } of this.loadedTabs.values()) {
+ try {
+ actor.sendAsyncMessage(this.outgoingMessageName, action);
+ } catch (e) {
+ // The target page is closed/closing by the user or test, so just ignore.
+ }
+ }
+ }
+
+ /**
+ * 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 a port number.
+ * It is generated in AboutNewTabChild.sys.mjs.
+ */
+ validatePortID(id) {
+ if (typeof id !== "string" || !id.includes(":")) {
+ console.error("Invalid portID");
+ }
+
+ return id;
+ }
+
+ /**
+ * getTargetById - Retrieve the message target by portID, if it exists
+ *
+ * @param {string} id A portID
+ * @return {obj|null} The message target, if it exists.
+ */
+ getTargetById(id) {
+ this.validatePortID(id);
+
+ for (let { portID, actor } of this.loadedTabs.values()) {
+ if (portID === id) {
+ return actor;
+ }
+ }
+ 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.
+ lazy.AboutHomeStartupCache.onPreloadedNewTabMessage();
+
+ const preloadedActors = this.getPreloadedActors();
+ if (preloadedActors && action.data) {
+ for (let preloadedActor of preloadedActors) {
+ try {
+ preloadedActor.sendAsyncMessage(this.outgoingMessageName, action);
+ } catch (e) {
+ // The preloaded page is no longer available, so just ignore.
+ }
+ }
+ }
+ }
+
+ /**
+ * getPreloadedActors - Retrieve the preloaded actors
+ *
+ * @return {Array|null} An array of actors belonging to the preloaded browsers, or null
+ * if there aren't any preloaded browsers
+ */
+ getPreloadedActors() {
+ let preloadedActors = [];
+ for (let { actor, browser } of this.loadedTabs.values()) {
+ if (this.isPreloadedBrowser(browser)) {
+ preloadedActors.push(actor);
+ }
+ }
+ return preloadedActors.length ? preloadedActors : 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";
+ }
+
+ simulateMessagesForExistingTabs() {
+ // Some pages might have already loaded, so we won't get the usual message
+ for (const loadedTab of this.loadedTabs.values()) {
+ let simulatedDetails = {
+ actor: loadedTab.actor,
+ browser: loadedTab.browser,
+ browsingContext: loadedTab.browsingContext,
+ portID: loadedTab.portID,
+ url: loadedTab.url,
+ simulated: true,
+ };
+
+ this.onActionFromContent(
+ {
+ type: at.NEW_TAB_INIT,
+ data: simulatedDetails,
+ },
+ loadedTab.portID
+ );
+
+ if (loadedTab.loaded) {
+ this.tabLoaded(simulatedDetails);
+ }
+ }
+ }
+
+ /**
+ * onNewTabInit - Handler for special RemotePage:Init message fired
+ * on initialization.
+ *
+ * @param {obj} msg The messsage from a page that was just initialized
+ * @param {obj} tabDetails details about a loaded tab
+ *
+ * tabDetails contains:
+ * actor, browser, browsingContext, portID, url
+ */
+ onNewTabInit(msg, tabDetails) {
+ this.onActionFromContent(
+ {
+ type: at.NEW_TAB_INIT,
+ data: tabDetails,
+ },
+ msg.data.portID
+ );
+ }
+
+ /**
+ * onNewTabLoad - Handler for special RemotePage:Load message fired on page load.
+ *
+ * @param {obj} msg The messsage from a page that was just loaded
+ * @param {obj} tabDetails details about a loaded tab, similar to onNewTabInit
+ */
+ onNewTabLoad(msg, tabDetails) {
+ this.tabLoaded(tabDetails);
+ }
+
+ tabLoaded(tabDetails) {
+ tabDetails.loaded = true;
+
+ let { browser } = tabDetails;
+ 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 }, tabDetails.portID);
+ }
+
+ /**
+ * onNewTabUnloadLoad - Handler for special RemotePage:Unload message fired
+ * on page unload.
+ *
+ * @param {obj} msg The messsage from a page that was just unloaded
+ * @param {obj} tabDetails details about a loaded tab, similar to onNewTabInit
+ */
+ onNewTabUnload(msg, tabDetails) {
+ this.onActionFromContent({ type: at.NEW_TAB_UNLOAD }, tabDetails.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
+ * @param {obj} tabDetails details about a loaded tab, similar to onNewTabInit
+ */
+ onMessage(msg, tabDetails) {
+ if (!msg.data || !msg.data.type) {
+ console.error(
+ new Error(
+ `Received an improperly formatted message from ${tabDetails.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 = {
+ browser: tabDetails.browser,
+ };
+
+ this.onActionFromContent(action, tabDetails.portID);
+ }
+}
+
+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..8614671903
--- /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.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const { Preferences } = ChromeUtils.importESModule(
+ "resource://gre/modules/Preferences.sys.mjs"
+);
+
+const ACTIVITY_STREAM_PREF_BRANCH = "browser.newtabpage.activity-stream.";
+
+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);
+ }
+}
+
+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..f34e289f8a
--- /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/. */
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ IndexedDB: "resource://gre/modules/IndexedDB.sys.mjs",
+});
+
+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 lazy.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 lazy.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/CFRMessageProvider.sys.mjs b/browser/components/newtab/lib/CFRMessageProvider.sys.mjs
new file mode 100644
index 0000000000..d183400f82
--- /dev/null
+++ b/browser/components/newtab/lib/CFRMessageProvider.sys.mjs
@@ -0,0 +1,821 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 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 CFR_MESSAGES = [
+ {
+ id: "FACEBOOK_CONTAINER_3",
+ template: "cfr_doorhanger",
+ groups: ["cfr-message-provider"],
+ 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://browser/skin/addons/addon-install-downloading.svg",
+ 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",
+ groups: ["cfr-message-provider"],
+ 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://browser/skin/addons/addon-install-downloading.svg",
+ 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",
+ groups: ["cfr-message-provider"],
+ 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://browser/skin/addons/addon-install-downloading.svg",
+ 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",
+ groups: ["cfr-message-provider"],
+ 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://browser/skin/addons/addon-install-downloading.svg",
+ 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",
+ groups: ["cfr-message-provider"],
+ 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://browser/skin/addons/addon-install-downloading.svg",
+ 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: "DOH_ROLLOUT_CONFIRMATION",
+ groups: ["cfr-message-provider"],
+ 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://global/skin/icons/security.svg",
+ buttons: {
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-doh-secondary-button" },
+ action: {
+ type: "DISABLE_DOH",
+ },
+ },
+ ],
+ primary: {
+ label: { string_id: "cfr-doorhanger-doh-primary-button-2" },
+ 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",
+ groups: ["cfr-message-provider"],
+ frequency: {
+ lifetime: 3,
+ },
+ targeting:
+ "(!type || type == 'save') && isFxAEnabled == true && usesFirefoxSync == false",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "icon_and_message",
+ text: "Securely store and sync your passwords to all your devices.",
+ 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: {
+ value: "Turn on Sync",
+ attributes: { accesskey: "T" },
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "sync",
+ entrypoint: "cfr-save-login",
+ },
+ },
+ },
+ },
+ bucket_id: "CFR_SAVE_LOGIN",
+ heading_text: "Never Lose a Password Again",
+ 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",
+ groups: ["cfr-message-provider"],
+ frequency: {
+ lifetime: 3,
+ },
+ targeting:
+ "type == 'update' && isFxAEnabled == true && usesFirefoxSync == false",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "icon_and_message",
+ text: "Securely store and sync your passwords to all your devices.",
+ 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: {
+ value: "Turn on Sync",
+ attributes: { accesskey: "T" },
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "sync",
+ entrypoint: "cfr-update-login",
+ },
+ },
+ },
+ },
+ bucket_id: "CFR_UPDATE_LOGIN",
+ heading_text: "Never Lose a Password Again",
+ 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: "MILESTONE_MESSAGE",
+ groups: ["cfr-message-provider"],
+ template: "milestone_message",
+ content: {
+ layout: "short_message",
+ category: "cfrFeatures",
+ anchor_id: "tracking-protection-icon-container",
+ skip_address_bar_notifier: true,
+ bucket_id: "CFR_MILESTONE_MESSAGE",
+ heading_text: { string_id: "cfr-doorhanger-milestone-heading2" },
+ 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",
+ groups: ["cfr-message-provider"],
+ 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",
+ groups: ["cfr-message-provider"],
+ 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://global/skin/icons/search-glass.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",
+ groups: ["cfr-message-provider"],
+ 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" },
+ },
+ {
+ id: "PREF_OBSERVER_MESSAGE_94",
+ groups: ["cfr-message-provider"],
+ targeting: "true",
+ template: "infobar",
+ content: {
+ type: "global",
+ text: "This is a message triggered when a pref value changes",
+ buttons: [
+ {
+ label: "OK",
+ primary: true,
+ accessKey: "O",
+ action: {
+ type: "CANCEL",
+ },
+ },
+ ],
+ },
+ trigger: { id: "preferenceObserver", params: ["foo.bar"] },
+ },
+];
+
+export const CFRMessageProvider = {
+ getMessages() {
+ return Promise.resolve(CFR_MESSAGES.filter(msg => !msg.exclude));
+ },
+};
diff --git a/browser/components/newtab/lib/CFRPageActions.jsm b/browser/components/newtab/lib/CFRPageActions.jsm
new file mode 100644
index 0000000000..2051e5f5f7
--- /dev/null
+++ b/browser/components/newtab/lib/CFRPageActions.jsm
@@ -0,0 +1,1049 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ CustomizableUI: "resource:///modules/CustomizableUI.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.sys.mjs",
+});
+
+XPCOMUtils.defineLazyServiceGetter(
+ lazy,
+ "TrackingDBService",
+ "@mozilla.org/tracking-db-service;1",
+ "nsITrackingDBService"
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "milestones",
+ "browser.contentblocking.cfr-milestone.milestones",
+ "[]",
+ null,
+ JSON.parse
+);
+
+const POPUP_NOTIFICATION_ID = "contextual-feature-recommendation";
+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",
+ });
+ }
+ }
+
+ reloadL10n() {
+ lazy.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");
+ }
+ }
+ }
+
+ _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") {
+ const message = RecommendationMap.get(this.currentNotification?.browser);
+ this._sendTelemetry({
+ message_id: message?.id,
+ bucket_id: message?.content.bucket_id,
+ event: "DISMISS",
+ });
+ 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) {
+ const data = { action: "cfr_user_event", source: "CFR", ...ping };
+ if (lazy.PrivateBrowsingUtils.isWindowPrivate(this.window)) {
+ data.is_private = true;
+ }
+ this._dispatchCFRAction({
+ type: "DOORHANGER_TELEMETRY",
+ data,
+ });
+ }
+
+ _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];
+ }
+
+ console.error(`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 lazy.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 _setAddonRating(document, content) {
+ 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 { rating } = content.addon;
+ if (rating) {
+ const MAX_RATING = 5;
+ const STARS_WIDTH = 16 * MAX_RATING;
+ const calcWidth = stars => `${(stars / MAX_RATING) * STARS_WIDTH}px`;
+ const filledWidth =
+ rating <= MAX_RATING ? calcWidth(rating) : calcWidth(MAX_RATING);
+ const emptyWidth =
+ rating <= MAX_RATING ? calcWidth(MAX_RATING - rating) : calcWidth(0);
+
+ footerFilledStars.style.width = filledWidth;
+ footerEmptyStars.style.width = emptyWidth;
+
+ 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", users);
+ footerUsers.hidden = false;
+ } else {
+ // Prevent whitespace around empty label from affecting other spacing
+ footerUsers.hidden = true;
+ footerUsers.removeAttribute("value");
+ }
+ }
+
+ _createElementAndAppend({ type, id }, parent) {
+ let element = this.window.document.createXULElement(type);
+ if (id) {
+ element.setAttribute("id", id);
+ }
+ parent.appendChild(element);
+ return element;
+ }
+
+ async _renderMilestonePopup(message, browser) {
+ this.maybeLoadCustomElement(this.window);
+
+ let { content, id } = message;
+ let { primary, secondary } = content.buttons;
+ let earliestDate = await lazy.TrackingDBService.getEarliestRecordedDate();
+ let timestamp = new Date().getTime(earliestDate);
+ let panelTitle = "";
+ let headerLabel = this.window.document.getElementById(
+ "cfr-notification-header-label"
+ );
+ let reachedMilestone = 0;
+ let totalSaved = await lazy.TrackingDBService.sumAllEvents();
+ for (let milestone of lazy.milestones) {
+ if (totalSaved >= milestone) {
+ reachedMilestone = milestone;
+ }
+ }
+ if (headerLabel.firstChild) {
+ headerLabel.firstChild.remove();
+ }
+ headerLabel.appendChild(
+ lazy.RemoteL10n.createElement(this.window.document, "span", {
+ content: message.content.heading_text,
+ attributes: {
+ blockedCount: reachedMilestone,
+ date: timestamp,
+ },
+ })
+ );
+
+ // 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 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,
+ },
+ ];
+
+ // Actually show the notification
+ this.currentNotification = this.window.PopupNotifications.show(
+ browser,
+ POPUP_NOTIFICATION_ID,
+ panelTitle,
+ "cfr",
+ mainAction,
+ secondaryActions,
+ {
+ hideClose: true,
+ persistWhileVisible: true,
+ recordTelemetryInPrivateBrowsing: content.show_in_private_browsing,
+ }
+ );
+ 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 } = 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 persistent = !!content.persistent_doorhanger;
+ let options = {
+ persistent,
+ persistWhileVisible: persistent,
+ recordTelemetryInPrivateBrowsing: content.show_in_private_browsing,
+ };
+ let panelTitle;
+
+ headerLabel.value = await this.getStrings(content.heading_text);
+ if (content.info_icon) {
+ 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",
+ });
+ // 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(
+ lazy.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",
+ });
+ 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;
+ default:
+ const authorText = await this.getStrings({
+ string_id: "cfr-doorhanger-extension-author",
+ args: { name: content.addon.author },
+ });
+ panelTitle = await this.getStrings(content.addon.title);
+ await this._setAddonRating(this.window.document, content);
+ if (footerText.firstChild) {
+ footerText.firstChild.remove();
+ }
+ if (footerText.lastChild) {
+ footerText.lastChild.remove();
+ }
+
+ // Main body content of the dropdown
+ footerText.appendChild(
+ lazy.RemoteL10n.createElement(this.window.document, "span", {
+ content: content.text,
+ })
+ );
+
+ 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",
+ });
+
+ footerText.appendChild(footerLink);
+ options = {
+ popupIconURL: content.addon.icon,
+ popupIconClass: content.icon_class,
+ name: authorText,
+ ...options,
+ };
+
+ primaryActionCallback = async () => {
+ primary.action.data.url =
+ // eslint-disable-next-line no-use-before-define
+ 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",
+ });
+ 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,
+ });
+ // 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 } = message;
+
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "CLICK_DOORHANGER",
+ });
+
+ 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;
+ let anchor;
+
+ // 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
+ //If the anchor has been moved to the overflow menu ('menu-panel') and an alt_anchor_id has been provided, we want to use the alt_anchor_id
+
+ if (
+ content.alt_anchor_id &&
+ lazy.CustomizableUI.getWidget(content.anchor_id).areaType.includes(
+ "panel"
+ )
+ ) {
+ anchor = this.window.document.getElementById(content.alt_anchor_id);
+ } else {
+ anchor =
+ this.window.document.getElementById(content.anchor_id) ||
+ this.container;
+ }
+ browser.cfrpopupnotificationanchor = anchor;
+
+ 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/c5c002f81f08a73e04868e0c2bf0eb113f200b03/toolkit/modules/PopupNotifications.sys.mjs#40
+ 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.content.persistent_doorhanger) {
+ 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) {
+ console.error(
+ "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 (!browser) {
+ return false;
+ }
+ // If we are forcing via the Admin page, the browser comes in a different format
+ const win = browser.ownerGlobal;
+ const { id, content } = recommendation;
+ RecommendationMap.set(browser, {
+ id,
+ content,
+ retain: true,
+ });
+ 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) {
+ if (!browser) {
+ return false;
+ }
+ const win = browser.ownerGlobal;
+ 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 } = recommendation;
+ if (
+ !content.show_in_private_browsing &&
+ lazy.PrivateBrowsingUtils.isWindowPrivate(win)
+ ) {
+ return false;
+ }
+ RecommendationMap.set(browser, {
+ id,
+ host,
+ content,
+ retain: true,
+ });
+ 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();
+ }
+ },
+};
+
+const EXPORTED_SYMBOLS = ["CFRPageActions", "PageAction"];
diff --git a/browser/components/newtab/lib/DefaultSites.sys.mjs b/browser/components/newtab/lib/DefaultSites.sys.mjs
new file mode 100644
index 0000000000..ea49cccc03
--- /dev/null
+++ b/browser/components/newtab/lib/DefaultSites.sys.mjs
@@ -0,0 +1,46 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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_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/",
+ ],
+]);
+
+// Immutable for export.
+export const 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..0297ca0b4c
--- /dev/null
+++ b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm
@@ -0,0 +1,2427 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 lazy = {};
+ChromeUtils.defineESModuleGetters(lazy, {
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ pktApi: "chrome://pocket/content/pktApi.sys.mjs",
+ PersistentCache: "resource://activity-stream/lib/PersistentCache.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+ RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
+});
+const { setTimeout, clearTimeout } = ChromeUtils.importESModule(
+ "resource://gre/modules/Timer.sys.mjs"
+);
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+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_PERSONALIZATION_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
+const MAX_LIFETIME_CAP = 500; // Guard against misconfiguration on the server
+const FETCH_TIMEOUT = 45 * 1000;
+const SPOCS_URL = "https://spocs.getpocket.com/spocs";
+const FEED_URL =
+ "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?version=3&consumer_key=$apiKey&locale_lang=$locale&region=$region&count=30";
+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_USER_TOPSITES = "feeds.topsites";
+const PREF_SYSTEM_TOPSITES = "feeds.system.topsites";
+const PREF_SPOCS_CLEAR_ENDPOINT = "discoverystream.endpointSpocsClear";
+const PREF_SHOW_SPONSORED = "showSponsored";
+const PREF_SHOW_SPONSORED_TOPSITES = "showSponsoredTopSites";
+const PREF_SPOC_IMPRESSIONS = "discoverystream.spoc.impressions";
+const PREF_FLIGHT_BLOCKS = "discoverystream.flight.blocks";
+const PREF_REC_IMPRESSIONS = "discoverystream.rec.impressions";
+const PREF_COLLECTIONS_ENABLED =
+ "discoverystream.sponsored-collections.enabled";
+const PREF_POCKET_BUTTON = "extensions.pocket.enabled";
+const PREF_COLLECTION_DISMISSIBLE = "discoverystream.isCollectionDismissible";
+const PREF_PERSONALIZATION = "discoverystream.personalization.enabled";
+const PREF_PERSONALIZATION_OVERRIDE =
+ "discoverystream.personalization.override";
+
+let getHardcodedLayout;
+
+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 lazy.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(Services.uuid.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
+ console.error(
+ `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 lazy.Region.home;
+ }
+
+ get isBff() {
+ if (this._isBff === undefined) {
+ const pocketConfig =
+ this.store.getState().Prefs.values?.pocketConfig || {};
+
+ const preffedLocaleListString = pocketConfig.localeListConfig || "";
+ const preffedLocales = preffedLocaleListString
+ .split(",")
+ .map(s => s.trim());
+ const localeEnabled = this.locale && preffedLocales.includes(this.locale);
+
+ const preffedRegionBffConfigString = pocketConfig.regionBffConfig || "";
+ const preffedRegionBffConfig = preffedRegionBffConfigString
+ .split(",")
+ .map(s => s.trim());
+ const regionBff = preffedRegionBffConfig.includes(this.region);
+ this._isBff = !localeEnabled && regionBff;
+ }
+
+ return this._isBff;
+ }
+
+ get showSpocs() {
+ // High level overall sponsored check, if one of these is true,
+ // we know we need some sort of spoc control setup.
+ return this.showSponsoredStories || this.showSponsoredTopsites;
+ }
+
+ get showSponsoredStories() {
+ // Combine user-set sponsored opt-out with Mozilla-set config
+ return (
+ this.store.getState().Prefs.values[PREF_SHOW_SPONSORED] &&
+ this.config.show_spocs
+ );
+ }
+
+ get showSponsoredTopsites() {
+ const placements = this.getPlacements();
+ // Combine user-set sponsored opt-out with placement data
+ return !!(
+ this.store.getState().Prefs.values[PREF_SHOW_SPONSORED_TOPSITES] &&
+ placements.find(placement => placement.name === "sponsored-topsites")
+ );
+ }
+
+ get showStories() {
+ // Combine user-set stories opt-out with Mozilla-set config
+ return (
+ this.store.getState().Prefs.values[PREF_SYSTEM_TOPSTORIES] &&
+ this.store.getState().Prefs.values[PREF_USER_TOPSTORIES]
+ );
+ }
+
+ get showTopsites() {
+ // Combine user-set topsites opt-out with Mozilla-set config
+ return (
+ this.store.getState().Prefs.values[PREF_SYSTEM_TOPSITES] &&
+ this.store.getState().Prefs.values[PREF_USER_TOPSITES]
+ );
+ }
+
+ get personalized() {
+ // If stories are not displayed, no point in trying to personalize them.
+ if (!this.showStories) {
+ return false;
+ }
+ const spocsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.spocsPersonalized;
+ const recsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.recsPersonalized;
+ const personalization =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION];
+
+ // There is a server sent flag to keep personalization on.
+ // If the server stops sending this, we turn personalization off,
+ // until the server starts returning the signal.
+ const overrideState =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION_OVERRIDE];
+
+ return (
+ personalization &&
+ !overrideState &&
+ !!this.recommendationProvider &&
+ (spocsPersonalized || recsPersonalized)
+ );
+ }
+
+ get recommendationProvider() {
+ if (this._recommendationProvider) {
+ return this._recommendationProvider;
+ }
+ this._recommendationProvider = this.store.feeds.get(
+ "feeds.recommendationprovider"
+ );
+ return this._recommendationProvider;
+ }
+
+ setupConfig(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,
+ },
+ })
+ );
+ }
+
+ setupPrefs(isStartup = false) {
+ const pocketNewtabExperiment = lazy.ExperimentAPI.getExperimentMetaData({
+ featureId: "pocketNewtab",
+ });
+
+ const pocketNewtabRollout = lazy.ExperimentAPI.getRolloutMetaData({
+ featureId: "pocketNewtab",
+ });
+
+ // We want to know if the user is in an experiment or rollout,
+ // but we prioritize experiments over rollouts.
+ const experimentMetaData = pocketNewtabExperiment || pocketNewtabRollout;
+
+ let utmSource = "pocket-newtab";
+ let utmCampaign = experimentMetaData?.slug;
+ let utmContent = experimentMetaData?.branch?.slug;
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_EXPERIMENT_DATA,
+ data: {
+ utmSource,
+ utmCampaign,
+ utmContent,
+ },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+
+ const pocketButtonEnabled = Services.prefs.getBoolPref(PREF_POCKET_BUTTON);
+
+ const nimbusConfig = this.store.getState().Prefs.values?.pocketConfig || {};
+ const { region } = this.store.getState().Prefs.values;
+
+ this.setupSpocsCacheUpdateTime();
+ const saveToPocketCardRegions = nimbusConfig.saveToPocketCardRegions
+ ?.split(",")
+ .map(s => s.trim());
+ const saveToPocketCard =
+ pocketButtonEnabled &&
+ (nimbusConfig.saveToPocketCard ||
+ saveToPocketCardRegions?.includes(region));
+
+ const hideDescriptionsRegions = nimbusConfig.hideDescriptionsRegions
+ ?.split(",")
+ .map(s => s.trim());
+ const hideDescriptions =
+ nimbusConfig.hideDescriptions ||
+ hideDescriptionsRegions?.includes(region);
+
+ // We don't BroadcastToContent for this, as the changes may
+ // shift around elements on an open newtab the user is currently reading.
+ // So instead we AlsoToPreloaded so the next tab is updated.
+ // This is because setupPrefs is called by the system and not a user interaction.
+ this.store.dispatch(
+ ac.AlsoToPreloaded({
+ type: at.DISCOVERY_STREAM_PREFS_SETUP,
+ data: {
+ recentSavesEnabled: nimbusConfig.recentSavesEnabled,
+ pocketButtonEnabled,
+ saveToPocketCard,
+ hideDescriptions,
+ compactImages: nimbusConfig.compactImages,
+ imageGradient: nimbusConfig.imageGradient,
+ newSponsoredLabel: nimbusConfig.newSponsoredLabel,
+ titleLines: nimbusConfig.titleLines,
+ descLines: nimbusConfig.descLines,
+ readTime: nimbusConfig.readTime,
+ },
+ 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,
+ },
+ })
+ );
+ }
+
+ async setupPocketState(target) {
+ let dispatch = action =>
+ this.store.dispatch(ac.OnlyToOneContent(action, target));
+ const isUserLoggedIn = lazy.pktApi.isUserLoggedIn();
+ dispatch({
+ type: at.DISCOVERY_STREAM_POCKET_STATE_SET,
+ data: {
+ isUserLoggedIn,
+ },
+ });
+
+ // If we're not logged in, don't bother fetching recent saves, we're done.
+ if (isUserLoggedIn) {
+ let recentSaves = await lazy.pktApi.getRecentSavesCache();
+ if (recentSaves) {
+ // We have cache, so we can use those.
+ dispatch({
+ type: at.DISCOVERY_STREAM_RECENT_SAVES,
+ data: {
+ recentSaves,
+ },
+ });
+ } else {
+ // We don't have cache, so fetch fresh stories.
+ lazy.pktApi.getRecentSaves({
+ success(data) {
+ dispatch({
+ type: at.DISCOVERY_STREAM_RECENT_SAVES,
+ data: {
+ recentSaves: data,
+ },
+ });
+ },
+ error(error) {},
+ });
+ }
+ }
+ }
+
+ uninitPrefs() {
+ // Reset in-memory cache
+ this._prefCache = {};
+ }
+
+ async fetchFromEndpoint(rawEndpoint, options = {}) {
+ if (!rawEndpoint) {
+ console.error("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) {
+ console.error(`Failed to fetch ${endpoint}: ${error.message}`);
+ }
+ return null;
+ }
+
+ get spocsCacheUpdateTime() {
+ if (this._spocsCacheUpdateTime) {
+ return this._spocsCacheUpdateTime;
+ }
+ this.setupSpocsCacheUpdateTime();
+ return this._spocsCacheUpdateTime;
+ }
+
+ setupSpocsCacheUpdateTime() {
+ const nimbusConfig = this.store.getState().Prefs.values?.pocketConfig || {};
+ const { spocsCacheTimeout } = nimbusConfig;
+ const MAX_TIMEOUT = 30;
+ const MIN_TIMEOUT = 5;
+ // We do a bit of min max checking the the configured value is between
+ // 5 and 30 minutes, to protect against unreasonable values.
+ if (
+ spocsCacheTimeout &&
+ spocsCacheTimeout <= MAX_TIMEOUT &&
+ spocsCacheTimeout >= MIN_TIMEOUT
+ ) {
+ // This value is in minutes, but we want ms.
+ this._spocsCacheUpdateTime = spocsCacheTimeout * 60 * 1000;
+ } else {
+ // The const is already in ms.
+ this._spocsCacheUpdateTime = SPOCS_FEEDS_UPDATE_TIME;
+ }
+ }
+
+ /**
+ * 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: this.spocsCacheUpdateTime,
+ 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.showSpocs && this.isExpired({ cachedData, key: "spocs" }),
+ feeds:
+ this.showStories &&
+ (!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 {
+ console.error("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.filter(
+ c => c.placement && c.spocs
+ )) {
+ // If we find a valid placement, we set it to this value.
+ let placement;
+
+ // We need to check to see if this placement is on or not.
+ // If this placement has a prefs array, check against that.
+ if (component.spocs.prefs) {
+ // Check every pref in the array to see if this placement is turned on.
+ if (
+ component.spocs.prefs.length &&
+ component.spocs.prefs.every(
+ p => this.store.getState().Prefs.values[p]
+ )
+ ) {
+ // This placement is on.
+ placement = component.placement;
+ }
+ } else if (this.showSponsoredStories) {
+ // If we do not have a prefs array, use old check.
+ // This is because Pocket spocs uses an old non pref method.
+ placement = component.placement;
+ }
+
+ // Validate this placement and check for dupes.
+ if (placement?.name && !placementsMap[placement.name]) {
+ placementsMap[placement.name] = placement;
+ placements.push(placement);
+ }
+ }
+ }
+
+ // Update placements data.
+ // Even if we have no placements, we still want to update it to clear it.
+ 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();
+ }
+
+ parseGridPositions(csvPositions) {
+ let gridPositions;
+
+ // Only accept parseable non-negative integers
+ try {
+ gridPositions = csvPositions.map(index => {
+ let parsedInt = parseInt(index, 10);
+
+ if (!isNaN(parsedInt) && parsedInt >= 0) {
+ return parsedInt;
+ }
+
+ throw new Error("Bad input");
+ });
+ } catch (e) {
+ // Catch spoc positions that are not numbers or negative, and do nothing.
+ // We have hard coded backup positions.
+ gridPositions = undefined;
+ }
+
+ return gridPositions;
+ }
+
+ async loadLayout(sendUpdate, isStartup) {
+ let layoutResp = {};
+ let url = "";
+
+ if (!this.config.hardcoded_layout) {
+ layoutResp = await this.fetchLayout(isStartup);
+ }
+
+ if (!layoutResp || !layoutResp.layout) {
+ const isBasicLayout =
+ this.config.hardcoded_basic_layout ||
+ this.store.getState().Prefs.values[PREF_HARDCODED_BASIC_LAYOUT] ||
+ this.store.getState().Prefs.values[PREF_REGION_BASIC_LAYOUT];
+
+ const sponsoredCollectionsEnabled =
+ this.store.getState().Prefs.values[PREF_COLLECTIONS_ENABLED];
+
+ const pocketConfig =
+ this.store.getState().Prefs.values?.pocketConfig || {};
+ const onboardingExperience =
+ this.isBff && pocketConfig.onboardingExperience;
+
+ let items = isBasicLayout ? 3 : 21;
+ if (pocketConfig.fourCardLayout || pocketConfig.hybridLayout) {
+ items = isBasicLayout ? 4 : 24;
+ }
+
+ const prepConfArr = arr => {
+ return arr
+ ?.split(",")
+ .filter(item => item)
+ .map(item => parseInt(item, 10));
+ };
+
+ const spocAdTypes = prepConfArr(pocketConfig.spocAdTypes);
+ const spocZoneIds = prepConfArr(pocketConfig.spocZoneIds);
+ const spocTopsitesAdTypes = prepConfArr(pocketConfig.spocTopsitesAdTypes);
+ const spocTopsitesZoneIds = prepConfArr(pocketConfig.spocTopsitesZoneIds);
+ const { spocSiteId } = pocketConfig;
+ let spocPlacementData;
+ let spocTopsitesPlacementData;
+ let spocsUrl;
+
+ if (spocAdTypes?.length && spocZoneIds?.length) {
+ spocPlacementData = {
+ ad_types: spocAdTypes,
+ zone_ids: spocZoneIds,
+ };
+ }
+
+ if (spocTopsitesAdTypes?.length && spocTopsitesZoneIds?.length) {
+ spocTopsitesPlacementData = {
+ ad_types: spocTopsitesAdTypes,
+ zone_ids: spocTopsitesZoneIds,
+ };
+ }
+
+ if (spocSiteId) {
+ const newUrl = new URL(SPOCS_URL);
+ newUrl.searchParams.set("site", spocSiteId);
+ spocsUrl = newUrl.href;
+ }
+
+ let feedUrl = FEED_URL;
+
+ if (this.isBff) {
+ feedUrl = `https://${lazy.NimbusFeatures.saveToPocket.getVariable(
+ "bffApi"
+ )}/desktop/v1/recommendations?locale=$locale&region=$region&count=30`;
+ }
+
+ // Set a hardcoded layout if one is needed.
+ // Changing values in this layout in memory object is unnecessary.
+ layoutResp = getHardcodedLayout({
+ spocsUrl,
+ feedUrl,
+ items,
+ sponsoredCollectionsEnabled,
+ spocPlacementData,
+ spocTopsitesPlacementData,
+ spocPositions: this.parseGridPositions(
+ pocketConfig.spocPositions?.split(`,`)
+ ),
+ spocTopsitesPositions: this.parseGridPositions(
+ pocketConfig.spocTopsitesPositions?.split(`,`)
+ ),
+ widgetPositions: this.parseGridPositions(
+ pocketConfig.widgetPositions?.split(`,`)
+ ),
+ widgetData: [
+ ...(this.locale.startsWith("en-") ? [{ type: "TopicsWidget" }] : []),
+ ],
+ hybridLayout: pocketConfig.hybridLayout,
+ hideCardBackground: pocketConfig.hideCardBackground,
+ fourCardLayout: pocketConfig.fourCardLayout,
+ newFooterSection: pocketConfig.newFooterSection,
+ compactGrid: pocketConfig.compactGrid,
+ // For now essentialReadsHeader and editorsPicksHeader are English only.
+ essentialReadsHeader:
+ this.locale.startsWith("en-") && pocketConfig.essentialReadsHeader,
+ editorsPicksHeader:
+ this.locale.startsWith("en-") && pocketConfig.editorsPicksHeader,
+ onboardingExperience,
+ });
+ }
+
+ 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,
+ },
+ });
+ })
+ .catch(
+ /* istanbul ignore next */ error => {
+ console.error(
+ `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;
+ 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 turns personalization on/off if the server sends the override command.
+ // The server sends a true signal to keep personalization on. So a malfunctioning
+ // server would more likely mistakenly turn off personalization, and not turn it on.
+ // This is safer, because the override is for cases where personalization is causing issues.
+ // So having it mistakenly go off is safe, but it mistakenly going on could be bad.
+ personalizationOverride(overrideCommand) {
+ // Are we currently in an override state.
+ // This is useful to know if we want to do a cleanup.
+ const overrideState =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION_OVERRIDE];
+
+ // Is this profile currently set to be personalized.
+ const personalization =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION];
+
+ // If we have an override command, profile is currently personalized,
+ // and is not currently being overridden, we can set the override pref.
+ if (overrideCommand && personalization && !overrideState) {
+ this.store.dispatch(ac.SetPref(PREF_PERSONALIZATION_OVERRIDE, true));
+ }
+
+ // This is if we need to revert an override and do cleanup.
+ // We do this if we are in an override state,
+ // but not currently receiving the override signal.
+ if (!overrideCommand && overrideState) {
+ this.store.dispatch({
+ type: at.CLEAR_PREF,
+ data: { name: PREF_PERSONALIZATION_OVERRIDE },
+ });
+ }
+ }
+
+ updateSponsoredCollectionsPref(collectionEnabled = false) {
+ const currentState =
+ this.store.getState().Prefs.values[PREF_COLLECTIONS_ENABLED];
+
+ // If the current state does not match the new state, update the pref.
+ if (currentState !== collectionEnabled) {
+ this.store.dispatch(
+ ac.SetPref(PREF_COLLECTIONS_ENABLED, collectionEnabled)
+ );
+ }
+ }
+
+ async loadSpocs(sendUpdate, isStartup) {
+ const cachedData = (await this.cache.get()) || {};
+ let spocsState;
+
+ const placements = this.getPlacements();
+
+ if (this.showSpocs && placements?.length) {
+ 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.personalizationOverride(
+ // The server's old signal was for a version override.
+ // When we removed version 1, version 2 was now the defacto only version.
+ // Without a version 1, the override is now a command to turn off personalization.
+ !spocsResponse.settings.feature_flags.spoc_v2
+ );
+ this.updateSponsoredCollectionsPref(
+ spocsResponse.settings.feature_flags.collections
+ );
+ }
+
+ 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 {
+ console.error("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 loadPersonalizationScoresCache(isStartup = false) {
+ const cachedData = (await this.cache.get()) || {};
+ const { personalization } = cachedData;
+
+ if (this.personalized && personalization && personalization.scores) {
+ this.recommendationProvider.setProvider(personalization.scores);
+
+ this.personalizationLastUpdated = personalization._timestamp;
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: this.personalizationLastUpdated,
+ },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+ }
+
+ /*
+ * This creates a new recommendationProvider using fresh data,
+ * It's run on a last updated timer. This is the opposite of loadPersonalizationScoresCache.
+ * 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 updatePersonalizationScores() {
+ if (
+ !this.personalized ||
+ Date.now() - this.personalizationLastUpdated <
+ MIN_PERSONALIZATION_UPDATE_TIME
+ ) {
+ return;
+ }
+
+ this.recommendationProvider.setProvider();
+
+ await this.recommendationProvider.init();
+
+ const personalization = { scores: this.recommendationProvider.getScores() };
+ this.personalizationLastUpdated = Date.now();
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: this.personalizationLastUpdated,
+ },
+ })
+ );
+ personalization._timestamp = this.personalizationLastUpdated;
+ this.cache.set("personalization", personalization);
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "idle-daily":
+ this.updatePersonalizationScores();
+ break;
+ case "nsPref:changed":
+ // If the Pocket button was turned on or off, we need to update the cards
+ // because cards show menu options for the Pocket button that need to be removed.
+ if (data === PREF_POCKET_BUTTON) {
+ this.configReset();
+ }
+ 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?.pocketConfig?.spocsPersonalized;
+ const recsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.recsPersonalized;
+ const personalizedByType =
+ type === "feed" ? recsPersonalized : spocsPersonalized;
+
+ const data = (
+ await Promise.all(
+ items.map(item => this.scoreItem(item, personalizedByType))
+ )
+ )
+ // Sort by highest scores.
+ .sort(this.sortItem);
+
+ return { data };
+ }
+
+ async scoreItem(item, personalizedByType) {
+ item.score = item.item_score;
+ if (item.score !== 0 && !item.score) {
+ item.score = 1;
+ }
+ if (this.personalized && personalizedByType) {
+ await this.recommendationProvider.calculateItemRelevanceScore(item);
+ }
+ return item;
+ }
+
+ filterBlocked(data) {
+ if (data && data.length) {
+ let flights = this.readDataPref(PREF_FLIGHT_BLOCKS);
+ const filteredItems = data.filter(item => {
+ const blocked =
+ lazy.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 })) {
+ let options = {};
+ if (this.isBff) {
+ const headers = new Headers();
+ const oAuthConsumerKey = lazy.NimbusFeatures.saveToPocket.getVariable(
+ "oAuthConsumerKeyBff"
+ );
+ headers.append("consumer_key", oAuthConsumerKey);
+ options = {
+ method: "GET",
+ headers,
+ };
+ }
+
+ const feedResponse = await this.fetchFromEndpoint(feedUrl, options);
+ if (feedResponse) {
+ const { settings = {} } = feedResponse;
+ let { recommendations } = feedResponse;
+ if (this.isBff) {
+ recommendations = feedResponse.data.map(item => ({
+ id: item.tileId,
+ url: item.url,
+ title: item.title,
+ excerpt: item.excerpt,
+ publisher: item.publisher,
+ raw_image_src: item.imageUrl,
+ }));
+ }
+ const { data: scoredItems } = await this.scoreItems(
+ recommendations,
+ "feed"
+ );
+ const { recsExpireTime } = settings;
+ const rotatedItems = this.rotate(scoredItems, recsExpireTime);
+ this.componentFeedFetched = true;
+ feed = {
+ lastUpdated: Date.now(),
+ data: {
+ settings,
+ recommendations: rotatedItems,
+ status: "success",
+ },
+ };
+ } else {
+ console.error("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 personalizationCacheLoadPromise = this.loadPersonalizationScoresCache(
+ options.isStartup
+ );
+
+ const spocsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.spocsPersonalized;
+ const recsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.recsPersonalized;
+
+ 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) {
+ // personalizationCacheLoadPromise 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.
+ personalizationCacheLoadPromise.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.recommendationProvider.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 || this.showTopsites) {
+ const promises = [];
+ // We could potentially have either or both sponsored topsites or stories.
+ // We only make one fetch, and control which to request when we fetch.
+ // So for now we only care if we need to make this request at all.
+ const spocsPromise = this.loadSpocs(dispatch, isStartup).catch(error =>
+ console.error(`Error trying to load spocs feeds: ${error}`)
+ );
+ promises.push(spocsPromise);
+ if (this.showStories) {
+ const storiesPromise = this.loadComponentFeeds(
+ dispatch,
+ isStartup
+ ).catch(error =>
+ console.error(`Error trying to load component feeds: ${error}`)
+ );
+ promises.push(storiesPromise);
+ }
+ await Promise.all(promises);
+ 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("personalization", {});
+ // Reset in-memory caches.
+ this._isBff = undefined;
+ this._spocsCacheUpdateTime = undefined;
+ }
+
+ 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.setupPrefs(false /* isStartup */);
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE,
+ data: {
+ value:
+ this.store.getState().Prefs.values[PREF_COLLECTION_DISMISSIBLE],
+ },
+ })
+ );
+ this.personalizationLastUpdated = 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 specific 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);
+ }
+ }
+
+ onCollectionsChanged() {
+ // Update layout, and reload any off screen tabs.
+ // This does not change any existing open tabs.
+ // It also doesn't update any spoc or rec data, just the layout.
+ const dispatch = action => this.store.dispatch(ac.AlsoToPreloaded(action));
+ this.loadLayout(dispatch, false);
+ }
+
+ 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:
+ case PREF_PERSONALIZATION:
+ // This is a config reset directly related to Discovery Stream pref.
+ this.configReset();
+ break;
+ case PREF_COLLECTIONS_ENABLED:
+ this.onCollectionsChanged();
+ break;
+ case PREF_USER_TOPSITES:
+ case PREF_SYSTEM_TOPSITES:
+ if (
+ !(
+ this.showTopsites ||
+ (this.showStories && this.showSponsoredStories)
+ )
+ ) {
+ // Ensure we delete any remote data potentially related to spocs.
+ this.clearSpocs();
+ }
+ break;
+ case PREF_USER_TOPSTORIES:
+ case PREF_SYSTEM_TOPSTORIES:
+ if (
+ !(
+ this.showStories ||
+ (this.showTopsites && this.showSponsoredTopsites)
+ )
+ ) {
+ // Ensure we delete any remote data potentially related to spocs.
+ this.clearSpocs();
+ }
+ if (action.data.value) {
+ this.enableStories();
+ }
+ break;
+ // Check if spocs was disabled. Remove them if they were.
+ case PREF_SHOW_SPONSORED:
+ case PREF_SHOW_SPONSORED_TOPSITES:
+ const dispatch = update =>
+ this.store.dispatch(ac.BroadcastToContent(update));
+ // We refresh placements data because one of the spocs were turned off.
+ this.updatePlacements(
+ dispatch,
+ this.store.getState().DiscoveryStream.layout
+ );
+ // Currently the order of this is important.
+ // We need to check this after updatePlacements is called,
+ // because some of the spoc logic depends on the result of placement updates.
+ if (
+ !(
+ (this.showSponsoredStories ||
+ (this.showTopSites && this.showSponsoredTopSites)) &&
+ (this.showSponsoredTopsites ||
+ (this.showStories && this.showSponsoredStories))
+ )
+ ) {
+ // Ensure we delete any remote data potentially related to spocs.
+ this.clearSpocs();
+ }
+ // Placements have changed so consider spocs expired, and reload them.
+ await this.cache.set("spocs", {});
+ await this.loadSpocs(dispatch);
+ 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.setupConfig(true /* isStartup */);
+ this.setupPrefs(true /* isStartup */);
+ // 2. If config.enabled is true, start loading data.
+ if (this.config.enabled) {
+ await this.enable();
+ }
+ Services.prefs.addObserver(PREF_POCKET_BUTTON, this);
+ 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:
+ lazy.RemoteSettings.pollChanges();
+ break;
+ case at.DISCOVERY_STREAM_DEV_EXPIRE_CACHE:
+ // Personalization scores 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_POCKET_STATE_INIT:
+ this.setupPocketState(action.meta.fromTarget);
+ 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._recommendationProvider = null;
+ Services.prefs.removeObserver(PREF_POCKET_BUTTON, this);
+ 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);
+ if (action.data.name === "pocketConfig") {
+ await this.onPrefChange();
+ this.setupPrefs(false /* isStartup */);
+ }
+ 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.
+ `spocsUrl` Changing the url for spocs is used for adding a siteId query param.
+ `feedUrl` Where to fetch stories from.
+ `items` How many items to include in the primary card grid.
+ `spocPositions` Changes the position of spoc cards.
+ `spocTopsitesPositions` Changes the position of spoc topsites.
+ `spocPlacementData` Used to set the spoc content.
+ `spocTopsitesPlacementData` Used to set spoc content for topsites.
+ `sponsoredCollectionsEnabled` Tuns on and off the sponsored collection section.
+ `hybridLayout` Changes cards to smaller more compact cards only for specific breakpoints.
+ `hideCardBackground` Removes Pocket card background and borders.
+ `fourCardLayout` Enable four Pocket cards per row.
+ `newFooterSection` Changes the layout of the topics section.
+ `compactGrid` Reduce the number of pixels between the Pocket cards.
+ `essentialReadsHeader` Updates the Pocket section header and title to say "Today’s Essential Reads", moves the "Recommended by Pocket" header to the right side.
+ `editorsPicksHeader` Updates the Pocket section header and title to say "Editor’s Picks", if used with essentialReadsHeader, creates a second section 2 rows down for editorsPicks.
+ `onboardingExperience` Show new users some UI explaining Pocket above the Pocket section.
+*/
+getHardcodedLayout = ({
+ spocsUrl = SPOCS_URL,
+ feedUrl = FEED_URL,
+ items = 21,
+ spocPositions = [1, 5, 7, 11, 18, 20],
+ spocTopsitesPositions = [1],
+ spocPlacementData = { ad_types: [3617], zone_ids: [217758, 217995] },
+ spocTopsitesPlacementData,
+ widgetPositions = [],
+ widgetData = [],
+ sponsoredCollectionsEnabled = false,
+ hybridLayout = false,
+ hideCardBackground = false,
+ fourCardLayout = false,
+ newFooterSection = false,
+ compactGrid = false,
+ essentialReadsHeader = false,
+ editorsPicksHeader = false,
+ onboardingExperience = false,
+}) => ({
+ lastUpdate: Date.now(),
+ spocs: {
+ url: spocsUrl,
+ },
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "TopSites",
+ header: {
+ title: {
+ id: "newtab-section-header-topsites",
+ },
+ },
+ ...(spocTopsitesPlacementData
+ ? {
+ placement: {
+ name: "sponsored-topsites",
+ ad_types: spocTopsitesPlacementData.ad_types,
+ zone_ids: spocTopsitesPlacementData.zone_ids,
+ },
+ spocs: {
+ probability: 1,
+ prefs: [PREF_SHOW_SPONSORED_TOPSITES],
+ positions: spocTopsitesPositions.map(position => {
+ return { index: position };
+ }),
+ },
+ }
+ : {}),
+ properties: {},
+ },
+ ...(sponsoredCollectionsEnabled
+ ? [
+ {
+ 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",
+ essentialReadsHeader,
+ editorsPicksHeader,
+ 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://global/skin/icons/pocket.svg",
+ },
+ properties: {},
+ styles: {
+ ".ds-message": "margin-bottom: -20px",
+ },
+ },
+ {
+ type: "CardGrid",
+ properties: {
+ items,
+ hybridLayout,
+ hideCardBackground,
+ fourCardLayout,
+ compactGrid,
+ essentialReadsHeader,
+ editorsPicksHeader,
+ onboardingExperience,
+ },
+ widgets: {
+ positions: widgetPositions.map(position => {
+ return { index: position };
+ }),
+ data: widgetData,
+ },
+ cta_variant: "link",
+ header: {
+ title: "",
+ },
+ placement: {
+ name: "spocs",
+ ad_types: spocPlacementData.ad_types,
+ zone_ids: spocPlacementData.zone_ids,
+ },
+ feed: {
+ embed_reference: null,
+ url: feedUrl,
+ },
+ spocs: {
+ probability: 1,
+ positions: spocPositions.map(position => {
+ return { index: position };
+ }),
+ },
+ },
+ {
+ type: "Navigation",
+ newFooterSection,
+ 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 & fitness",
+ 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",
+ },
+ ],
+ extraLinks: [
+ {
+ name: "Career",
+ url: "https://getpocket.com/explore/career?utm_source=pocket-newtab",
+ },
+ {
+ name: "Technology",
+ url: "https://getpocket.com/explore/technology?utm_source=pocket-newtab",
+ },
+ ],
+ privacyNoticeURL: {
+ url: "https://www.mozilla.org/privacy/firefox/#suggest-relevant-content",
+ title: {
+ id: "newtab-section-menu-privacy-notice",
+ },
+ },
+ },
+ header: {
+ title: {
+ id: "newtab-pocket-read-more",
+ },
+ },
+ styles: {
+ ".ds-navigation": "margin-top: -10px;",
+ },
+ },
+ ...(newFooterSection
+ ? [
+ {
+ type: "PrivacyLink",
+ properties: {
+ url: "https://www.mozilla.org/privacy/firefox/",
+ title: {
+ id: "newtab-section-menu-privacy-notice",
+ },
+ },
+ },
+ ]
+ : []),
+ ],
+ },
+ ],
+});
+
+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..6c7b756e0d
--- /dev/null
+++ b/browser/components/newtab/lib/DownloadsManager.jsm
@@ -0,0 +1,191 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ DownloadsCommon: "resource:///modules/DownloadsCommon.sys.mjs",
+ DownloadsViewUI: "resource:///modules/DownloadsViewUI.sys.mjs",
+ FileUtils: "resource://gre/modules/FileUtils.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+});
+
+const DOWNLOAD_CHANGED_DELAY_TIME = 1000; // time in ms to delay timer for downloads changed events
+
+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: lazy.DownloadsViewUI.getDisplayName(download),
+ description:
+ lazy.DownloadsViewUI.getSizeWithUnits(download) ||
+ lazy.DownloadsCommon.strings.sizeUnknown,
+ referrer,
+ date_added: download.endTime,
+ };
+ }
+
+ init(store) {
+ this._store = store;
+ this._downloadData = lazy.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 &&
+ lazy.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 => {
+ lazy.DownloadsCommon.copyDownloadLink(download);
+ });
+ break;
+ case at.REMOVE_DOWNLOAD_FILE:
+ doDownloadAction(download => {
+ lazy.DownloadsCommon.deleteDownload(download).catch(console.error);
+ });
+ break;
+ case at.SHOW_DOWNLOAD_FILE:
+ doDownloadAction(download => {
+ lazy.DownloadsCommon.showDownloadedFile(
+ new lazy.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 => {
+ lazy.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;
+ }
+ }
+}
+const 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..0311582919
--- /dev/null
+++ b/browser/components/newtab/lib/FaviconFeed.jsm
@@ -0,0 +1,197 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { getDomain } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/TippyTopProvider.sys.mjs"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
+});
+
+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) {
+ return new Promise(resolve =>
+ lazy.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),
+ lazy.NewTabUtils.activityStreamProvider.THUMB_FAVICON_SIZE
+ )
+ );
+}
+
+/**
+ * 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
+ (${lazy.PlacesUtils.history.TRANSITIONS.REDIRECT_PERMANENT},
+ ${lazy.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 lazy.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) {
+ lazy.PlacesUtils.favicons.setAndFetchFaviconForPage(
+ Services.io.newURI(url),
+ iconInfo.iconUri,
+ false,
+ lazy.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
+ null,
+ Services.scriptSecurityManager.getSystemPrincipal()
+ );
+ }
+ }
+}
+
+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();
+ lazy.PlacesUtils.favicons.setAndFetchFaviconForPage(
+ Services.io.newURI(url),
+ iconUri,
+ false,
+ lazy.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/FeatureCalloutMessages.sys.mjs b/browser/components/newtab/lib/FeatureCalloutMessages.sys.mjs
new file mode 100644
index 0000000000..3dbba0c212
--- /dev/null
+++ b/browser/components/newtab/lib/FeatureCalloutMessages.sys.mjs
@@ -0,0 +1,648 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Eventually, make this a messaging system
+// provider instead of adding these message
+// into OnboardingMessageProvider.jsm
+const FIREFOX_VIEW_PREF = "browser.firefox-view.feature-tour";
+const PDFJS_PREF = "browser.pdfjs.feature-tour";
+// Empty screens are included as placeholders to ensure step
+// indicator shows the correct number of total steps in the tour
+const EMPTY_SCREEN = { content: {} };
+const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
+
+// Generate a JEXL targeting string based on the current screen
+// id found in a given Feature Callout tour progress preference
+// and the `complete` property being true
+const matchCurrentScreenTargeting = (prefName, screenId) => {
+ const prefVal = `'${prefName}' | preferenceValue`;
+ //regExpMatch() is a JEXL filter expression. Here we check if 'screen' and 'complete' exist in the pref's value (which is stringified JSON), and return their values. Returns null otherwise
+ const screenRegEx = '(?<=screen":)"(.*)(?=",)';
+ const completeRegEx = '(?<=complete":)(.*)(?=})';
+
+ const screenMatch = `${prefVal} | regExpMatch('${screenRegEx}')`;
+ const completeMatch = `${prefVal} | regExpMatch('${completeRegEx}')`;
+ //We are checking the return of regExpMatch() here. If it's truthy, we grab the matched string and compare it to the desired value
+ const screenVal = `(${screenMatch}) ? (${screenMatch}[1] == '${screenId}') : false`;
+ const completeVal = `(${completeMatch}) ? (${completeMatch}[1] != "true") : false`;
+
+ return `(${screenVal}) && (${completeVal})`;
+};
+
+/**
+ * add24HourImpressionJEXLTargeting -
+ * Creates a "hasn't been viewed in > 24 hours"
+ * JEXL string and adds it to each message specified
+ *
+ * @param {array} messageIds - IDs of messages that the targeting string will be added to
+ * @param {string} prefix - The prefix of messageIDs that will used to create the JEXL string
+ * @param {array} messages - The array of messages that will be edited
+ * @returns {array} - The array of messages with the appropriate targeting strings edited
+ */
+function add24HourImpressionJEXLTargeting(
+ messageIds,
+ prefix,
+ uneditedMessages
+) {
+ let noImpressionsIn24HoursString = uneditedMessages
+ .filter(message => message.id.startsWith(prefix))
+ .map(
+ message =>
+ // If the last impression is null or if epoch time
+ // of the impression is < current time - 24hours worth of MS
+ `(messageImpressions.${message.id}[messageImpressions.${
+ message.id
+ } | length - 1] == null || messageImpressions.${
+ message.id
+ }[messageImpressions.${message.id} | length - 1] < ${
+ Date.now() - ONE_DAY_IN_MS
+ })`
+ )
+ .join(" && ");
+
+ // We're appending the string here instead of using
+ // template strings to avoid a recursion error from
+ // using the 'messages' variable within itself
+ return uneditedMessages.map(message => {
+ if (messageIds.includes(message.id)) {
+ message.targeting += `&& ${noImpressionsIn24HoursString}`;
+ }
+
+ return message;
+ });
+}
+
+// Exporting the about:firefoxview messages as a method here
+// acts as a safety guard against mutations of the original objects
+const MESSAGES = () => {
+ let messages = [
+ {
+ id: "FIREFOX_VIEW_SPOTLIGHT",
+ template: "spotlight",
+ content: {
+ id: "FIREFOX_VIEW_PROMO",
+ template: "multistage",
+ modal: "tab",
+ screens: [
+ {
+ id: "DEFAULT_MODAL_UI",
+ content: {
+ title: {
+ fontSize: "32px",
+ fontWeight: 400,
+ string_id: "firefoxview-spotlight-promo-title",
+ },
+ subtitle: {
+ fontSize: "15px",
+ fontWeight: 400,
+ marginBlock: "10px",
+ marginInline: "40px",
+ string_id: "firefoxview-spotlight-promo-subtitle",
+ },
+ logo: { height: "48px" },
+ primary_button: {
+ label: {
+ string_id: "firefoxview-spotlight-promo-primarybutton",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "FEATURE_CALLOUT_1",
+ complete: false,
+ }),
+ },
+ },
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "firefoxview-spotlight-promo-secondarybutton",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 3,
+ trigger: {
+ id: "featureCalloutCheck",
+ },
+ frequency: {
+ // Add the highest possible cap to ensure impressions are recorded while allowing the Spotlight to sync across windows/tabs with Firefox View open
+ lifetime: 100,
+ },
+ targeting: `!inMr2022Holdback && source == "about:firefoxview" &&
+ !'browser.newtabpage.activity-stream.asrouter.providers.cfr'|preferenceIsUserSet &&
+ 'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features'|preferenceValue &&
+ ${matchCurrentScreenTargeting(
+ FIREFOX_VIEW_PREF,
+ "FIREFOX_VIEW_SPOTLIGHT"
+ )}`,
+ },
+ {
+ id: "FIREFOX_VIEW_FEATURE_TOUR_1_NO_CWS",
+ template: "feature_callout",
+ content: {
+ id: "FIREFOX_VIEW_FEATURE_TOUR",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ {
+ id: "FEATURE_CALLOUT_1",
+ parent_selector: "#tab-pickup-container",
+ content: {
+ position: "callout",
+ arrow_position: "top",
+ title: {
+ string_id: "callout-firefox-view-tab-pickup-title",
+ },
+ subtitle: {
+ string_id: "callout-firefox-view-tab-pickup-subtitle",
+ },
+ logo: {
+ imageURL: "chrome://browser/content/callout-tab-pickup.svg",
+ darkModeImageURL:
+ "chrome://browser/content/callout-tab-pickup-dark.svg",
+ height: "128px",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-primary-advance-button-label",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "FEATURE_CALLOUT_2",
+ complete: false,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ EMPTY_SCREEN,
+ ],
+ },
+ priority: 3,
+ targeting: `!inMr2022Holdback && source == "about:firefoxview" && ${matchCurrentScreenTargeting(
+ FIREFOX_VIEW_PREF,
+ "FEATURE_CALLOUT_1"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "FIREFOX_VIEW_FEATURE_TOUR_2_NO_CWS",
+ template: "feature_callout",
+ content: {
+ id: "FIREFOX_VIEW_FEATURE_TOUR",
+ startScreen: 1,
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ EMPTY_SCREEN,
+ {
+ id: "FEATURE_CALLOUT_2",
+ parent_selector: "#recently-closed-tabs-container",
+ content: {
+ position: "callout",
+ arrow_position: "bottom",
+ title: {
+ string_id: "callout-firefox-view-recently-closed-title",
+ },
+ subtitle: {
+ string_id: "callout-firefox-view-recently-closed-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-primary-complete-button-label",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: FIREFOX_VIEW_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 3,
+ targeting: `!inMr2022Holdback && source == "about:firefoxview" && ${matchCurrentScreenTargeting(
+ FIREFOX_VIEW_PREF,
+ "FEATURE_CALLOUT_2"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "FIREFOX_VIEW_TAB_PICKUP_REMINDER",
+ template: "feature_callout",
+ content: {
+ id: "FIREFOX_VIEW_TAB_PICKUP_REMINDER",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ {
+ id: "FIREFOX_VIEW_TAB_PICKUP_REMINDER",
+ parent_selector: "#tab-pickup-container",
+ content: {
+ position: "callout",
+ arrow_position: "top",
+ title: {
+ string_id:
+ "continuous-onboarding-firefox-view-tab-pickup-title",
+ },
+ subtitle: {
+ string_id:
+ "continuous-onboarding-firefox-view-tab-pickup-subtitle",
+ },
+ logo: {
+ imageURL: "chrome://browser/content/callout-tab-pickup.svg",
+ darkModeImageURL:
+ "chrome://browser/content/callout-tab-pickup-dark.svg",
+ height: "128px",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr1-onboarding-get-started-primary-button-label",
+ },
+ action: {
+ type: "CLICK_ELEMENT",
+ navigate: true,
+ data: {
+ selector:
+ "#tab-pickup-container button.primary:not(#error-state-button)",
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 2,
+ targeting: `!inMr2022Holdback && source == "about:firefoxview" && "browser.firefox-view.view-count" | preferenceValue > 2
+ && (("identity.fxaccounts.enabled" | preferenceValue == false) || !(("services.sync.engine.tabs" | preferenceValue == true) && ("services.sync.username" | preferenceValue))) && (!messageImpressions.FIREFOX_VIEW_SPOTLIGHT[messageImpressions.FIREFOX_VIEW_SPOTLIGHT | length - 1] || messageImpressions.FIREFOX_VIEW_SPOTLIGHT[messageImpressions.FIREFOX_VIEW_SPOTLIGHT | length - 1] < currentDate|date - ${ONE_DAY_IN_MS})`,
+ frequency: {
+ lifetime: 1,
+ },
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "PDFJS_FEATURE_TOUR_1_A",
+ template: "feature_callout",
+ content: {
+ id: "PDFJS_FEATURE_TOUR",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ {
+ id: "FEATURE_CALLOUT_1_A",
+ parent_selector: "hbox#browser",
+ content: {
+ position: "callout",
+ callout_position_override: {
+ top: "45px",
+ right: "55px",
+ },
+ arrow_position: "top-end",
+ title: {
+ string_id: "callout-pdfjs-edit-title",
+ },
+ subtitle: {
+ string_id: "callout-pdfjs-edit-body-a",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-pdfjs-edit-button",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "FEATURE_CALLOUT_2_A",
+ complete: false,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ EMPTY_SCREEN,
+ ],
+ },
+ priority: 1,
+ targeting: `source == "chrome" && ${matchCurrentScreenTargeting(
+ PDFJS_PREF,
+ "FEATURE_CALLOUT_1_A"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "PDFJS_FEATURE_TOUR_2_A",
+ template: "feature_callout",
+ content: {
+ id: "PDFJS_FEATURE_TOUR",
+ startScreen: 1,
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ EMPTY_SCREEN,
+ {
+ id: "FEATURE_CALLOUT_2_A",
+ parent_selector: "hbox#browser",
+ content: {
+ position: "callout",
+ callout_position_override: {
+ top: "45px",
+ right: "25px",
+ },
+ arrow_position: "top-end",
+ title: {
+ string_id: "callout-pdfjs-draw-title",
+ },
+ subtitle: {
+ string_id: "callout-pdfjs-draw-body-a",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-pdfjs-draw-button",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 1,
+ targeting: `source == "chrome" && ${matchCurrentScreenTargeting(
+ PDFJS_PREF,
+ "FEATURE_CALLOUT_2_A"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "PDFJS_FEATURE_TOUR_1_B",
+ template: "feature_callout",
+ content: {
+ id: "PDFJS_FEATURE_TOUR",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ {
+ id: "FEATURE_CALLOUT_1_B",
+ parent_selector: "hbox#browser",
+ content: {
+ position: "callout",
+ callout_position_override: {
+ top: "45px",
+ right: "55px",
+ },
+ arrow_position: "top-end",
+ title: {
+ string_id: "callout-pdfjs-edit-title",
+ },
+ subtitle: {
+ string_id: "callout-pdfjs-edit-body-b",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-pdfjs-edit-button",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "FEATURE_CALLOUT_2_B",
+ complete: false,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ EMPTY_SCREEN,
+ ],
+ },
+ priority: 1,
+ targeting: `source == "chrome" && ${matchCurrentScreenTargeting(
+ PDFJS_PREF,
+ "FEATURE_CALLOUT_1_B"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ {
+ id: "PDFJS_FEATURE_TOUR_2_B",
+ template: "feature_callout",
+ content: {
+ id: "PDFJS_FEATURE_TOUR",
+ startScreen: 1,
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ disableHistoryUpdates: true,
+ screens: [
+ EMPTY_SCREEN,
+ {
+ id: "FEATURE_CALLOUT_2_B",
+ parent_selector: "hbox#browser",
+ content: {
+ position: "callout",
+ callout_position_override: {
+ top: "45px",
+ right: "25px",
+ },
+ arrow_position: "top-end",
+ title: {
+ string_id: "callout-pdfjs-draw-title",
+ },
+ subtitle: {
+ string_id: "callout-pdfjs-draw-body-b",
+ },
+ primary_button: {
+ label: {
+ string_id: "callout-pdfjs-draw-button",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ dismiss_button: {
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: PDFJS_PREF,
+ value: JSON.stringify({
+ screen: "",
+ complete: true,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 1,
+ targeting: `source == "chrome" && ${matchCurrentScreenTargeting(
+ PDFJS_PREF,
+ "FEATURE_CALLOUT_2_B"
+ )}`,
+ trigger: { id: "featureCalloutCheck" },
+ },
+ ];
+ messages = add24HourImpressionJEXLTargeting(
+ ["FIREFOX_VIEW_TAB_PICKUP_REMINDER"],
+ "FIREFOX_VIEW",
+ messages
+ );
+ return messages;
+};
+
+export const FeatureCalloutMessages = {
+ getMessages() {
+ return MESSAGES();
+ },
+};
diff --git a/browser/components/newtab/lib/FilterAdult.jsm b/browser/components/newtab/lib/FilterAdult.jsm
new file mode 100644
index 0000000000..2ee9c4c467
--- /dev/null
+++ b/browser/components/newtab/lib/FilterAdult.jsm
@@ -0,0 +1,3036 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "gFilterAdultEnabled",
+ "browser.newtabpage.activity-stream.filterAdult",
+ true
+);
+
+// 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);
+}
+
+const FilterAdult = {
+ /**
+ * Filter out any link objects that have a url with an adult base domain.
+ *
+ * @param {string[]} links
+ * An array of links to test.
+ * @returns {string[]}
+ * A filtered array without adult links.
+ */
+ filter(links) {
+ if (!lazy.gFilterAdultEnabled) {
+ return links;
+ }
+
+ return links.filter(({ url }) => {
+ try {
+ const uri = Services.io.newURI(url);
+ return !gAdultSet.has(md5Hash(Services.eTLD.getBaseDomain(uri)));
+ } catch (ex) {
+ return true;
+ }
+ });
+ },
+
+ /**
+ * Determine if the supplied url is an adult url or not.
+ *
+ * @param {string} url
+ * The url to test.
+ * @returns {boolean}
+ * True if it is an adult url.
+ */
+ isAdultUrl(url) {
+ if (!lazy.gFilterAdultEnabled) {
+ return false;
+ }
+ try {
+ const uri = Services.io.newURI(url);
+ return gAdultSet.has(md5Hash(Services.eTLD.getBaseDomain(uri)));
+ } catch (ex) {
+ return false;
+ }
+ },
+
+ /**
+ * For tests, adds a domain to the adult list.
+ */
+ addDomainToList(url) {
+ gAdultSet.add(
+ md5Hash(Services.eTLD.getBaseDomain(Services.io.newURI(url)))
+ );
+ },
+
+ /**
+ * For tests, removes a domain to the adult list.
+ */
+ removeDomainFromList(url) {
+ gAdultSet.delete(
+ md5Hash(Services.eTLD.getBaseDomain(Services.io.newURI(url)))
+ );
+ },
+};
+
+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..45a30bfa97
--- /dev/null
+++ b/browser/components/newtab/lib/HighlightsFeed.jsm
@@ -0,0 +1,350 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+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.importESModule(
+ "resource://activity-stream/common/Reducers.sys.mjs"
+ );
+const { Dedupe } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Dedupe.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "FilterAdult",
+ "resource://activity-stream/lib/FilterAdult.jsm"
+);
+ChromeUtils.defineESModuleGetters(lazy, {
+ LinksCache: "resource://activity-stream/lib/LinksCache.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+});
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "Screenshots",
+ "resource://activity-stream/lib/Screenshots.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "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;
+
+class HighlightsFeed {
+ constructor() {
+ this.dedupe = new Dedupe(this._dedupeKey);
+ this.linksCache = new lazy.LinksCache(
+ lazy.NewTabUtils.activityStreamLinks,
+ "getHighlights",
+ ["image"]
+ );
+ lazy.PageThumbs.addExpirationFilter(this);
+ this.downloadsManager = new lazy.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);
+ lazy.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 = lazy.FilterAdult.filter(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 lazy.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..c75f17f197
--- /dev/null
+++ b/browser/components/newtab/lib/InfoBar.jsm
@@ -0,0 +1,172 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.sys.mjs",
+});
+
+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.gNotificationBox;
+ } else {
+ notificationContainer = gBrowser.getNotificationBox(browser);
+ }
+
+ let priority = content.priority || notificationContainer.PRIORITY_SYSTEM;
+
+ this.notification = notificationContainer.appendNotification(
+ this.message.id,
+ {
+ label: this.formatMessageConfig(doc, content.text),
+ image: content.icon || "chrome://branding/content/icon64.png",
+ priority,
+ eventCallback: this.infobarCallback,
+ },
+ content.buttons.map(b => this.formatButtonConfig(b))
+ );
+
+ this.addImpression();
+ }
+
+ formatMessageConfig(doc, content) {
+ let docFragment = doc.createDocumentFragment();
+ // notificationbox will only `appendChild` for documentFragments
+ docFragment.appendChild(
+ lazy.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") {
+ this.notification = null;
+ // eslint-disable-next-line no-use-before-define
+ InfoBar._activeInfobar = null;
+ } else if (this.notification) {
+ this.sendUserEventTelemetry("DISMISSED");
+ this.notification = null;
+ // eslint-disable-next-line no-use-before-define
+ InfoBar._activeInfobar = null;
+ }
+ }
+
+ sendUserEventTelemetry(event) {
+ const ping = {
+ message_id: this.message.id,
+ event,
+ };
+ this._dispatch({
+ type: "INFOBAR_TELEMETRY",
+ data: { action: "infobar_user_event", ...ping },
+ });
+ }
+}
+
+const InfoBar = {
+ _activeInfobar: null,
+
+ 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) {
+ // Prevent stacking multiple infobars
+ if (this._activeInfobar) {
+ return null;
+ }
+
+ const win = browser?.ownerGlobal;
+
+ if (!win || lazy.PrivateBrowsingUtils.isWindowPrivate(win)) {
+ return null;
+ }
+
+ this.maybeLoadCustomElement(win);
+ this.maybeInsertFTL(win);
+
+ let notification = new InfoBarNotification(message, dispatch);
+ notification.showNotification(browser);
+ this._activeInfobar = true;
+
+ return notification;
+ },
+};
+
+const EXPORTED_SYMBOLS = ["InfoBar"];
diff --git a/browser/components/newtab/lib/LinksCache.sys.mjs b/browser/components/newtab/lib/LinksCache.sys.mjs
new file mode 100644
index 0000000000..0dfb89e74e
--- /dev/null
+++ b/browser/components/newtab/lib/LinksCache.sys.mjs
@@ -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/. */
+
+// 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.
+ */
+export 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..e37d1df8b1
--- /dev/null
+++ b/browser/components/newtab/lib/MomentsPageHub.jsm
@@ -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/. */
+"use strict";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ setInterval: "resource://gre/modules/Timer.sys.mjs",
+ clearInterval: "resource://gre/modules/Timer.sys.mjs",
+});
+
+// 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 = lazy.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() {
+ lazy.clearInterval(this.state._intervalId);
+ this.state = {};
+ this._initialized = false;
+ }
+}
+
+/**
+ * ToolbarBadgeHub - singleton instance of _ToolbarBadgeHub that can initiate
+ * message requests and render messages.
+ */
+const 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..f1a7f0d142
--- /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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+/**
+ * NewTabInit - A placeholder for now. This will send a copy of the state to all
+ * newly opened tabs.
+ */
+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..bcc02aba5f
--- /dev/null
+++ b/browser/components/newtab/lib/OnboardingMessageProvider.jsm
@@ -0,0 +1,1276 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const { FeatureCalloutMessages } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/FeatureCalloutMessages.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ShellService: "resource:///modules/ShellService.sys.mjs",
+});
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "usesFirefoxSync",
+ "services.sync.username"
+);
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "mobileDevices",
+ "services.sync.clients.devices.mobile",
+ 0
+);
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "hidePrivatePin",
+ "browser.startup.upgradeDialog.pinPBM.disabled",
+ false
+);
+
+const L10N = new Localization([
+ "branding/brand.ftl",
+ "browser/newtab/onboarding.ftl",
+ "toolkit/branding/brandings.ftl",
+ "toolkit/branding/accounts.ftl",
+]);
+
+const HOMEPAGE_PREF = "browser.startup.homepage";
+const NEWTAB_PREF = "browser.newtabpage.enabled";
+
+const BASE_MESSAGES = () => [
+ {
+ id: "FXA_ACCOUNTS_BADGE",
+ template: "toolbar_badge",
+ content: {
+ delay: 10000, // delay for 10 seconds
+ target: "fxa-toolbar-menu-button",
+ },
+ targeting: "false",
+ 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" },
+ },
+ {
+ id: "CFR_FIREFOX_VIEW",
+ groups: ["cfr"],
+ template: "cfr_doorhanger",
+ //If Firefox View button has been moved to the overflow menu, we want to change the anchor element
+ content: {
+ bucket_id: "CFR_FIREFOX_VIEW",
+ anchor_id: "firefox-view-button",
+ alt_anchor_id: "nav-bar-overflow-button",
+ layout: "icon_and_message",
+ icon: "chrome://browser/content/cfr-lightning.svg",
+ icon_dark_theme: "chrome://browser/content/cfr-lightning-dark.svg",
+ icon_class: "cfr-doorhanger-small-icon",
+ heading_text: {
+ string_id: "firefoxview-cfr-header-v2",
+ },
+ text: {
+ string_id: "firefoxview-cfr-body-v2",
+ },
+ buttons: {
+ primary: {
+ label: {
+ string_id: "firefoxview-cfr-primarybutton",
+ },
+ action: {
+ type: "OPEN_FIREFOX_VIEW",
+ navigate: true,
+ },
+ },
+ secondary: [
+ {
+ label: {
+ string_id: "firefoxview-cfr-secondarybutton",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ ],
+ },
+ skip_address_bar_notifier: true,
+ },
+ frequency: {
+ lifetime: 1,
+ },
+ trigger: {
+ id: "nthTabClosed",
+ },
+ // Avoid breaking existing tests that close tabs for now.
+ targeting: `!inMr2022Holdback && fxViewButtonAreaType != null && (currentDate|date - profileAgeCreated) / 86400000 >= 2 && tabsClosedCount >= 3 && 'browser.firefox-view.view-count'|preferenceValue == 0 && !'browser.newtabpage.activity-stream.asrouter.providers.cfr'|preferenceIsUserSet`,
+ },
+ {
+ id: "FX_MR_106_UPGRADE",
+ template: "spotlight",
+ targeting: "true",
+ content: {
+ template: "multistage",
+ id: "FX_MR_106_UPGRADE",
+ transitions: true,
+ modal: "tab",
+ screens: [
+ {
+ id: "UPGRADE_PIN_FIREFOX",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-155px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-pin-image-alt",
+ },
+ progress_bar: "true",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-pintaskbar.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-existing-pin-header",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-existing-pin-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-pin-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ },
+ checkbox: {
+ label: {
+ string_id: "mr2022-onboarding-existing-pin-checkbox-label",
+ },
+ defaultValue: true,
+ action: {
+ type: "MULTI_ACTION",
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ data: {
+ privatePin: true,
+ },
+ },
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ ],
+ },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "UPGRADE_SET_DEFAULT",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-60px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-default-image-alt",
+ },
+ progress_bar: "true",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-settodefault.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-set-default-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-set-default-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-set-default-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "UPGRADE_IMPORT_SETTINGS",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-42px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-import-image-alt",
+ },
+ progress_bar: "true",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-import.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-import-header",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-import-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id:
+ "mr2022-onboarding-import-primary-button-label-no-attribution",
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "UPGRADE_MOBILE_DOWNLOAD",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-160px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-mobile-download-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-mobilecrosspromo.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-mobile-download-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-mobile-download-subtitle",
+ },
+ hero_image: {
+ url: "chrome://activity-stream/content/data/content/assets/mobile-download-qr-existing-user.svg",
+ },
+ cta_paragraph: {
+ text: {
+ string_id: "mr2022-onboarding-mobile-download-cta-text",
+ string_name: "download-label",
+ },
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://www.mozilla.org/firefox/mobile/get-app/?utm_medium=firefox-desktop&utm_source=onboarding-modal&utm_campaign=mr2022&utm_content=existing-global",
+ where: "tab",
+ },
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "UPGRADE_PIN_PRIVATE_WINDOW",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-100px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-pin-private-image-alt",
+ },
+ progress_bar: "true",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-pinprivate.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-upgrade-onboarding-pin-private-window-header",
+ },
+ subtitle: {
+ string_id:
+ "mr2022-upgrade-onboarding-pin-private-window-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id:
+ "mr2022-upgrade-onboarding-pin-private-window-primary-button-label",
+ },
+ action: {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ data: {
+ privatePin: true,
+ },
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "UPGRADE_DATA_RECOMMENDATION",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-80px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-privacy-segmentation-image-alt",
+ },
+ progress_bar: "true",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-privacysegmentation.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-privacy-segmentation-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-privacy-segmentation-subtitle",
+ },
+ cta_paragraph: {
+ text: {
+ string_id: "mr2022-onboarding-privacy-segmentation-text-cta",
+ },
+ },
+ primary_button: {
+ label: {
+ string_id:
+ "mr2022-onboarding-privacy-segmentation-button-primary-label",
+ },
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "browser.dataFeatureRecommendations.enabled",
+ value: true,
+ },
+ },
+ navigate: true,
+ },
+ },
+ additional_button: {
+ label: {
+ string_id:
+ "mr2022-onboarding-privacy-segmentation-button-secondary-label",
+ },
+ style: "secondary",
+ action: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "browser.dataFeatureRecommendations.enabled",
+ value: false,
+ },
+ },
+ navigate: true,
+ },
+ },
+ },
+ },
+ {
+ id: "UPGRADE_GRATITUDE",
+ content: {
+ position: "split",
+ progress_bar: "true",
+ split_narrow_bkg_position: "-228px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-gratitude-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-gratitude.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-gratitude-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-gratitude-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-gratitude-primary-button-label",
+ },
+ action: {
+ type: "OPEN_FIREFOX_VIEW",
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-gratitude-secondary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ {
+ id: "FX_100_UPGRADE",
+ template: "spotlight",
+ targeting: "false",
+ content: {
+ template: "multistage",
+ id: "FX_100_UPGRADE",
+ transitions: true,
+ screens: [
+ {
+ id: "UPGRADE_PIN_FIREFOX",
+ content: {
+ logo: {
+ imageURL:
+ "chrome://activity-stream/content/data/content/assets/heart.webp",
+ height: "73px",
+ },
+ has_noodles: true,
+ title: {
+ fontSize: "36px",
+ string_id: "fx100-upgrade-thanks-header",
+ },
+ title_style: "fancy shine",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/confetti.svg') top / 100% no-repeat var(--in-content-page-background)",
+ subtitle: {
+ string_id: "fx100-upgrade-thanks-keep-body",
+ },
+ primary_button: {
+ label: {
+ string_id: "fx100-thank-you-pin-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ {
+ id: "PB_NEWTAB_FOCUS_PROMO",
+ type: "default",
+ template: "pb_newtab",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "FOCUS",
+ promoHeader: "fluent:about-private-browsing-focus-promo-header-c",
+ promoImageLarge: "chrome://browser/content/assets/focus-promo.png",
+ promoLinkText: "fluent:about-private-browsing-focus-promo-cta",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle: "fluent:about-private-browsing-focus-promo-text-c",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "SHOW_SPOTLIGHT",
+ data: {
+ content: {
+ id: "FOCUS_PROMO",
+ template: "multistage",
+ modal: "tab",
+ backdrop: "transparent",
+ screens: [
+ {
+ id: "DEFAULT_MODAL_UI",
+ content: {
+ logo: {
+ imageURL:
+ "chrome://browser/content/assets/focus-logo.svg",
+ height: "48px",
+ },
+ title: {
+ string_id: "spotlight-focus-promo-title",
+ },
+ subtitle: {
+ string_id: "spotlight-focus-promo-subtitle",
+ },
+ dismiss_button: {
+ action: {
+ navigate: true,
+ },
+ },
+ ios: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/167k4ih?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fapps.apple.com%2Fus%2Fapp%2Ffirefox-focus-privacy-browser%2Fid1055677337",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ android: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/167k4ih?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dorg.mozilla.focus",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ tiles: {
+ type: "mobile_downloads",
+ data: {
+ QR_code: {
+ image_url:
+ "chrome://browser/content/assets/focus-qr-code.svg",
+ alt_text: {
+ string_id: "spotlight-focus-promo-qr-code",
+ },
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ priority: 2,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ // Exclude the next 2 messages: 1) Klar for en 2) Klar for de
+ targeting:
+ "!(region in [ 'DE', 'AT', 'CH'] && localeLanguageCode == 'en') && localeLanguageCode != 'de'",
+ },
+ {
+ id: "PB_NEWTAB_KLAR_PROMO",
+ type: "default",
+ template: "pb_newtab",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "FOCUS",
+ promoHeader: "fluent:about-private-browsing-focus-promo-header-c",
+ promoImageLarge: "chrome://browser/content/assets/focus-promo.png",
+ promoLinkText: "Download Firefox Klar",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle:
+ "Firefox Klar clears your history every time while blocking ads and trackers.",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "SHOW_SPOTLIGHT",
+ data: {
+ content: {
+ id: "KLAR_PROMO",
+ template: "multistage",
+ modal: "tab",
+ backdrop: "transparent",
+ screens: [
+ {
+ id: "DEFAULT_MODAL_UI",
+ order: 0,
+ content: {
+ logo: {
+ imageURL:
+ "chrome://browser/content/assets/focus-logo.svg",
+ height: "48px",
+ },
+ title: "Get Firefox Klar",
+ subtitle: {
+ string_id: "spotlight-focus-promo-subtitle",
+ },
+ dismiss_button: {
+ action: {
+ navigate: true,
+ },
+ },
+ ios: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/a8bxj8j?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fapps.apple.com%2Fde%2Fapp%2Fklar-by-firefox%2Fid1073435754",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ android: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/a8bxj8j?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dorg.mozilla.klar",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ tiles: {
+ type: "mobile_downloads",
+ data: {
+ QR_code: {
+ image_url:
+ "chrome://browser/content/assets/klar-qr-code.svg",
+ alt_text: "Scan the QR code to get Firefox Klar",
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ priority: 2,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ targeting: "region in [ 'DE', 'AT', 'CH'] && localeLanguageCode == 'en'",
+ },
+ {
+ id: "PB_NEWTAB_KLAR_PROMO_DE",
+ type: "default",
+ template: "pb_newtab",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "FOCUS",
+ promoHeader: "fluent:about-private-browsing-focus-promo-header-c",
+ promoImageLarge: "chrome://browser/content/assets/focus-promo.png",
+ promoLinkText: "fluent:about-private-browsing-focus-promo-cta",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle: "fluent:about-private-browsing-focus-promo-text-c",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "SHOW_SPOTLIGHT",
+ data: {
+ content: {
+ id: "FOCUS_PROMO",
+ template: "multistage",
+ modal: "tab",
+ backdrop: "transparent",
+ screens: [
+ {
+ id: "DEFAULT_MODAL_UI",
+ content: {
+ logo: {
+ imageURL:
+ "chrome://browser/content/assets/focus-logo.svg",
+ height: "48px",
+ },
+ title: {
+ string_id: "spotlight-focus-promo-title",
+ },
+ subtitle: {
+ string_id: "spotlight-focus-promo-subtitle",
+ },
+ dismiss_button: {
+ action: {
+ navigate: true,
+ },
+ },
+ ios: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/a8bxj8j?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fapps.apple.com%2Fde%2Fapp%2Fklar-by-firefox%2Fid1073435754",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ android: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/a8bxj8j?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dorg.mozilla.klar",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ tiles: {
+ type: "mobile_downloads",
+ data: {
+ QR_code: {
+ image_url:
+ "chrome://browser/content/assets/klar-qr-code.svg",
+ alt_text: {
+ string_id: "spotlight-focus-promo-qr-code",
+ },
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ priority: 2,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ targeting: "localeLanguageCode == 'de'",
+ },
+ {
+ id: "PB_NEWTAB_INFO_SECTION",
+ template: "pb_newtab",
+ content: {
+ promoEnabled: false,
+ infoEnabled: true,
+ infoIcon: "",
+ infoTitle: "",
+ infoBody: "fluent:about-private-browsing-info-description-private-window",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitleEnabled: false,
+ },
+ targeting: "true",
+ },
+ {
+ id: "PB_NEWTAB_PIN_PROMO",
+ template: "pb_newtab",
+ type: "default",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "PIN",
+ promoHeader: "fluent:about-private-browsing-pin-promo-header",
+ promoImageLarge:
+ "chrome://browser/content/assets/private-promo-asset.svg",
+ promoLinkText: "fluent:about-private-browsing-pin-promo-link-text",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle: "fluent:about-private-browsing-pin-promo-title",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "browser.privateWindowSeparation.enabled",
+ value: true,
+ },
+ },
+ },
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ data: {
+ privatePin: true,
+ },
+ },
+ {
+ type: "BLOCK_MESSAGE",
+ data: {
+ id: "PB_NEWTAB_PIN_PROMO",
+ },
+ },
+ {
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "privatebrowsing", where: "current" },
+ },
+ ],
+ },
+ },
+ },
+ },
+ priority: 3,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ targeting: "!inMr2022Holdback && doesAppNeedPrivatePin",
+ },
+ {
+ id: "PB_NEWTAB_COOKIE_BANNERS_PROMO",
+ template: "pb_newtab",
+ type: "default",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "COOKIE_BANNERS",
+ promoHeader: "fluent:about-private-browsing-cookie-banners-promo-header",
+ promoImageLarge:
+ "chrome://browser/content/assets/cookie-banners-begone.svg",
+ promoLinkText:
+ "fluent:about-private-browsing-cookie-banners-promo-button",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle: "fluent:about-private-browsing-cookie-banners-promo-message",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.mode",
+ value: Ci.nsICookieBannerService.MODE_REJECT,
+ },
+ },
+ },
+ {
+ // This pref may be removed (with the normal pref controlling
+ // both modes), at which time we should remove this action.
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.mode.privateBrowsing",
+ value: Ci.nsICookieBannerService.MODE_REJECT,
+ },
+ },
+ },
+ {
+ // Reset this pref to default
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.detectOnly",
+ },
+ },
+ },
+ {
+ type: "BLOCK_MESSAGE",
+ data: {
+ id: "PB_NEWTAB_COOKIE_BANNERS_PROMO",
+ },
+ },
+ {
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "privatebrowsing", where: "current" },
+ },
+ ],
+ },
+ },
+ },
+ },
+ priority: 4,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ targeting: `!'cookiebanners.service.mode'|preferenceIsUserSet`,
+ },
+ {
+ id: "CFR_COOKIEBANNER",
+ groups: ["cfr"],
+ template: "cfr_doorhanger",
+ content: {
+ bucket_id: "CFR_COOKIEBANNER",
+ anchor_id: "tracking-protection-icon-container",
+ layout: "icon_and_message",
+ icon: "chrome://browser/skin/controlcenter/3rdpartycookies.svg",
+ icon_class: "cfr-doorhanger-small-icon",
+ persistent_doorhanger: true,
+ show_in_private_browsing: true,
+ heading_text: {
+ string_id: "cfr-cbh-header",
+ },
+ text: {
+ string_id: "cfr-cbh-body",
+ },
+ buttons: {
+ primary: {
+ label: {
+ string_id: "cfr-cbh-confirm-button",
+ },
+ action: {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.mode",
+ value: 1,
+ },
+ },
+ },
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.mode.privateBrowsing",
+ value: 1,
+ },
+ },
+ },
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "cookiebanners.service.detectOnly",
+ value: false,
+ },
+ },
+ },
+ {
+ type: "RELOAD_BROWSER",
+ },
+ ],
+ },
+ },
+ },
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-cbh-dismiss-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ ],
+ },
+ skip_address_bar_notifier: true,
+ },
+ frequency: {
+ custom: [{ period: 24 * 60 * 60 * 1000 * 2, cap: 1 }],
+ lifetime: 2,
+ },
+ trigger: {
+ id: "cookieBannerDetected",
+ },
+ targeting: `'cookiebanners.ui.desktop.enabled'|preferenceValue == true && 'cookiebanners.service.detectOnly'|preferenceValue == true`,
+ },
+];
+
+// Eventually, move Feature Callout messages to their own provider
+const ONBOARDING_MESSAGES = () =>
+ BASE_MESSAGES().concat(FeatureCalloutMessages.getMessages());
+
+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;
+ },
+ async _doesAppNeedPin(privateBrowsing = false) {
+ const needPin = await lazy.ShellService.doesAppNeedPin(privateBrowsing);
+ return needPin;
+ },
+ async _doesAppNeedDefault() {
+ let checkDefault = Services.prefs.getBoolPref(
+ "browser.shell.checkDefaultBrowser",
+ false
+ );
+ let isDefault = await lazy.ShellService.isDefaultBrowser();
+ return checkDefault && !isDefault;
+ },
+ _shouldShowPrivacySegmentationScreen() {
+ // Fall back to pref: browser.privacySegmentation.preferences.show
+ return lazy.NimbusFeatures.majorRelease2022.getVariable(
+ "feltPrivacyShowPreferencesSection"
+ );
+ },
+ _doesHomepageNeedReset() {
+ return (
+ Services.prefs.prefHasUserValue(HOMEPAGE_PREF) ||
+ Services.prefs.prefHasUserValue(NEWTAB_PREF)
+ );
+ },
+
+ async getUpgradeMessage() {
+ let message = (await OnboardingMessageProvider.getMessages()).find(
+ ({ id }) => id === "FX_MR_106_UPGRADE"
+ );
+
+ let { content } = message;
+ // Helper to find screens and remove them where applicable.
+ function removeScreens(check) {
+ const { screens } = content;
+ for (let i = 0; i < screens?.length; i++) {
+ if (check(screens[i])) {
+ screens.splice(i--, 1);
+ }
+ }
+ }
+
+ // Helper to prepare mobile download screen content
+ function prepareMobileDownload() {
+ let mobileContent = content.screens.find(
+ screen => screen.id === "UPGRADE_MOBILE_DOWNLOAD"
+ )?.content;
+
+ if (!mobileContent) {
+ return;
+ }
+ if (!lazy.BrowserUtils.sendToDeviceEmailsSupported()) {
+ // If send to device emails are not supported for a user's locale,
+ // remove the send to device link and update the screen text
+ delete mobileContent.cta_paragraph.action;
+ mobileContent.cta_paragraph.text = {
+ string_id: "mr2022-onboarding-no-mobile-download-cta-text",
+ };
+ }
+ // Update CN specific QRCode url
+ if (AppConstants.isChinaRepack()) {
+ mobileContent.hero_image.url = `${mobileContent.hero_image.url.slice(
+ 0,
+ mobileContent.hero_image.url.indexOf(".svg")
+ )}-cn.svg`;
+ }
+ }
+
+ let pinScreen = content.screens?.find(
+ screen => screen.id === "UPGRADE_PIN_FIREFOX"
+ );
+ const needPin = await this._doesAppNeedPin();
+ const needDefault = await this._doesAppNeedDefault();
+ const needPrivatePin =
+ !lazy.hidePrivatePin && (await this._doesAppNeedPin(true));
+ const showSegmentation = this._shouldShowPrivacySegmentationScreen();
+
+ //If a user has Firefox as default remove import screen
+ if (!needDefault) {
+ removeScreens(screen => screen.id?.startsWith("UPGRADE_IMPORT_SETTINGS"));
+ }
+
+ // If already pinned, convert "pin" screen to "welcome" with desired action.
+ let removeDefault = !needDefault;
+ // If user doesn't need pin, update screen to set "default" or "get started" configuration
+ if (!needPin && pinScreen) {
+ // don't need to show the checkbox
+ delete pinScreen.content.checkbox;
+
+ removeDefault = true;
+ let primary = pinScreen.content.primary_button;
+ if (needDefault) {
+ pinScreen.id = "UPGRADE_ONLY_DEFAULT";
+ pinScreen.content.subtitle = {
+ string_id: "mr2022-onboarding-existing-set-default-only-subtitle",
+ };
+ primary.label.string_id =
+ "mr2022-onboarding-set-default-primary-button-label";
+
+ // The "pin" screen will now handle "default" so remove other "default."
+ primary.action.type = "SET_DEFAULT_BROWSER";
+ } else {
+ pinScreen.id = "UPGRADE_GET_STARTED";
+ pinScreen.content.subtitle = {
+ string_id: "mr2022-onboarding-get-started-primary-subtitle",
+ };
+ primary.label = {
+ string_id: "mr2022-onboarding-get-started-primary-button-label",
+ };
+ delete primary.action.type;
+ }
+ }
+
+ // If a user has Firefox private pinned remove pin private window screen
+ // We also remove standalone pin private window screen if a user doesn't have
+ // Firefox pinned in which case the option is shown as checkbox with UPGRADE_PIN_FIREFOX screen
+ if (!needPrivatePin || needPin) {
+ removeScreens(screen =>
+ screen.id?.startsWith("UPGRADE_PIN_PRIVATE_WINDOW")
+ );
+ }
+
+ if (!showSegmentation) {
+ removeScreens(screen =>
+ screen.id?.startsWith("UPGRADE_DATA_RECOMMENDATION")
+ );
+ }
+
+ //If privatePin, remove checkbox from pinscreen
+ if (!needPrivatePin) {
+ delete content.screens?.find(
+ screen => screen.id === "UPGRADE_PIN_FIREFOX"
+ )?.content?.checkbox;
+ }
+
+ if (removeDefault) {
+ removeScreens(screen => screen.id?.startsWith("UPGRADE_SET_DEFAULT"));
+ }
+
+ // Remove mobile download screen if user has sync enabled
+ if (lazy.usesFirefoxSync && lazy.mobileDevices > 0) {
+ removeScreens(screen => screen.id === "UPGRADE_MOBILE_DOWNLOAD");
+ } else {
+ prepareMobileDownload();
+ }
+
+ return message;
+ },
+};
+
+const EXPORTED_SYMBOLS = ["OnboardingMessageProvider"];
diff --git a/browser/components/newtab/lib/PageEventManager.sys.mjs b/browser/components/newtab/lib/PageEventManager.sys.mjs
new file mode 100644
index 0000000000..7b45a5e070
--- /dev/null
+++ b/browser/components/newtab/lib/PageEventManager.sys.mjs
@@ -0,0 +1,94 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Methods for setting up and tearing down page event listeners. These are used
+ * to dismiss Feature Callouts when the callout's anchor element is clicked.
+ */
+export class PageEventManager {
+ /**
+ * A set of parameters defining a page event listener.
+ * @typedef {Object} PageEventListenerParams
+ * @property {String} type Event type string e.g. `click`
+ * @property {String} selectors Target selector, e.g. `tag.class, #id[attr]`
+ * @property {PageEventListenerOptions} [options] addEventListener options
+ *
+ * @typedef {Object} PageEventListenerOptions
+ * @property {Boolean} [capture] Use event capturing phase?
+ * @property {Boolean} [once] Remove listener after first event?
+ * @property {Boolean} [preventDefault] Inverted value for `passive` option
+ */
+
+ /**
+ * Maps event listener params to their abort controllers.
+ * @type {Map<PageEventListenerParams, AbortController>}
+ */
+ _listeners = new Map();
+
+ /**
+ * @param {Document} doc The document to look for event targets in
+ */
+ constructor(doc) {
+ this.doc = doc;
+ }
+
+ /**
+ * Adds a page event listener.
+ * @param {PageEventListenerParams} params
+ * @param {Function} callback Function to call when event is triggered
+ */
+ on(params, callback) {
+ if (this._listeners.has(params)) {
+ return;
+ }
+ const { type, selectors, options = {} } = params;
+ const controller = new AbortController();
+ const opt = {
+ capture: !!options.capture,
+ passive: !options.preventDefault,
+ signal: controller.signal,
+ };
+ const targets = this.doc.querySelectorAll(selectors);
+ for (const target of targets) {
+ target.addEventListener(type, callback, opt);
+ }
+ this._listeners.set(params, controller);
+ }
+
+ /**
+ * Removes a page event listener.
+ * @param {PageEventListenerParams} params
+ */
+ off(params) {
+ const controller = this._listeners.get(params);
+ if (!controller) {
+ return;
+ }
+ controller.abort();
+ this._listeners.delete(params);
+ }
+
+ /**
+ * Adds a page event listener that is removed after the first event.
+ * @param {PageEventListenerParams} params
+ * @param {Function} callback Function to call when event is triggered
+ */
+ once(params, callback) {
+ const wrappedCallback = (...args) => {
+ this.off(params);
+ callback(...args);
+ };
+ this.on(params, wrappedCallback);
+ }
+
+ /**
+ * Removes all page event listeners.
+ */
+ clear() {
+ for (const controller of this._listeners.values()) {
+ controller.abort();
+ }
+ this._listeners.clear();
+ }
+}
diff --git a/browser/components/newtab/lib/PanelTestProvider.sys.mjs b/browser/components/newtab/lib/PanelTestProvider.sys.mjs
new file mode 100644
index 0000000000..b5ff59290a
--- /dev/null
+++ b/browser/components/newtab/lib/PanelTestProvider.sys.mjs
@@ -0,0 +1,626 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 TWO_DAYS = 2 * 24 * 3600 * 1000;
+
+const MESSAGES = () => [
+ {
+ 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_ALT",
+ template: "whatsnew_panel_message",
+ order: 6,
+ content: {
+ bucket_id: "WHATS_NEW_72",
+ published_date: 1574776601000,
+ title: "Title",
+ icon_url:
+ "chrome://activity-stream/content/data/content/assets/protection-report-icon.png",
+ icon_alt: { string_id: "cfr-badge-reader-label-newfeature" },
+ body: "Message body",
+ link_text: "Click here",
+ cta_url: "about:blank",
+ 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: "Title",
+ icon_url: "chrome://global/skin/icons/check.svg",
+ icon_alt: "",
+ body: "Message content",
+ cta_url:
+ "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/search-shortcuts",
+ cta_type: "OPEN_URL",
+ link_text: "Click here",
+ },
+ 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",
+ 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: "about:blank",
+ 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: "Title",
+ body: "Message content",
+ cta_url:
+ "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/media-keyboard-control",
+ cta_type: "OPEN_URL",
+ link_text: "Click here",
+ },
+ 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: "PERSONALIZED_CFR_MESSAGE",
+ template: "cfr_doorhanger",
+ groups: ["cfr"],
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ bucket_id: "PERSONALIZED_CFR_MESSAGE",
+ notification_text: "Personalized CFR Recommendation",
+ heading_text: { string_id: "cfr-doorhanger-bookmark-fxa-header" },
+ info_icon: {
+ label: {
+ attributes: {
+ tooltiptext: { string_id: "cfr-doorhanger-fxa-close-btn-tooltip" },
+ },
+ },
+ sumo_path: "https://example.com",
+ },
+ text: { string_id: "cfr-doorhanger-bookmark-fxa-body" },
+ icon: "chrome://branding/content/icon64.png",
+ icon_class: "cfr-doorhanger-large-icon",
+ persistent_doorhanger: true,
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-milestone-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"],
+ },
+ },
+ {
+ id: "MULTISTAGE_SPOTLIGHT_MESSAGE",
+ groups: ["panel-test-provider"],
+ template: "spotlight",
+ content: {
+ id: "MULTISTAGE_SPOTLIGHT_MESSAGE",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: true,
+ screens: [
+ {
+ id: "AW_PIN_FIREFOX",
+ content: {
+ has_noodles: true,
+ title: {
+ string_id: "mr2022-onboarding-welcome-pin-header",
+ },
+ logo: {
+ imageURL: "chrome://browser/content/callout-tab-pickup.svg",
+ darkModeImageURL:
+ "chrome://browser/content/callout-tab-pickup-dark.svg",
+ reducedMotionImageURL:
+ "chrome://activity-stream/content/data/content/assets/glyph-pin-16.svg",
+ darkModeReducedMotionImageURL:
+ "chrome://activity-stream/content/data/content/assets/firefox.svg",
+ alt: "sample alt text",
+ },
+ hero_text: {
+ string_id: "fx100-thank-you-hero-text",
+ },
+ help_text: {
+ text: "Some sample help text",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-pin-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ dismiss_button: {
+ action: {
+ dismiss: true,
+ },
+ },
+ },
+ },
+ {
+ id: "AW_SET_DEFAULT",
+ content: {
+ has_noodles: true,
+ logo: {
+ imageURL: "chrome://browser/content/logos/vpn-promo-logo.svg",
+ height: "100px",
+ },
+ title: {
+ fontSize: "36px",
+ fontWeight: 276,
+ string_id: "mr2022-onboarding-set-default-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-set-default-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-set-default-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ {
+ id: "BACKGROUND_IMAGE",
+ content: {
+ background: "#000",
+ text_color: "light",
+ progress_bar: true,
+ logo: {
+ imageURL:
+ "https://firefox-settings-attachments.cdn.mozilla.net/main-workspace/ms-images/a3c640c8-7594-4bb2-bc18-8b4744f3aaf2.gif",
+ },
+ title: "A dialog with a background",
+ subtitle:
+ "The text color is configurable and a progress bar style step indicator is used",
+ primary_button: {
+ label: "Continue",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ {
+ id: "BACKGROUND_COLOR",
+ content: {
+ background: "white",
+ progress_bar: true,
+ logo: {
+ height: "200px",
+ imageURL: "",
+ },
+ title: {
+ fontSize: "36px",
+ fontWeight: 276,
+ raw: "Peace of mind.",
+ },
+ title_style: "fancy shine",
+ text_color: "dark",
+ subtitle: "Using progress bar style step indicator",
+ primary_button: {
+ label: "Continue",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ frequency: { lifetime: 3 },
+ trigger: { id: "defaultBrowserCheck" },
+ },
+ {
+ id: "PB_FOCUS_PROMO",
+ groups: ["panel-test-provider"],
+ template: "spotlight",
+ content: {
+ template: "multistage",
+ backdrop: "transparent",
+ screens: [
+ {
+ id: "PBM_FIREFOX_FOCUS",
+ order: 0,
+ content: {
+ logo: {
+ imageURL: "chrome://browser/content/assets/focus-logo.svg",
+ height: "48px",
+ },
+ title: {
+ string_id: "spotlight-focus-promo-title",
+ },
+ subtitle: {
+ string_id: "spotlight-focus-promo-subtitle",
+ },
+ dismiss_button: {
+ action: {
+ dismiss: true,
+ },
+ },
+ ios: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/167k4ih?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fapps.apple.com%2Fus%2Fapp%2Ffirefox-focus-privacy-browser%2Fid1055677337",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ android: {
+ action: {
+ data: {
+ args: "https://app.adjust.com/167k4ih?campaign=firefox-desktop&adgroup=pb&creative=focus-omc172&redirect=https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dorg.mozilla.focus",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ email_link: {
+ action: {
+ data: {
+ args: "https://mozilla.org",
+ where: "tabshifted",
+ },
+ type: "OPEN_URL",
+ navigate: true,
+ },
+ },
+ tiles: {
+ type: "mobile_downloads",
+ data: {
+ QR_code: {
+ image_url:
+ "chrome://browser/content/assets/focus-qr-code.svg",
+ alt_text: {
+ string_id: "spotlight-focus-promo-qr-code",
+ },
+ },
+ email: {
+ link_text: "Email yourself a link",
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ },
+ },
+ },
+ ],
+ },
+ trigger: { id: "defaultBrowserCheck" },
+ },
+ {
+ id: "PB_NEWTAB_VPN_PROMO",
+ template: "pb_newtab",
+ content: {
+ promoEnabled: true,
+ promoType: "VPN",
+ infoEnabled: true,
+ infoBody: "fluent:about-private-browsing-info-description-private-window",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitleEnabled: false,
+ promoLinkType: "button",
+ promoLinkText: "fluent:about-private-browsing-prominent-cta",
+ promoSectionStyle: "below-search",
+ promoHeader: "fluent:about-private-browsing-get-privacy",
+ promoTitle: "fluent:about-private-browsing-hide-activity-1",
+ promoTitleEnabled: true,
+ promoImageLarge: "chrome://browser/content/assets/moz-vpn.svg",
+ promoButton: {
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://vpn.mozilla.org/",
+ },
+ },
+ },
+ },
+ groups: ["panel-test-provider"],
+ targeting: "region != 'CN' && !hasActiveEnterprisePolicies",
+ frequency: { lifetime: 3 },
+ },
+ {
+ id: "PB_PIN_PROMO",
+ template: "pb_newtab",
+ groups: ["pbNewtab"],
+ content: {
+ infoBody: "fluent:about-private-browsing-info-description-simplified",
+ infoEnabled: true,
+ infoIcon: "chrome://global/skin/icons/indicator-private-browsing.svg",
+ infoLinkText: "fluent:about-private-browsing-learn-more-link",
+ infoTitle: "",
+ infoTitleEnabled: false,
+ promoEnabled: true,
+ promoType: "PIN",
+ promoHeader: "Private browsing freedom in one click",
+ promoImageLarge:
+ "chrome://browser/content/assets/private-promo-asset.svg",
+ promoLinkText: "Pin To Taskbar",
+ promoLinkType: "button",
+ promoSectionStyle: "below-search",
+ promoTitle:
+ "No saved cookies or history, right from your desktop. Browse like no one’s watching.",
+ promoTitleEnabled: true,
+ promoButton: {
+ action: {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "browser.privateWindowSeparation.enabled",
+ value: true,
+ },
+ },
+ },
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ {
+ type: "BLOCK_MESSAGE",
+ data: {
+ id: "PB_PIN_PROMO",
+ },
+ },
+ {
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "privatebrowsing", where: "current" },
+ },
+ ],
+ },
+ },
+ },
+ },
+ priority: 3,
+ frequency: {
+ custom: [
+ {
+ cap: 3,
+ period: 604800000, // Max 3 per week
+ },
+ ],
+ lifetime: 12,
+ },
+ targeting:
+ "region != 'CN' && !hasActiveEnterprisePolicies && doesAppNeedPin",
+ },
+ {
+ id: "TEST_TOAST_NOTIFICATION1",
+ weight: 100,
+ template: "toast_notification",
+ content: {
+ title: {
+ string_id: "cfr-doorhanger-bookmark-fxa-header",
+ },
+ body: "Body",
+ image_url:
+ "https://firefox-settings-attachments.cdn.mozilla.net/main-workspace/ms-images/a3c640c8-7594-4bb2-bc18-8b4744f3aaf2.gif",
+ launch_url: "https://mozilla.org",
+ requireInteraction: true,
+ actions: [
+ {
+ action: "dismiss",
+ title: "Dismiss",
+ windowsSystemActivationType: true,
+ },
+ {
+ action: "snooze",
+ title: "Snooze",
+ windowsSystemActivationType: true,
+ },
+ { action: "callback", title: "Callback" },
+ ],
+ tag: "test_toast_notification",
+ },
+ groups: ["panel-test-provider"],
+ targeting: "!hasActiveEnterprisePolicies",
+ trigger: { id: "backgroundTaskMessage" },
+ frequency: { lifetime: 3 },
+ },
+ {
+ id: "MR2022_BACKGROUND_UPDATE_TOAST_NOTIFICATION",
+ weight: 100,
+ template: "toast_notification",
+ content: {
+ title: {
+ string_id: "mr2022-background-update-toast-title",
+ },
+ body: {
+ string_id: "mr2022-background-update-toast-text",
+ },
+ image_url:
+ "https://firefox-settings-attachments.cdn.mozilla.net/main-workspace/ms-images/673d2808-e5d8-41b9-957e-f60d53233b97.png",
+ requireInteraction: true,
+ actions: [
+ {
+ action: "open",
+ title: {
+ string_id: "mr2022-background-update-toast-primary-button-label",
+ },
+ },
+ {
+ action: "snooze",
+ windowsSystemActivationType: true,
+ title: {
+ string_id: "mr2022-background-update-toast-secondary-button-label",
+ },
+ },
+ ],
+ tag: "mr2022_background_update",
+ },
+ groups: ["panel-test-provider"],
+ targeting: "!hasActiveEnterprisePolicies",
+ trigger: { id: "backgroundTaskMessage" },
+ frequency: { lifetime: 3 },
+ },
+];
+
+export const PanelTestProvider = {
+ getMessages() {
+ return Promise.resolve(
+ MESSAGES().map(message => ({
+ ...message,
+ targeting: `providerCohorts.panel_local_testing == "SHOW_TEST"`,
+ }))
+ );
+ },
+};
diff --git a/browser/components/newtab/lib/PersistentCache.sys.mjs b/browser/components/newtab/lib/PersistentCache.sys.mjs
new file mode 100644
index 0000000000..4a27f26a30
--- /dev/null
+++ b/browser/components/newtab/lib/PersistentCache.sys.mjs
@@ -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/. */
+
+/**
+ * A file (disk) based persistent cache of a JSON serializable object.
+ */
+export 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 = PathUtils.join(PathUtils.localProfileDir, this._filename);
+ } catch (error) {
+ reject(error);
+ return;
+ }
+
+ let data = {};
+ try {
+ data = await IOUtils.readJSON(filepath);
+ } catch (error) {
+ if (
+ // isInstance() is not available in node unit test. It should be safe to use instanceof as it's directly from IOUtils.
+ // eslint-disable-next-line mozilla/use-isInstance
+ !(error instanceof DOMException) ||
+ error.name !== "NotFoundError"
+ ) {
+ console.error(
+ `Failed to parse ${this._filename}: ${error.message}`
+ );
+ }
+ }
+
+ resolve(data);
+ }))
+ );
+ }
+
+ /**
+ * Persist the cache to file.
+ */
+ async _persist(data) {
+ const filepath = PathUtils.join(PathUtils.localProfileDir, this._filename);
+ await IOUtils.writeJSON(filepath, data, {
+ tmpPath: `${filepath}.tmp`,
+ });
+ }
+}
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..c1f54408f2
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm
@@ -0,0 +1,282 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
+ Utils: "resource://services-settings/Utils.sys.mjs",
+});
+
+const { BasePromiseWorker } = ChromeUtils.importESModule(
+ "resource://gre/modules/PromiseWorker.sys.mjs"
+);
+
+const RECIPE_NAME = "personality-provider-recipe";
+const MODELS_NAME = "personality-provider-models";
+
+class PersonalityProvider {
+ constructor(modelKeys) {
+ this.modelKeys = modelKeys;
+ this.onSync = this.onSync.bind(this);
+ this.setup();
+ }
+
+ setScores(scores) {
+ 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"
+ );
+
+ 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 = lazy.Utils.SERVER_URL;
+ 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) {
+ lazy.RemoteSettings(collection).on("sync", this.onSync);
+ }
+
+ teardownSyncAttachment(collection) {
+ lazy.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 lazy.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 } = lazy.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 lazy.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 personalization scores of this provider instance.
+ */
+ getScores() {
+ return {
+ // 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..3ed118857e
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.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/. */
+
+/* eslint-env mozilla/chrome-worker */
+
+"use strict";
+
+// Order of these are important.
+/* import-globals-from /toolkit/components/workerloader/require.js */
+/* import-globals-from Tokenize.jsm */
+/* import-globals-from NaiveBayesTextTagger.jsm */
+/* import-globals-from NmfTextTagger.jsm */
+/* import-globals-from RecipeExecutor.jsm */
+/* import-globals-from PersonalityProviderWorkerClass.jsm */
+importScripts(
+ "resource://gre/modules/workers/require.js",
+ "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");
+
+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));
+self.addEventListener("unhandledrejection", function (error) {
+ throw error.reason;
+});
diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm
new file mode 100644
index 0000000000..e761f827d2
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm
@@ -0,0 +1,311 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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";
+
+// PersonalityProviderWorker.js imports the following scripts before this.
+/* import-globals-from Tokenize.jsm */
+/* import-globals-from NaiveBayesTextTagger.jsm */
+/* import-globals-from NmfTextTagger.jsm */
+/* import-globals-from RecipeExecutor.jsm */
+
+// 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"];
+
+// A helper function to create a hash out of a file.
+async function _getFileHash(filepath) {
+ const data = await IOUtils.read(filepath);
+ // File is an instance of Uint8Array
+ const digest = await crypto.subtle.digest("SHA-256", data);
+ const uint8 = new Uint8Array(digest);
+ // return the two-digit hexadecimal code for a byte
+ const toHex = b => b.toString(16).padStart(2, "0");
+ return Array.from(uint8, toHex).join("");
+}
+
+/**
+ * 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 {
+ async getPersonalityProviderDir() {
+ const personalityProviderDir = PathUtils.join(
+ await PathUtils.getLocalProfileDir(),
+ "personality-provider"
+ );
+
+ // Cache this so we don't need to await again.
+ this.getPersonalityProviderDir = () =>
+ Promise.resolve(personalityProviderDir);
+ return personalityProviderDir;
+ }
+
+ 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.forEach(record => this.deleteAttachment(record));
+
+ // Download every new/updated attachment.
+ const toDownload = created.concat(updated.map(u => u.new));
+ // maybeDownloadAttachment is async but we don't care inside onSync.
+ toDownload.forEach(record => this.maybeDownloadAttachment(record));
+ }
+
+ /**
+ * Attempts to download the attachment, but only if it doesn't already exist.
+ */
+ async maybeDownloadAttachment(record, retries = 3) {
+ const {
+ attachment: { filename, hash, size },
+ } = record;
+ await IOUtils.makeDirectory(await this.getPersonalityProviderDir());
+ const localFilePath = PathUtils.join(
+ await this.getPersonalityProviderDir(),
+ filename
+ );
+
+ let retry = 0;
+ while (
+ retry++ < retries &&
+ // exists is an issue for perf because I might not need to call it.
+ (!(await IOUtils.exists(localFilePath)) ||
+ (await IOUtils.stat(localFilePath)).size !== size ||
+ (await _getFileHash(localFilePath)) !== hash)
+ ) {
+ await this._downloadAttachment(record);
+ }
+ }
+
+ /**
+ * Downloads the attachment to disk assuming the dir already exists
+ * and any existing files matching the filename are clobbered.
+ */
+ async _downloadAttachment(record) {
+ const {
+ attachment: { location, filename },
+ } = record;
+ const remoteFilePath = this.baseAttachmentsURL + location;
+ const localFilePath = PathUtils.join(
+ await this.getPersonalityProviderDir(),
+ 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);
+
+ await IOUtils.write(localFilePath, bytes, {
+ tmpPath: `${localFilePath}.tmp`,
+ });
+ }
+
+ async deleteAttachment(record) {
+ const {
+ attachment: { filename },
+ } = record;
+ await IOUtils.makeDirectory(await this.getPersonalityProviderDir());
+ const path = PathUtils.join(
+ await this.getPersonalityProviderDir(),
+ filename
+ );
+
+ await IOUtils.remove(path, { ignoreAbsent: true });
+ // Cleanup the directory if it is empty, do nothing if it is not empty.
+ try {
+ await IOUtils.remove(await this.getPersonalityProviderDir(), {
+ ignoreAbsent: true,
+ });
+ } catch (e) {
+ // This is likely because the directory is not empty, so we don't care.
+ }
+ }
+
+ /**
+ * Gets contents of the attachment if it already exists on file,
+ * and if not attempts to download it.
+ */
+ async getAttachment(record) {
+ const {
+ attachment: { filename },
+ } = record;
+ const filepath = PathUtils.join(
+ await this.getPersonalityProviderDir(),
+ filename
+ );
+
+ try {
+ await this.maybeDownloadAttachment(record);
+ return await IOUtils.readJSON(filepath);
+ } catch (error) {
+ console.error(`Failed to load ${filepath}: ${error.message}`);
+ }
+ return {};
+ }
+
+ async fetchModels(models) {
+ this.models = await Promise.all(
+ models.map(async record => ({
+ ...(await 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") {
+ nbTaggers.push(new NaiveBayesTextTagger(model, toksToTfIdfVector));
+ } else if (model.model_type === "nmf") {
+ nmfTaggers[model.parent_tag] = new NmfTextTagger(
+ model,
+ 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() {
+ const recipeExecutor = new RecipeExecutor(
+ this.taggers.nbTaggers,
+ this.taggers.nmfTaggers,
+ 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..19dcfbdfde
--- /dev/null
+++ b/browser/components/newtab/lib/PlacesFeed.jsm
@@ -0,0 +1,566 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ actionUtils: au,
+} = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { shortURL } = ChromeUtils.import(
+ "resource://activity-stream/lib/ShortURL.jsm"
+);
+const { AboutNewTab } = ChromeUtils.import(
+ "resource:///modules/AboutNewTab.jsm"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PartnerLinkAttribution: "resource:///modules/PartnerLinkAttribution.sys.mjs",
+ pktApi: "chrome://pocket/content/pktApi.sys.mjs",
+ PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+});
+
+const LINK_BLOCKED_EVENT = "newtab-linkBlocked";
+const PLACES_LINKS_CHANGED_DELAY_TIME = 1000; // time in ms to delay timer for places links changed events
+
+// The pref to store the blocked sponsors of the sponsored Top Sites.
+// The value of this pref is an array (JSON serialized) of hostnames of the
+// blocked sponsors.
+const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+
+/**
+ * PlacesObserver - observes events from PlacesUtils.observers
+ */
+class PlacesObserver {
+ constructor(dispatch) {
+ this.dispatch = dispatch;
+ this.QueryInterface = ChromeUtils.generateQI(["nsISupportsWeakReference"]);
+ this.handlePlacesEvent = this.handlePlacesEvent.bind(this);
+ }
+
+ handlePlacesEvent(events) {
+ const removedPages = [];
+ const removedBookmarks = [];
+
+ for (const {
+ itemType,
+ source,
+ dateAdded,
+ guid,
+ title,
+ url,
+ isRemovedFromStore,
+ isTagging,
+ type,
+ } of events) {
+ switch (type) {
+ case "history-cleared":
+ this.dispatch({ type: at.PLACES_HISTORY_CLEARED });
+ break;
+ case "page-removed":
+ if (isRemovedFromStore) {
+ removedPages.push(url);
+ }
+ 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 !== lazy.PlacesUtils.bookmarks.TYPE_BOOKMARK ||
+ source === lazy.PlacesUtils.bookmarks.SOURCES.IMPORT ||
+ source === lazy.PlacesUtils.bookmarks.SOURCES.RESTORE ||
+ source === lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP ||
+ source === lazy.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 === lazy.PlacesUtils.bookmarks.TYPE_BOOKMARK &&
+ source !== lazy.PlacesUtils.bookmarks.SOURCES.IMPORT &&
+ source !== lazy.PlacesUtils.bookmarks.SOURCES.RESTORE &&
+ source !==
+ lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP &&
+ source !== lazy.PlacesUtils.bookmarks.SOURCES.SYNC)
+ ) {
+ removedBookmarks.push(url);
+ }
+ break;
+ }
+ }
+
+ if (removedPages.length || removedBookmarks.length) {
+ this.dispatch({ type: at.PLACES_LINKS_CHANGED });
+ }
+
+ if (removedPages.length) {
+ this.dispatch({
+ type: at.PLACES_LINKS_DELETED,
+ data: { urls: removedPages },
+ });
+ }
+
+ if (removedBookmarks.length) {
+ this.dispatch({
+ type: at.PLACES_BOOKMARKS_REMOVED,
+ data: { urls: removedBookmarks },
+ });
+ }
+ }
+}
+
+class PlacesFeed {
+ constructor() {
+ this.placesChangedTimer = null;
+ this.customDispatch = this.customDispatch.bind(this);
+ this.placesObserver = new PlacesObserver(this.customDispatch);
+ }
+
+ addObservers() {
+ lazy.PlacesUtils.observers.addListener(
+ ["bookmark-added", "bookmark-removed", "history-cleared", "page-removed"],
+ 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;
+ }
+ lazy.PlacesUtils.observers.removeListener(
+ ["bookmark-added", "bookmark-removed", "history-cleared", "page-removed"],
+ 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,
+ forceForeground: false, // This ensure we maintain user preference for how to open new tabs.
+ globalHistoryOptions: {
+ triggeringSponsoredURL: action.data.sponsored_tile_id
+ ? action.data.url
+ : undefined,
+ },
+ };
+
+ // 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) {
+ console.error(e);
+ return;
+ }
+
+ // Mark the page as typed for frecency bonus before opening the link
+ if (typedBonus) {
+ lazy.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) {
+ lazy.PlacesUtils.history.insert({
+ url: action.data.original_url,
+ visits: [{ transition: lazy.PlacesUtils.history.TRANSITION_TYPED }],
+ });
+ }
+ }
+
+ async saveToPocket(site, browser) {
+ const sendToPocket =
+ lazy.NimbusFeatures.pocketNewtab.getVariable("sendToPocket");
+ // An experiment to send the user directly to Pocket's signup page.
+ if (sendToPocket && !lazy.pktApi.isUserLoggedIn()) {
+ const pocketNewtabExperiment = lazy.ExperimentAPI.getExperiment({
+ featureId: "pocketNewtab",
+ });
+ const pocketSiteHost = Services.prefs.getStringPref(
+ "extensions.pocket.site"
+ ); // getpocket.com
+ let utmSource = "firefox_newtab_save_button";
+ // We want to know if the user is in a Pocket newtab related experiment.
+ let utmCampaign = pocketNewtabExperiment?.slug;
+ let utmContent = pocketNewtabExperiment?.branch?.slug;
+
+ const url = new URL(`https://${pocketSiteHost}/signup`);
+ url.searchParams.append("utm_source", utmSource);
+ if (utmCampaign && utmContent) {
+ url.searchParams.append("utm_campaign", utmCampaign);
+ url.searchParams.append("utm_content", utmContent);
+ }
+
+ const win = browser.ownerGlobal;
+ win.openTrustedLinkIn(url.href, "tab");
+ return;
+ }
+
+ const { url, title } = site;
+ try {
+ let data = await lazy.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) {
+ console.error(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 lazy.NewTabUtils.activityStreamLinks.deletePocketEntry(itemID);
+ this.store.dispatch({ type: at.POCKET_LINK_DELETED_OR_ARCHIVED });
+ } catch (err) {
+ console.error(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 lazy.NewTabUtils.activityStreamLinks.archivePocketEntry(itemID);
+ this.store.dispatch({ type: at.POCKET_LINK_DELETED_OR_ARCHIVED });
+ } catch (err) {
+ console.error(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
+ );
+ lazy.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"
+ ];
+ }
+
+ handoffSearchToAwesomebar(action) {
+ const { _target, data, meta } = action;
+ const searchEngine = this._getDefaultSearchEngine(
+ lazy.PrivateBrowsingUtils.isBrowserPrivate(_target.browser)
+ );
+ const urlBar = _target.browser.ownerGlobal.gURLBar;
+ let isFirstChange = true;
+
+ const newtabSession = AboutNewTab.activityStream.store.feeds
+ .get("feeds.telemetry")
+ ?.sessions.get(au.getPortIdOfSender(action));
+ if (!data || !data.text) {
+ urlBar.setHiddenFocus();
+ } else {
+ urlBar.handoff(data.text, searchEngine, newtabSession?.session_id);
+ 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(true);
+ urlBar.handoff("", searchEngine, newtabSession?.session_id);
+ this.store.dispatch(
+ ac.OnlyToOneContent({ type: at.DISABLE_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 = ev => {
+ // We are done. Show in-content search again and cleanup.
+ this.store.dispatch(
+ ac.OnlyToOneContent({ type: at.SHOW_SEARCH }, meta.fromTarget)
+ );
+
+ const forceSuppressFocusBorder = ev?.type === "mousedown";
+ urlBar.removeHiddenFocus(forceSuppressFocusBorder);
+
+ 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);
+ }
+
+ /**
+ * Add the hostnames of the given urls to the Top Sites sponsor blocklist.
+ *
+ * @param {array} urls
+ * An array of the objects structured as `{ url }`
+ */
+ addToBlockedTopSitesSponsors(urls) {
+ const blockedPref = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF, "[]")
+ );
+ const merged = new Set([...blockedPref, ...urls.map(url => shortURL(url))]);
+
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ JSON.stringify([...merged])
+ );
+ }
+
+ 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) {
+ let sponsoredTopSites = [];
+ action.data.forEach(site => {
+ const { url, pocket_id, isSponsoredTopSite } = site;
+ lazy.NewTabUtils.activityStreamLinks.blockURL({ url, pocket_id });
+ if (isSponsoredTopSite) {
+ sponsoredTopSites.push({ url });
+ }
+ });
+ if (sponsoredTopSites.length) {
+ this.addToBlockedTopSitesSponsors(sponsoredTopSites);
+ }
+ }
+ break;
+ }
+ case at.BOOKMARK_URL:
+ lazy.NewTabUtils.activityStreamLinks.addBookmark(
+ action.data,
+ action._target.browser.ownerGlobal
+ );
+ break;
+ case at.DELETE_BOOKMARK_BY_ID:
+ lazy.NewTabUtils.activityStreamLinks.deleteBookmark(action.data);
+ break;
+ case at.DELETE_HISTORY_URL: {
+ const { url, forceBlock, pocket_id } = action.data;
+ lazy.NewTabUtils.activityStreamLinks.deleteHistoryEntry(url);
+ if (forceBlock) {
+ lazy.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;
+ }
+ }
+}
+
+// Exported for testing only
+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..f6f46b069d
--- /dev/null
+++ b/browser/components/newtab/lib/PrefsFeed.jsm
@@ -0,0 +1,280 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+});
+
+class PrefsFeed {
+ constructor(prefMap) {
+ this._prefMap = prefMap;
+ this._prefs = new Prefs();
+ this.onExperimentUpdated = this.onExperimentUpdated.bind(this);
+ this.onPocketExperimentUpdated = this.onPocketExperimentUpdated.bind(this);
+ }
+
+ onPrefChanged(name, value) {
+ const prefItem = this._prefMap.get(name);
+ if (prefItem) {
+ let action = "BroadcastToContent";
+ if (prefItem.skipBroadcast) {
+ action = "OnlyToMain";
+ if (prefItem.alsoToPreloaded) {
+ action = "AlsoToPreloaded";
+ }
+ }
+
+ this.store.dispatch(
+ ac[action]({
+ 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 });
+ }
+
+ /**
+ * Handler for when experiment data updates.
+ */
+ onExperimentUpdated(event, reason) {
+ const value = lazy.NimbusFeatures.newtab.getAllVariables() || {};
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "featureConfig",
+ value,
+ },
+ })
+ );
+ }
+
+ /**
+ * Handler for Pocket specific experiment data updates.
+ */
+ onPocketExperimentUpdated(event, reason) {
+ const value = lazy.NimbusFeatures.pocketNewtab.getAllVariables() || {};
+ // Loaded experiments are set up inside init()
+ if (
+ reason !== "feature-experiment-loaded" &&
+ reason !== "feature-rollout-loaded"
+ ) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "pocketConfig",
+ value,
+ },
+ })
+ );
+ }
+ }
+
+ init() {
+ this._prefs.observeBranch(this);
+ lazy.NimbusFeatures.newtab.onUpdate(this.onExperimentUpdated);
+ lazy.NimbusFeatures.pocketNewtab.onUpdate(this.onPocketExperimentUpdated);
+
+ 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 = lazy.PrivateBrowsingUtils.enabled;
+ values.platform = AppConstants.platform;
+
+ // Save the geo pref if we have it
+ if (lazy.Region.home) {
+ values.region = lazy.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, lazy.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 internal 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 internal 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,
+ });
+
+ // Read the pref for the cached default engine name from firefox.js and
+ // store it in our internal list of prefs to watch
+ let placeholderPrefValue = Services.prefs.getStringPref(
+ "browser.urlbar.placeholderName",
+ ""
+ );
+ values["urlbar.placeholderName"] = placeholderPrefValue;
+ this._prefMap.set("urlbar.placeholderName", {
+ value: placeholderPrefValue,
+ });
+
+ // Add experiment values and default values
+ values.featureConfig = lazy.NimbusFeatures.newtab.getAllVariables() || {};
+ values.pocketConfig =
+ lazy.NimbusFeatures.pocketNewtab.getAllVariables() || {};
+ this._setBoolPref(values, "logowordmark.alwaysVisible", false);
+ this._setBoolPref(values, "feeds.section.topstories", false);
+ this._setBoolPref(values, "discoverystream.enabled", false);
+ this._setBoolPref(
+ values,
+ "discoverystream.sponsored-collections.enabled",
+ false
+ );
+ this._setBoolPref(values, "discoverystream.isCollectionDismissible", false);
+ this._setBoolPref(values, "discoverystream.hardcoded-basic-layout", false);
+ this._setBoolPref(values, "discoverystream.personalization.enabled", false);
+ this._setBoolPref(values, "discoverystream.personalization.override");
+ this._setStringPref(
+ values,
+ "discoverystream.personalization.modelKeys",
+ ""
+ );
+ 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);
+ lazy.NimbusFeatures.newtab.offUpdate(this.onExperimentUpdated);
+ lazy.NimbusFeatures.pocketNewtab.offUpdate(this.onPocketExperimentUpdated);
+ if (this.geo === "") {
+ Services.obs.removeObserver(this, lazy.Region.REGION_TOPIC);
+ }
+ }
+
+ async _setIndexedDBPref(id, value) {
+ const name = id === "topsites" ? id : `feeds.section.${id}`;
+ try {
+ await this._storage.set(name, value);
+ } catch (e) {
+ console.error("Could not set section preferences.");
+ }
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case lazy.Region.REGION_TOPIC:
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "region", value: lazy.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/RecommendationProvider.jsm b/browser/components/newtab/lib/RecommendationProvider.jsm
new file mode 100644
index 0000000000..2438dfe542
--- /dev/null
+++ b/browser/components/newtab/lib/RecommendationProvider.jsm
@@ -0,0 +1,132 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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";
+
+// Use XPCOMUtils.defineLazyModuleGetters to make the test harness keeps working
+// after bug 1608279.
+//
+// The test harness's workaround for "lazy getter on a plain object" is to
+// set the `lazy` object's prototype to the global object, inside the lazy
+// getter API.
+//
+// ChromeUtils.defineModuleGetter is converted into a static import declaration
+// by babel-plugin-jsm-to-esmodules, and it doesn't work for the following
+// 2 reasons:
+//
+// * There's no other lazy getter API call in this file, and the workaround
+// above stops working
+// * babel-plugin-jsm-to-esmodules ignores the first parameter of the lazy
+// getter API, and the result is wrong
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const lazy = {};
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ PersonalityProvider:
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.jsm",
+});
+
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+const PREF_PERSONALIZATION = "discoverystream.personalization.enabled";
+
+// The main purpose of this class is to handle interactions with the recommendation provider.
+// A recommendation provider scores a list of stories, currently this is a personality provider.
+// So all calls to the provider, anything involved with the setup of the provider,
+// accessing prefs for the provider, or updaing devtools with provider state, is contained in here.
+class RecommendationProvider {
+ setProvider(scores) {
+ // A 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.provider) {
+ return;
+ }
+ // At this point we've determined we can successfully create a v2 personalization provider.
+ this.provider = new lazy.PersonalityProvider(this.modelKeys);
+ this.provider.setScores(scores);
+ }
+
+ /*
+ * This calls any async initialization that's required,
+ * and then signals to devtools when that's done.
+ */
+ async init() {
+ if (this.provider && this.provider.init) {
+ await this.provider.init();
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_INIT,
+ })
+ );
+ }
+ }
+
+ get modelKeys() {
+ if (!this._modelKeys) {
+ this._modelKeys =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION_MODEL_KEYS];
+ }
+
+ return this._modelKeys;
+ }
+
+ getScores() {
+ return this.provider.getScores();
+ }
+
+ async calculateItemRelevanceScore(item) {
+ if (this.provider) {
+ const scoreResult = await this.provider.calculateItemRelevanceScore(item);
+ if (scoreResult === 0 || scoreResult) {
+ item.score = scoreResult;
+ }
+ }
+ }
+
+ teardown() {
+ if (this.provider && this.provider.teardown) {
+ // This removes any in memory listeners if available.
+ this.provider.teardown();
+ }
+ }
+
+ resetState() {
+ this._modelKeys = null;
+ this.provider = null;
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.DISCOVERY_STREAM_CONFIG_CHANGE:
+ this.teardown();
+ this.resetState();
+ break;
+ case at.PREF_CHANGED:
+ switch (action.data.name) {
+ case PREF_PERSONALIZATION_MODEL_KEYS:
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET,
+ })
+ );
+ break;
+ }
+ break;
+ case at.DISCOVERY_STREAM_PERSONALIZATION_TOGGLE:
+ let enabled = this.store.getState().Prefs.values[PREF_PERSONALIZATION];
+
+ this.store.dispatch(ac.SetPref(PREF_PERSONALIZATION, !enabled));
+ break;
+ }
+ }
+}
+
+const EXPORTED_SYMBOLS = ["RecommendationProvider"];
diff --git a/browser/components/newtab/lib/RemoteL10n.sys.mjs b/browser/components/newtab/lib/RemoteL10n.sys.mjs
new file mode 100644
index 0000000000..fe25c56a79
--- /dev/null
+++ b/browser/components/newtab/lib/RemoteL10n.sys.mjs
@@ -0,0 +1,249 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * The downloaded Fluent file is located in this sub-directory of the local
+ * profile directory.
+ */
+const USE_REMOTE_L10N_PREF =
+ "browser.newtabpage.activity-stream.asrouter.useRemoteL10n";
+
+/**
+ * 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",
+]);
+
+export 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 */
+ let useRemoteL10n = Services.prefs.getBoolPref(USE_REMOTE_L10N_PREF, true);
+ if (useRemoteL10n && !L10nRegistry.getInstance().hasSource("cfr")) {
+ const appLocale = Services.locale.appLocaleAsBCP47;
+ const l10nFluentDir = PathUtils.join(
+ Services.dirsvc.get("ProfLD", Ci.nsIFile).path,
+ "settings",
+ "main",
+ "ms-language-packs"
+ );
+ let cfrIndexedFileSource = new L10nFileSource(
+ "cfr",
+ "app",
+ [appLocale],
+ `file://${l10nFluentDir}/`,
+ {
+ addResourceOptions: {
+ allowOverrides: true,
+ },
+ },
+ [`file://${l10nFluentDir}/browser/newtab/asrouter.ftl`]
+ );
+ L10nRegistry.getInstance().registerSources([cfrIndexedFileSource]);
+ } else if (!useRemoteL10n && L10nRegistry.getInstance().hasSource("cfr")) {
+ L10nRegistry.getInstance().removeSources(["cfr"]);
+ }
+
+ return new DOMLocalization(
+ [
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ "browser/newtab/asrouter.ftl",
+ "toolkit/branding/accounts.ftl",
+ "toolkit/branding/brandings.ftl",
+ ],
+ false
+ );
+ }
+
+ 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);
+ }
+
+ /**
+ * Format given `localizableText`.
+ *
+ * Format `localizableText` if it is an object using any `string_id` field,
+ * otherwise return `localizableText` unmodified.
+ *
+ * @param {object|string} `localizableText` to format.
+ * @return {string} formatted text.
+ */
+ async formatLocalizableText(localizableText) {
+ if (typeof localizableText !== "string") {
+ // It's more useful to get an error than passing through an object without
+ // a `string_id` field.
+ let value = await this.l10n.formatValue(localizableText.string_id);
+ return value;
+ }
+ return localizableText;
+ }
+}
+
+export const RemoteL10n = new _RemoteL10n();
diff --git a/browser/components/newtab/lib/Screenshots.jsm b/browser/components/newtab/lib/Screenshots.jsm
new file mode 100644
index 0000000000..b454702265
--- /dev/null
+++ b/browser/components/newtab/lib/Screenshots.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 = ["Screenshots"];
+
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ BackgroundPageThumbs: "resource://gre/modules/BackgroundPageThumbs.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+});
+
+const GREY_10 = "#F9F9FA";
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "gPrivilegedAboutProcessEnabled",
+ "browser.tabs.remote.separatePrivilegedContentProcess",
+ false
+);
+
+const 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 lazy.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 (lazy.gPrivilegedAboutProcessEnabled) {
+ return lazy.PageThumbs.getThumbnailURL(url);
+ }
+
+ // Otherwise, for normal content processes, we fallback to using
+ // Blob URIs for the screenshots.
+ const imgPath = lazy.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) {
+ console.error(`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 lazy.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 (!lazy.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.sys.mjs b/browser/components/newtab/lib/SearchShortcuts.sys.mjs
new file mode 100644
index 0000000000..8b8edc18c2
--- /dev/null
+++ b/browser/components/newtab/lib/SearchShortcuts.sys.mjs
@@ -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/. */
+
+// List of sites we match against Topsites in order to identify sites
+// that should be converted to search Topsites
+export 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",
+ },
+];
+
+// These can be added via the editor but will not be added organically
+export const 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
+export const SEARCH_SHORTCUTS_EXPERIMENT =
+ "improvesearch.topSiteSearchShortcuts";
+
+export const SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF =
+ "improvesearch.topSiteSearchShortcuts.searchEngines";
+
+export const SEARCH_SHORTCUTS_HAVE_PINNED_PREF =
+ "improvesearch.topSiteSearchShortcuts.havePinned";
+
+export function getSearchProvider(candidateShortURL) {
+ return (
+ SEARCH_SHORTCUTS.filter(match => candidateShortURL === match.shortURL)[0] ||
+ null
+ );
+}
+
+// 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.
+export async function getSearchFormURL(keyword) {
+ const engine = await Services.search.getEngineByAlias(keyword);
+ return engine?.wrappedJSObject._searchForm;
+}
+
+// Check topsite against predefined list of valid search engines
+// https://searchfox.org/mozilla-central/rev/ca869724246f4230b272ed1c8b9944596e80d920/toolkit/components/search/nsSearchService.js#939
+export async function checkHasSearchEngine(keyword) {
+ return (await Services.search.getAppProvidedEngines()).find(
+ e => e.aliases.includes(keyword) && !e.hidden
+ );
+}
diff --git a/browser/components/newtab/lib/SectionsManager.jsm b/browser/components/newtab/lib/SectionsManager.jsm
new file mode 100644
index 0000000000..a9b2c4eeae
--- /dev/null
+++ b/browser/components/newtab/lib/SectionsManager.jsm
@@ -0,0 +1,712 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/EventEmitter.sys.mjs"
+);
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { getDefaultOptions } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamStorage.jsm"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
+});
+
+/*
+ * 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 = ({ newtab, pocketNewtab }) => ({
+ "feeds.section.topstories": options => ({
+ id: "topstories",
+ pref: {
+ titleString: {
+ id: "home-prefs-recommended-by-header",
+ values: { provider: options.provider_name },
+ },
+ descString: {
+ id: "home-prefs-recommended-by-description-new",
+ 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",
+ },
+ ]
+ : []),
+ ...(pocketNewtab.recentSavesEnabled
+ ? [
+ {
+ name: "showRecentSaves",
+ titleString: "home-prefs-recommended-by-option-recent-saves",
+ icon: "icon-info",
+ eventSource: "POCKET_RECENT_SAVES",
+ },
+ ]
+ : []),
+ ],
+ 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" },
+ },
+ },
+ 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: "home-prefs-recent-activity-header",
+ },
+ descString: {
+ id: "home-prefs-recent-activity-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: "chrome://global/skin/icons/highlights.svg",
+ title: {
+ id: "newtab-section-header-recent-activity",
+ },
+ compactCards: true,
+ rowsPref: "section.highlights.rows",
+ maxRows: 4,
+ emptyState: {
+ message: { id: "newtab-empty-section-highlights" },
+ icon: "chrome://global/skin/icons/highlights.svg",
+ },
+ 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;
+ const featureConfig = {
+ newtab: lazy.NimbusFeatures.newtab.getAllVariables() || {},
+ pocketNewtab: lazy.NimbusFeatures.pocketNewtab.getAllVariables() || {},
+ };
+
+ for (const feedPrefName of Object.keys(BUILT_IN_SECTIONS(featureConfig))) {
+ 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;
+ const featureConfig = {
+ newtab: lazy.NimbusFeatures.newtab.getAllVariables() || {},
+ pocketNewtab: lazy.NimbusFeatures.pocketNewtab.getAllVariables() || {},
+ };
+ try {
+ options = JSON.parse(optionsPrefValue);
+ } catch (e) {
+ options = {};
+ console.error(`Problem parsing options pref for ${feedPrefName}`);
+ }
+ try {
+ storedPrefs = (await this._storage.get(feedPrefName)) || {};
+ } catch (e) {
+ storedPrefs = {};
+ console.error(`Problem getting stored prefs for ${feedPrefName}`);
+ }
+ const defaultSection =
+ BUILT_IN_SECTIONS(featureConfig)[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
+ ) {
+ lazy.PlacesUtils.history.update({
+ url: card.url,
+ title: card.title,
+ description: card.description,
+ previewImageURL: card.image,
+ });
+ // Highlights query skips bookmarks with no visits.
+ lazy.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]) {
+ console.error(
+ `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
+ );
+ }
+ }
+}
+
+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..19416904f0
--- /dev/null
+++ b/browser/components/newtab/lib/ShortURL.jsm
@@ -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/. */
+
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+XPCOMUtils.defineLazyServiceGetter(
+ lazy,
+ "IDNService",
+ "@mozilla.org/network/idn-service;1",
+ "nsIIDNService"
+);
+
+/**
+ * Properly convert internationalized domain names.
+ * @param {string} host Domain hostname.
+ * @returns {string} Hostname suitable to be displayed.
+ */
+function handleIDNHost(hostname) {
+ try {
+ return lazy.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..0b174676b9
--- /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.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+
+// 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.sys.mjs b/browser/components/newtab/lib/SnippetsTestMessageProvider.sys.mjs
new file mode 100644
index 0000000000..7f28572f32
--- /dev/null
+++ b/browser/components/newtab/lib/SnippetsTestMessageProvider.sys.mjs
@@ -0,0 +1,688 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 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://global/skin/icons/pocket.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://global/skin/icons/pocket.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://global/skin/icons/pocket.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://global/skin/icons/pocket.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://global/skin/icons/pocket.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",
+ },
+ },
+];
+
+export 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"`,
+ }))
+ );
+ },
+};
diff --git a/browser/components/newtab/lib/Spotlight.jsm b/browser/components/newtab/lib/Spotlight.jsm
new file mode 100644
index 0000000000..a40af7f97a
--- /dev/null
+++ b/browser/components/newtab/lib/Spotlight.jsm
@@ -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/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ AboutWelcomeTelemetry:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(
+ lazy,
+ "AWTelemetry",
+ () => new lazy.AboutWelcomeTelemetry()
+);
+
+const Spotlight = {
+ sendUserEventTelemetry(event, message, dispatch) {
+ const ping = {
+ message_id: message.content.id,
+ event,
+ };
+ dispatch({
+ type: "SPOTLIGHT_TELEMETRY",
+ data: { action: "spotlight_user_event", ...ping },
+ });
+ },
+
+ defaultDispatch(message) {
+ if (message.type === "SPOTLIGHT_TELEMETRY") {
+ const { message_id, event } = message.data;
+ lazy.AWTelemetry.sendTelemetry({ message_id, event });
+ }
+ },
+
+ /**
+ * Shows spotlight tab or window modal specific to the given browser
+ * @param browser The browser for spotlight display
+ * @param message Message containing content to show
+ * @param dispatchCFRAction A function to dispatch resulting actions
+ * @return boolean value capturing if spotlight was displayed
+ */
+ async showSpotlightDialog(browser, message, dispatch = this.defaultDispatch) {
+ const win = browser?.ownerGlobal;
+ if (!win || win.gDialogBox.isOpen) {
+ return false;
+ }
+ const spotlight_url = "chrome://browser/content/spotlight.html";
+
+ const dispatchCFRAction =
+ // This also blocks CFR impressions, which is fine for current use cases.
+ message.content?.metrics === "block" ? () => {} : dispatch;
+
+ // This handles `IMPRESSION` events used by ASRouter for frequency caps.
+ // AboutWelcome handles `IMPRESSION` events for telemetry.
+ this.sendUserEventTelemetry("IMPRESSION", message, dispatchCFRAction);
+ dispatchCFRAction({ type: "IMPRESSION", data: message });
+
+ if (message.content?.modal === "tab") {
+ let { closedPromise } = win.gBrowser.getTabDialogBox(browser).open(
+ spotlight_url,
+ {
+ features: "resizable=no",
+ allowDuplicateDialogs: false,
+ },
+ message.content
+ );
+ await closedPromise;
+ } else {
+ await win.gDialogBox.open(spotlight_url, message.content);
+ }
+
+ // If dismissed report telemetry and exit
+ this.sendUserEventTelemetry("DISMISS", message, dispatchCFRAction);
+ return true;
+ },
+};
+
+const EXPORTED_SYMBOLS = ["Spotlight"];
diff --git a/browser/components/newtab/lib/Store.jsm b/browser/components/newtab/lib/Store.jsm
new file mode 100644
index 0000000000..36c2e03498
--- /dev/null
+++ b/browser/components/newtab/lib/Store.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";
+
+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.importESModule(
+ "resource://activity-stream/common/Reducers.sys.mjs"
+);
+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.
+ */
+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);
+
+ // 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;
+ }
+
+ /**
+ * getMessageChannel - Used by the AboutNewTabParent actor to get the message channel.
+ */
+ getMessageChannel() {
+ return this._messageChannel;
+ }
+}
+
+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..d55cedc45d
--- /dev/null
+++ b/browser/components/newtab/lib/SystemTickFeed.jsm
@@ -0,0 +1,75 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ clearInterval: "resource://gre/modules/Timer.sys.mjs",
+ setInterval: "resource://gre/modules/Timer.sys.mjs",
+});
+
+// Frequency at which SYSTEM_TICK events are fired
+const SYSTEM_TICK_INTERVAL = 5 * 60 * 1000;
+
+class SystemTickFeed {
+ init() {
+ this._idleService = Cc["@mozilla.org/widget/useridleservice;1"].getService(
+ Ci.nsIUserIdleService
+ );
+ this._hasObserver = false;
+ this.setTimer();
+ }
+
+ setTimer() {
+ this.intervalId = lazy.setInterval(() => {
+ if (this._idleService.idleTime > SYSTEM_TICK_INTERVAL) {
+ this.cancelTimer();
+ Services.obs.addObserver(this, "user-interaction-active");
+ this._hasObserver = true;
+ return;
+ }
+ this.dispatchTick();
+ }, SYSTEM_TICK_INTERVAL);
+ }
+
+ cancelTimer() {
+ lazy.clearInterval(this.intervalId);
+ this.intervalId = null;
+ }
+
+ observe() {
+ this.dispatchTick();
+ Services.obs.removeObserver(this, "user-interaction-active");
+ this._hasObserver = false;
+ this.setTimer();
+ }
+
+ dispatchTick() {
+ ChromeUtils.idleDispatch(() =>
+ this.store.dispatch({ type: at.SYSTEM_TICK })
+ );
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ break;
+ case at.UNINIT:
+ this.cancelTimer();
+ if (this._hasObserver) {
+ Services.obs.removeObserver(this, "user-interaction-active");
+ this._hasObserver = false;
+ }
+ break;
+ }
+ }
+}
+
+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..653603d809
--- /dev/null
+++ b/browser/components/newtab/lib/TelemetryFeed.jsm
@@ -0,0 +1,1403 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/ActorConstants.sys.mjs"
+);
+
+const { actionTypes: at, actionUtils: au } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { classifySite } = ChromeUtils.import(
+ "resource://activity-stream/lib/SiteClassifier.jsm"
+);
+
+const lazy = {};
+
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "AboutNewTab",
+ "resource:///modules/AboutNewTab.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "PingCentre",
+ "resource:///modules/PingCentre.jsm"
+);
+ChromeUtils.defineESModuleGetters(lazy, {
+ ClientID: "resource://gre/modules/ClientID.sys.mjs",
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ExtensionSettingsStore:
+ "resource://gre/modules/ExtensionSettingsStore.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.sys.mjs",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
+ UTEventReporting: "resource://activity-stream/lib/UTEventReporting.sys.mjs",
+ UpdateUtils: "resource://gre/modules/UpdateUtils.sys.mjs",
+ pktApi: "chrome://pocket/content/pktApi.sys.mjs",
+});
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "HomePage",
+ "resource:///modules/HomePage.jsm"
+);
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ AboutWelcomeTelemetry:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm",
+});
+XPCOMUtils.defineLazyGetter(
+ lazy,
+ "Telemetry",
+ () => new lazy.AboutWelcomeTelemetry()
+);
+
+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,
+ showSponsoredTopSites: 1 << 8,
+};
+
+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";
+const STRUCTURED_INGESTION_NAMESPACE_CS = "contextual-services";
+
+// 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(
+ lazy,
+ "browserSessionId",
+ () => lazy.TelemetrySession.getMetadata("").sessionId
+);
+
+// The scalar category for TopSites of Contextual Services
+const SCALAR_CATEGORY_TOPSITES = "contextual.services.topsites";
+// `contextId` is a unique identifier used by Contextual Services
+const CONTEXT_ID_PREF = "browser.contextual-services.contextId";
+XPCOMUtils.defineLazyGetter(lazy, "contextId", () => {
+ let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null);
+ if (!_contextId) {
+ _contextId = String(Services.uuid.generateUUID());
+ Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId);
+ }
+ return _contextId;
+});
+
+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: lazy.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() {
+ this._beginObservingNewtabPingPrefs();
+ 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 two scalars for the "deletion-request" ping (See bug 1602064 and 1729474)
+ Services.telemetry.scalarSet(
+ "deletion.request.impression_id",
+ this._impressionId
+ );
+ Services.telemetry.scalarSet("deletion.request.context_id", lazy.contextId);
+ Glean.newtab.locale.set(Services.locale.appLocaleAsBCP47);
+ }
+
+ 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 (lazy.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 || lazy.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(Services.uuid.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 lazy.PingCentre({ topic: ACTIVITY_STREAM_ID }),
+ });
+ return this.pingCentre;
+ }
+
+ /**
+ * Lazily initialize UTEventReporting to send pings
+ */
+ get utEvents() {
+ Object.defineProperty(this, "utEvents", {
+ value: new lazy.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() {
+ const experimentData = lazy.ExperimentAPI.getExperimentMetaData({
+ featureId: "cfr",
+ });
+ if (experimentData && experimentData.slug) {
+ return true;
+ }
+
+ 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(Services.uuid.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);
+
+ Glean.newtab.closed.record({ newtab_visit_id: session.session_id });
+ if (
+ this.telemetryEnabled &&
+ (lazy.NimbusFeatures.glean.getVariable("newtabPingEnabled") ?? true)
+ ) {
+ GleanPings.newtab.submit("newtab_session_end");
+ }
+
+ 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 { tiles, window_inner_width, window_inner_height } =
+ impressionSets[source];
+ const payload = this.createImpressionStats(port, {
+ source,
+ tiles,
+ window_inner_width,
+ window_inner_height,
+ });
+ 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:
+ lazy.TelemetryEnvironment.currentEnvironment.profile.resetDate ||
+ lazy.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 "spotlight_user_event":
+ event = await this.applySpotlightPolicy(event);
+ break;
+ case "toast_notification_user_event":
+ event = await this.applyToastNotificationPolicy(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 bucket_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
+ * 4). In Private Browsing windows, unless in experiment, collects impression_id and bucket_id
+ */
+ async applyCFRPolicy(ping) {
+ if (
+ (lazy.UpdateUtils.getUpdateChannel(true) === "release" ||
+ ping.is_private) &&
+ !this.isInCFRCohort
+ ) {
+ ping.message_id = "n/a";
+ ping.impression_id = this._impressionId;
+ } else {
+ ping.client_id = await this.telemetryClientId;
+ }
+ delete ping.action;
+ delete ping.is_private;
+ 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 = lazy.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 = lazy.browserSessionId;
+ delete ping.action;
+ return { ping, pingType: "infobar" };
+ }
+
+ async applySpotlightPolicy(ping) {
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = lazy.browserSessionId;
+ delete ping.action;
+ return { ping, pingType: "spotlight" };
+ }
+
+ async applyToastNotificationPolicy(ping) {
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = lazy.browserSessionId;
+ delete ping.action;
+ return { ping, pingType: "toast_notification" };
+ }
+
+ /**
+ * 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 (
+ lazy.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 = lazy.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 {
+ console.error(`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 = lazy.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 = Services.uuid.generateUUID().toString();
+ // Structured Ingestion does not support the UUID generated by Services.uuid,
+ // 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),
+ namespace
+ );
+ }
+ }
+
+ handleImpressionStats(action) {
+ const payload = this.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+ this.sendStructuredIngestionEvent(
+ payload,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "impression-stats",
+ "1"
+ );
+ }
+
+ handleTopSitesSponsoredImpressionStats(action) {
+ const { data } = action;
+ const {
+ type,
+ position,
+ source,
+ advertiser: advertiser_name,
+ tile_id,
+ } = data;
+ // Legacy telemetry (scalars and PingCentre payloads) expects 1-based tile
+ // positions.
+ const legacyTelemetryPosition = position + 1;
+
+ let pingType;
+
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ if (type === "impression") {
+ pingType = "topsites-impression";
+ Services.telemetry.keyedScalarAdd(
+ `${SCALAR_CATEGORY_TOPSITES}.impression`,
+ `${source}_${legacyTelemetryPosition}`,
+ 1
+ );
+ if (session) {
+ Glean.topsites.impression.record({
+ advertiser_name,
+ tile_id: tile_id.toString(),
+ newtab_visit_id: session.session_id,
+ is_sponsored: true,
+ position,
+ });
+ }
+ } else if (type === "click") {
+ pingType = "topsites-click";
+ Services.telemetry.keyedScalarAdd(
+ `${SCALAR_CATEGORY_TOPSITES}.click`,
+ `${source}_${legacyTelemetryPosition}`,
+ 1
+ );
+ if (session) {
+ Glean.topsites.click.record({
+ advertiser_name,
+ tile_id: tile_id.toString(),
+ newtab_visit_id: session.session_id,
+ is_sponsored: true,
+ position,
+ });
+ }
+ } else {
+ console.error("Unknown ping type for sponsored TopSites impression");
+ return;
+ }
+
+ let payload = {
+ ...data,
+ position: legacyTelemetryPosition,
+ context_id: lazy.contextId,
+ };
+ delete payload.type;
+ this.sendStructuredIngestionEvent(
+ payload,
+ STRUCTURED_INGESTION_NAMESPACE_CS,
+ pingType,
+ "1"
+ );
+ }
+
+ handleTopSitesOrganicImpressionStats(action) {
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ if (!session) {
+ return;
+ }
+
+ switch (action.data?.type) {
+ case "impression":
+ Glean.topsites.impression.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: false,
+ position: action.data.position,
+ });
+ break;
+
+ case "click":
+ Glean.topsites.click.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: false,
+ position: action.data.position,
+ });
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ handleUserEvent(action) {
+ let userEvent = this.createUserEvent(action);
+ this.sendEvent(userEvent);
+ this.sendUTEvent(userEvent, this.utEvents.sendUserEvent);
+ }
+
+ handleDiscoveryStreamUserEvent(action) {
+ const pocket_logged_in_status = lazy.pktApi.isUserLoggedIn();
+ Glean.pocket.isSignedIn.set(pocket_logged_in_status);
+ this.handleUserEvent({
+ ...action,
+ data: {
+ ...(action.data || {}),
+ value: {
+ ...(action.data?.value || {}),
+ pocket_logged_in_status,
+ },
+ },
+ });
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ switch (action.data?.event) {
+ case "CLICK":
+ if (
+ action.data.source === "POPULAR_TOPICS" ||
+ action.data.value?.card_type === "topics_widget"
+ ) {
+ Glean.pocket.topicClick.record({
+ newtab_visit_id: session.session_id,
+ topic: action.data.value?.topic,
+ });
+ } else if (["spoc", "organic"].includes(action.data.value?.card_type)) {
+ Glean.pocket.click.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: action.data.value?.card_type === "spoc",
+ position: action.data.action_position,
+ });
+ }
+ break;
+ case "SAVE_TO_POCKET":
+ Glean.pocket.save.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: action.data.value?.card_type === "spoc",
+ position: action.data.action_position,
+ });
+ break;
+ }
+ }
+
+ async handleASRouterUserEvent(action) {
+ const { ping, pingType } = await this.createASRouterEvent(action);
+ if (!pingType) {
+ console.error("Unknown ping type for ASRouter telemetry");
+ return;
+ }
+
+ // Now that the action has become a ping, we can echo it to Glean.
+ if (this.telemetryEnabled) {
+ lazy.Telemetry.submitGleanPingForPing({ ...ping, pingType });
+ }
+
+ 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;
+ let newtabCategory = "disabled";
+ let homePageCategory = "disabled";
+
+ // 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")) {
+ newtabCategory = "enabled";
+ if (
+ lazy.AboutNewTab.newTabURLOverridden &&
+ !lazy.AboutNewTab.newTabURL.startsWith("moz-extension://")
+ ) {
+ value.newtab_url_category = await this._classifySite(
+ lazy.AboutNewTab.newTabURL
+ );
+ newtabAffected = true;
+ newtabCategory = value.newtab_url_category;
+ }
+ }
+ // Check if the newtab page setting is controlled by an extension.
+ await lazy.ExtensionSettingsStore.initialize();
+ const newtabExtensionInfo = lazy.ExtensionSettingsStore.getSetting(
+ "url_overrides",
+ "newTabURL"
+ );
+ if (newtabExtensionInfo && newtabExtensionInfo.id) {
+ value.newtab_extension_id = newtabExtensionInfo.id;
+ newtabAffected = true;
+ newtabCategory = "extension";
+ }
+
+ const homePageURL = lazy.HomePage.get();
+ if (
+ !["about:home", "about:blank"].includes(homePageURL) &&
+ !homePageURL.startsWith("moz-extension://")
+ ) {
+ value.home_url_category = await this._classifySite(homePageURL);
+ homeAffected = true;
+ homePageCategory = value.home_url_category;
+ }
+ const homeExtensionInfo = lazy.ExtensionSettingsStore.getSetting(
+ "prefs",
+ "homepage_override"
+ );
+ if (homeExtensionInfo && homeExtensionInfo.id) {
+ value.home_extension_id = homeExtensionInfo.id;
+ homeAffected = true;
+ homePageCategory = "extension";
+ }
+ if (!homeAffected && !lazy.HomePage.overridden) {
+ homePageCategory = "enabled";
+ }
+
+ 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);
+ }
+ Glean.newtab.newtabCategory.set(newtabCategory);
+ Glean.newtab.homepageCategory.set(homePageCategory);
+ if (lazy.NimbusFeatures.glean.getVariable("newtabPingEnabled") ?? true) {
+ GleanPings.newtab.submit("component_init");
+ }
+ }
+ }
+
+ 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.DISCOVERY_STREAM_USER_EVENT:
+ this.handleDiscoveryStreamUserEvent(action);
+ 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 msg.SPOTLIGHT_TELEMETRY:
+ // Intentional fall-through
+ case msg.TOAST_NOTIFICATION_TELEMETRY:
+ // Intentional fall-through
+ case at.AS_ROUTER_TELEMETRY_USER_EVENT:
+ this.handleASRouterUserEvent(action);
+ break;
+ case at.TOP_SITES_SPONSORED_IMPRESSION_STATS:
+ this.handleTopSitesSponsoredImpressionStats(action);
+ break;
+ case at.TOP_SITES_ORGANIC_IMPRESSION_STATS:
+ this.handleTopSitesOrganicImpressionStats(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 { window_inner_width, window_inner_height, source, tiles } = data;
+ const impressionSets = session.impressionSets || {};
+ const impressions = impressionSets[source] || {
+ tiles: [],
+ window_inner_width,
+ window_inner_height,
+ };
+ // The payload might contain other properties, we need `id`, `pos` and potentially `shim` here.
+ tiles.forEach(tile => {
+ impressions.tiles.push({
+ id: tile.id,
+ pos: tile.pos,
+ ...(tile.shim ? { shim: tile.shim } : {}),
+ });
+ Glean.pocket.impression.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: tile.type === "spoc",
+ position: tile.pos,
+ });
+ });
+ impressionSets[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" &&
+ !lazy.HomePage.overridden &&
+ Services.prefs.getIntPref("browser.startup.page") === 1
+ ) {
+ lazy.AboutNewTab.maybeRecordTopsitesPainted(timestamp);
+ }
+
+ Object.assign(session.perf, data);
+
+ if (data.visibility_event_rcvd_ts && !session.newtabOpened) {
+ session.newtabOpened = true;
+ const source = ONBOARDING_ALLOWED_PAGE_VALUES.includes(session.page)
+ ? session.page
+ : "other";
+ Glean.newtab.opened.record({
+ newtab_visit_id: session.session_id,
+ source,
+ });
+ }
+ }
+
+ _beginObservingNewtabPingPrefs() {
+ const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+ const ACTIVITY_STREAM_PREF_BRANCH = "browser.newtabpage.activity-stream.";
+ const NEWTAB_PING_PREFS = {
+ showSearch: Glean.newtabSearch.enabled,
+ "feeds.topsites": Glean.topsites.enabled,
+ showSponsoredTopSites: Glean.topsites.sponsoredEnabled,
+ "feeds.section.topstories": Glean.pocket.enabled,
+ showSponsored: Glean.pocket.sponsoredStoriesEnabled,
+ topSitesRows: Glean.topsites.rows,
+ };
+ const setNewtabPrefMetrics = fullPrefName => {
+ const pref = fullPrefName.slice(ACTIVITY_STREAM_PREF_BRANCH.length);
+ if (!Object.hasOwn(NEWTAB_PING_PREFS, pref)) {
+ return;
+ }
+ const metric = NEWTAB_PING_PREFS[pref];
+ switch (Services.prefs.getPrefType(fullPrefName)) {
+ case Services.prefs.PREF_BOOL:
+ metric.set(Services.prefs.getBoolPref(fullPrefName));
+ break;
+
+ case Services.prefs.PREF_INT:
+ metric.set(Services.prefs.getIntPref(fullPrefName));
+ break;
+ }
+ };
+ Services.prefs.addObserver(
+ ACTIVITY_STREAM_PREF_BRANCH,
+ (subject, topic, data) => setNewtabPrefMetrics(data)
+ );
+ for (const pref of Object.keys(NEWTAB_PING_PREFS)) {
+ const fullPrefName = ACTIVITY_STREAM_PREF_BRANCH + pref;
+ setNewtabPrefMetrics(fullPrefName);
+ }
+ Glean.pocket.isSignedIn.set(lazy.pktApi.isUserLoggedIn());
+
+ const setBlockedSponsorsMetrics = () => {
+ let blocklist;
+ try {
+ blocklist = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF, "[]")
+ );
+ } catch (e) {}
+ if (blocklist) {
+ Glean.newtab.blockedSponsors.set(blocklist);
+ }
+ };
+
+ Services.prefs.addObserver(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ setBlockedSponsorsMetrics
+ );
+ setBlockedSponsorsMetrics();
+ }
+
+ 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.sys.mjs b/browser/components/newtab/lib/TippyTopProvider.sys.mjs
new file mode 100644
index 0000000000..8f32516119
--- /dev/null
+++ b/browser/components/newtab/lib/TippyTopProvider.sys.mjs
@@ -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/. */
+
+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.
+ */
+export 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;
+}
+
+export 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) {
+ console.error("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;
+ }
+}
diff --git a/browser/components/newtab/lib/ToastNotification.jsm b/browser/components/newtab/lib/ToastNotification.jsm
new file mode 100644
index 0000000000..0b2d756415
--- /dev/null
+++ b/browser/components/newtab/lib/ToastNotification.jsm
@@ -0,0 +1,118 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.sys.mjs",
+});
+
+XPCOMUtils.defineLazyServiceGetters(lazy, {
+ AlertsService: ["@mozilla.org/alerts-service;1", "nsIAlertsService"],
+});
+
+const ToastNotification = {
+ // Allow testing to stub the alerts service.
+ get AlertsService() {
+ return lazy.AlertsService;
+ },
+
+ sendUserEventTelemetry(event, message, dispatch) {
+ const ping = {
+ message_id: message.id,
+ event,
+ };
+ dispatch({
+ type: "TOAST_NOTIFICATION_TELEMETRY",
+ data: { action: "toast_notification_user_event", ...ping },
+ });
+ },
+
+ /**
+ * Show a toast notification.
+ * @param message Message containing content to show.
+ * @param dispatch A function to dispatch resulting actions.
+ * @return boolean value capturing if toast notification was displayed.
+ */
+ async showToastNotification(message, dispatch) {
+ let { content } = message;
+ let title = await lazy.RemoteL10n.formatLocalizableText(content.title);
+ let body = await lazy.RemoteL10n.formatLocalizableText(content.body);
+
+ // The only link between background task message experiment and user
+ // re-engagement via the notification is the associated "tag". Said tag is
+ // usually controlled by the message content, but for message experiments,
+ // we want to avoid a missing tag and to ensure a deterministic tag for
+ // easier analysis, including across branches.
+ let { tag } = content;
+
+ let experimentMetadata =
+ lazy.ExperimentAPI.getExperimentMetaData({
+ featureId: "backgroundTaskMessage",
+ }) || {};
+
+ if (
+ experimentMetadata?.active &&
+ experimentMetadata?.slug &&
+ experimentMetadata?.branch?.slug
+ ) {
+ // Like `my-experiment:my-branch`.
+ tag = `${experimentMetadata?.slug}:${experimentMetadata?.branch?.slug}`;
+ }
+
+ // There are two events named `IMPRESSION` the first one refers to telemetry
+ // while the other refers to ASRouter impressions used for the frequency cap
+ this.sendUserEventTelemetry("IMPRESSION", message, dispatch);
+ dispatch({ type: "IMPRESSION", data: message });
+
+ let alert = Cc["@mozilla.org/alert-notification;1"].createInstance(
+ Ci.nsIAlertNotification
+ );
+ let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
+ alert.init(
+ tag,
+ content.image_url
+ ? Services.urlFormatter.formatURL(content.image_url)
+ : content.image_url,
+ title,
+ body,
+ true /* aTextClickable */,
+ content.data,
+ null /* aDir */,
+ null /* aLang */,
+ null /* aData */,
+ systemPrincipal,
+ null /* aInPrivateBrowsing */,
+ content.requireInteraction
+ );
+
+ if (content.actions) {
+ let actions = Cu.cloneInto(content.actions, {});
+ for (let action of actions) {
+ if (action.title) {
+ action.title = await lazy.RemoteL10n.formatLocalizableText(
+ action.title
+ );
+ }
+ }
+ alert.actions = actions;
+ }
+
+ if (content.launch_url) {
+ alert.launchURL = Services.urlFormatter.formatURL(content.launch_url);
+ }
+
+ this.AlertsService.showAlert(alert);
+
+ return true;
+ },
+};
+
+const EXPORTED_SYMBOLS = ["ToastNotification"];
diff --git a/browser/components/newtab/lib/ToolbarBadgeHub.jsm b/browser/components/newtab/lib/ToolbarBadgeHub.jsm
new file mode 100644
index 0000000000..f403ca9186
--- /dev/null
+++ b/browser/components/newtab/lib/ToolbarBadgeHub.jsm
@@ -0,0 +1,318 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ clearTimeout: "resource://gre/modules/Timer.sys.mjs",
+ requestIdleCallback: "resource://gre/modules/Timer.sys.mjs",
+ setTimeout: "resource://gre/modules/Timer.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+ ToolbarPanelHub: "resource://activity-stream/lib/ToolbarPanelHub.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":
+ lazy.ToolbarPanelHub.enableToolbarButton();
+ lazy.ToolbarPanelHub.enableAppmenuButton();
+ break;
+ }
+ }
+
+ _clearBadgeTimeout() {
+ if (this.state.showBadgeTimeoutId) {
+ lazy.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
+ lazy.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.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;
+ }
+
+ lazy.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 = lazy.setTimeout(() => {
+ lazy.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 &&
+ !lazy.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);
+ }
+}
+
+/**
+ * ToolbarBadgeHub - singleton instance of _ToolbarBadgeHub that can initiate
+ * message requests and render messages.
+ */
+const 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..53e08c026b
--- /dev/null
+++ b/browser/components/newtab/lib/ToolbarPanelHub.jsm
@@ -0,0 +1,612 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ PanelMultiView: "resource:///modules/PanelMultiView.sys.mjs",
+ Preferences: "resource://gre/modules/Preferences.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.sys.mjs",
+
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
+});
+
+XPCOMUtils.defineLazyModuleGetters(lazy, {
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+});
+XPCOMUtils.defineLazyServiceGetter(
+ lazy,
+ "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;
+ lazy.EveryWindow.unregisterCallback(TOOLBAR_BUTTON_ID);
+ lazy.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;
+ lazy.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("toolkit/branding/brandings.ftl");
+ win.MozXULElement.insertFTLIfNeeded("toolkit/branding/accounts.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) {
+ lazy.EveryWindow.registerCallback(
+ APPMENU_BUTTON_ID,
+ this._showAppmenuButton,
+ this._hideAppmenuButton
+ );
+ }
+ }
+
+ // Removes the button from the Appmenu.
+ // Only used in tests.
+ disableAppmenuButton() {
+ lazy.EveryWindow.unregisterCallback(APPMENU_BUTTON_ID);
+ }
+
+ // Turns on the Toolbar button for all open windows and future windows.
+ async enableToolbarButton() {
+ if ((await this.messages).length) {
+ lazy.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 = () => {
+ lazy.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 = lazy.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 = lazy.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 = lazy.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) {
+ console.error(e);
+ url = message.content.cta_url;
+ }
+ lazy.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.sys.mjs
+ // 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 = lazy.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(
+ lazy.RemoteL10n.createElement(doc, "p", {
+ classList: "whatsNew-message-date",
+ content: new Date(content.published_date).toLocaleDateString(
+ "default",
+ {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ }
+ ),
+ })
+ );
+ }
+
+ const wrapperEl = lazy.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 = lazy.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 = lazy.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(
+ lazy.RemoteL10n.createElement(doc, "h2", {
+ classList: "whatsNew-message-title",
+ content: content.title,
+ attributes: this.state.contentArguments,
+ })
+ );
+
+ wrapperEl.appendChild(
+ lazy.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 = lazy.RemoteL10n.createElement(doc, "div");
+ messageEl.setAttribute("id", "protections-popup-message");
+ messageEl.classList.add("whatsNew-hero-message");
+ const wrapperEl = lazy.RemoteL10n.createElement(doc, "div");
+ wrapperEl.classList.add("whatsNew-message-body");
+ messageEl.appendChild(wrapperEl);
+
+ wrapperEl.appendChild(
+ lazy.RemoteL10n.createElement(doc, "h2", {
+ classList: "whatsNew-message-title",
+ content: message.content.title,
+ })
+ );
+ wrapperEl.appendChild(
+ lazy.RemoteL10n.createElement(doc, "p", {
+ classList: "protections-popup-content",
+ content: message.content.body,
+ })
+ );
+
+ if (message.content.link_text) {
+ let linkEl = lazy.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 lazy.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 lazy.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 = lazy.PanelMultiView.getViewNode(document, id);
+ document.l10n.setAttributes(el, string_id);
+ el.hidden = false;
+ }
+
+ _hideElement(document, id) {
+ const el = lazy.PanelMultiView.getViewNode(document, id);
+ if (el) {
+ el.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 &&
+ !lazy.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. No message is shown if undefined.
+ * @param {object[]} messages Messages selected from devtools page
+ */
+ forceShowMessage(browser, messages) {
+ if (!browser) {
+ return;
+ }
+ 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)
+ );
+ }
+}
+
+/**
+ * ToolbarPanelHub - singleton instance of _ToolbarPanelHub that can initiate
+ * message requests and render messages.
+ */
+const 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..9b516cb9ba
--- /dev/null
+++ b/browser/components/newtab/lib/TopSitesFeed.jsm
@@ -0,0 +1,1715 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+const { TippyTopProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/TippyTopProvider.sys.mjs"
+);
+const { insertPinned, TOP_SITES_MAX_SITES_PER_ROW } =
+ ChromeUtils.importESModule(
+ "resource://activity-stream/common/Reducers.sys.mjs"
+ );
+const { Dedupe } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Dedupe.sys.mjs"
+);
+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.importESModule(
+ "resource://activity-stream/lib/SearchShortcuts.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "FilterAdult",
+ "resource://activity-stream/lib/FilterAdult.jsm"
+);
+ChromeUtils.defineESModuleGetters(lazy, {
+ LinksCache: "resource://activity-stream/lib/LinksCache.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+ RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
+ Sampling: "resource://gre/modules/components-utils/Sampling.sys.mjs",
+});
+ChromeUtils.defineModuleGetter(
+ lazy,
+ "Screenshots",
+ "resource://activity-stream/lib/Screenshots.jsm"
+);
+
+XPCOMUtils.defineLazyGetter(lazy, "log", () => {
+ const { Logger } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/Logger.sys.mjs"
+ );
+ return new Logger("TopSitesFeed");
+});
+
+// `contextId` is a unique identifier used by Contextual Services
+const CONTEXT_ID_PREF = "browser.contextual-services.contextId";
+XPCOMUtils.defineLazyGetter(lazy, "contextId", () => {
+ let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null);
+ if (!_contextId) {
+ _contextId = String(Services.uuid.generateUUID());
+ Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId);
+ }
+ return _contextId;
+});
+
+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";
+// The default total number of sponsored top sites to fetch from Contile
+// and Pocket.
+const MAX_NUM_SPONSORED = 2;
+// Nimbus variable for the total number of sponsored top sites including
+// both Contile and Pocket sources.
+// The default will be `MAX_NUM_SPONSORED` if this variable is unspecified.
+const NIMBUS_VARIABLE_MAX_SPONSORED = "topSitesMaxSponsored";
+// Nimbus variable to allow more than two sponsored tiles from Contile to be
+//considered for Top Sites.
+const NIMBUS_VARIABLE_ADDITIONAL_TILES =
+ "topSitesUseAdditionalTilesFromContile";
+// Nimbus variable to enable the SOV feature for sponsored tiles.
+const NIMBUS_VARIABLE_CONTILE_SOV_ENABLED = "topSitesContileSovEnabled";
+// Nimbu variable for the total number of sponsor topsite that come from Contile
+// The default will be `CONTILE_MAX_NUM_SPONSORED` if variable is unspecified.
+const NIMBUS_VARIABLE_CONTILE_MAX_NUM_SPONSORED = "topSitesContileMaxSponsored";
+
+// 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 DEFAULT_SITES_OVERRIDE_PREF =
+ "browser.newtabpage.activity-stream.default.sites";
+const DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH = "browser.topsites.experiment.";
+
+// Mozilla Tiles Service (Contile) prefs
+// Nimbus variable for the Contile integration. It falls back to the pref:
+// `browser.topsites.contile.enabled`.
+const NIMBUS_VARIABLE_CONTILE_ENABLED = "topSitesContileEnabled";
+const CONTILE_ENDPOINT_PREF = "browser.topsites.contile.endpoint";
+const CONTILE_UPDATE_INTERVAL = 15 * 60 * 1000; // 15 minutes
+// The maximum number of sponsored top sites to fetch from Contile.
+const CONTILE_MAX_NUM_SPONSORED = 2;
+const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+const CONTILE_CACHE_PREF = "browser.topsites.contile.cachedTiles";
+const CONTILE_CACHE_VALID_FOR_PREF = "browser.topsites.contile.cacheValidFor";
+const CONTILE_CACHE_LAST_FETCH_PREF = "browser.topsites.contile.lastFetch";
+
+// Partners of sponsored tiles.
+const SPONSORED_TILE_PARTNER_AMP = "amp";
+const SPONSORED_TILE_PARTNER_MOZ_SALES = "moz-sales";
+const SPONSORED_TILE_PARTNERS = new Set([
+ SPONSORED_TILE_PARTNER_AMP,
+ SPONSORED_TILE_PARTNER_MOZ_SALES,
+]);
+
+function getShortURLForCurrentSearch() {
+ const url = shortURL({ url: Services.search.defaultEngine.searchForm });
+ return url;
+}
+
+class ContileIntegration {
+ constructor(topSitesFeed) {
+ this._topSitesFeed = topSitesFeed;
+ this._lastPeriodicUpdate = 0;
+ this._sites = [];
+ // The Share-of-Voice object managed by Shepherd and sent via Contile.
+ this._sov = null;
+ }
+
+ get sites() {
+ return this._sites;
+ }
+
+ get sov() {
+ return this._sov;
+ }
+
+ periodicUpdate() {
+ let now = Date.now();
+ if (now - this._lastPeriodicUpdate >= CONTILE_UPDATE_INTERVAL) {
+ this._lastPeriodicUpdate = now;
+ this.refresh();
+ }
+ }
+
+ async refresh() {
+ let updateDefaultSites = await this._fetchSites();
+ if (updateDefaultSites) {
+ this._topSitesFeed._readDefaults();
+ }
+ }
+
+ /**
+ * Clear Contile Cache Prefs.
+ */
+ _resetContileCachePrefs() {
+ Services.prefs.clearUserPref(CONTILE_CACHE_PREF);
+ Services.prefs.clearUserPref(CONTILE_CACHE_LAST_FETCH_PREF);
+ Services.prefs.clearUserPref(CONTILE_CACHE_VALID_FOR_PREF);
+ }
+
+ /**
+ * Filter the tiles whose sponsor is on the Top Sites sponsor blocklist.
+ *
+ * @param {array} tiles
+ * An array of the tile objects
+ */
+ _filterBlockedSponsors(tiles) {
+ const blocklist = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF, "[]")
+ );
+ return tiles.filter(tile => !blocklist.includes(shortURL(tile)));
+ }
+
+ /**
+ * Calculate the time Contile response is valid for based on cache-control header
+ *
+ * @param {string} cacheHeader
+ * string value of the Contile resposne cache-control header
+ */
+ _extractCacheValidFor(cacheHeader) {
+ if (cacheHeader === undefined) {
+ lazy.log.warn("Contile response cache control header is undefined");
+ return 0;
+ }
+ const [, staleIfError] = cacheHeader.match(/stale-if-error=\s*([0-9]+)/i);
+ const [, maxAge] = cacheHeader.match(/max-age=\s*([0-9]+)/i);
+ const validFor =
+ Number.parseInt(staleIfError, 10) + Number.parseInt(maxAge, 10);
+ return isNaN(validFor) ? 0 : validFor;
+ }
+
+ /**
+ * Load Tiles from Contile Cache Prefs
+ */
+ _loadTilesFromCache() {
+ lazy.log.info("Contile client is trying to load tiles from local cache.");
+ const now = Math.round(Date.now() / 1000);
+ const lastFetch = Services.prefs.getIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ 0
+ );
+ const validFor = Services.prefs.getIntPref(CONTILE_CACHE_VALID_FOR_PREF, 0);
+ if (now <= lastFetch + validFor) {
+ try {
+ let cachedTiles = JSON.parse(
+ Services.prefs.getStringPref(CONTILE_CACHE_PREF)
+ );
+ cachedTiles = this._filterBlockedSponsors(cachedTiles);
+ this._sites = cachedTiles;
+ lazy.log.info("Local cache loaded.");
+ return true;
+ } catch (error) {
+ lazy.log.warn(`Failed to load tiles from local cache: ${error}.`);
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine number of Tiles to get from Contile
+ */
+ _getMaxNumFromContile() {
+ return (
+ lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_MAX_NUM_SPONSORED
+ ) ?? CONTILE_MAX_NUM_SPONSORED
+ );
+ }
+
+ async _fetchSites() {
+ if (
+ !lazy.NimbusFeatures.newtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_ENABLED
+ ) ||
+ !this._topSitesFeed.store.getState().Prefs.values[SHOW_SPONSORED_PREF]
+ ) {
+ if (this._sites.length) {
+ this._sites = [];
+ return true;
+ }
+ return false;
+ }
+ try {
+ let url = Services.prefs.getStringPref(CONTILE_ENDPOINT_PREF);
+ const response = await fetch(url, { credentials: "omit" });
+ if (!response.ok) {
+ lazy.log.warn(
+ `Contile endpoint returned unexpected status: ${response.status}`
+ );
+ if (response.status === 304 || response.status >= 500) {
+ return this._loadTilesFromCache();
+ }
+ }
+
+ const lastFetch = Math.round(Date.now() / 1000);
+ Services.prefs.setIntPref(CONTILE_CACHE_LAST_FETCH_PREF, lastFetch);
+
+ // Contile returns 204 indicating there is no content at the moment.
+ // If this happens, it will clear `this._sites` reset the cached tiles
+ // to an empty array.
+ if (response.status === 204) {
+ if (this._sites.length) {
+ this._sites = [];
+ Services.prefs.setStringPref(
+ CONTILE_CACHE_PREF,
+ JSON.stringify(this._sites)
+ );
+ return true;
+ }
+ return false;
+ }
+ const body = await response.json();
+
+ if (body?.sov) {
+ this._sov = JSON.parse(atob(body.sov));
+ }
+ if (body?.tiles && Array.isArray(body.tiles)) {
+ const useAdditionalTiles = lazy.NimbusFeatures.newtab.getVariable(
+ NIMBUS_VARIABLE_ADDITIONAL_TILES
+ );
+
+ const maxNumFromContile = this._getMaxNumFromContile();
+
+ let { tiles } = body;
+ if (
+ useAdditionalTiles !== undefined &&
+ !useAdditionalTiles &&
+ tiles.length > maxNumFromContile
+ ) {
+ tiles.length = maxNumFromContile;
+ }
+ tiles = this._filterBlockedSponsors(tiles);
+ if (tiles.length > maxNumFromContile) {
+ lazy.log.info("Remove unused links from Contile");
+ tiles.length = maxNumFromContile;
+ }
+ this._sites = tiles;
+ Services.prefs.setStringPref(
+ CONTILE_CACHE_PREF,
+ JSON.stringify(this._sites)
+ );
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_VALID_FOR_PREF,
+ this._extractCacheValidFor(
+ response.headers.get("cache-control") ||
+ response.headers.get("Cache-Control")
+ )
+ );
+
+ return true;
+ }
+ } catch (error) {
+ lazy.log.warn(
+ `Failed to fetch data from Contile server: ${error.message}`
+ );
+ return this._loadTilesFromCache();
+ }
+ return false;
+ }
+}
+
+class TopSitesFeed {
+ constructor() {
+ this._contile = new ContileIntegration(this);
+ this._tippyTopProvider = new TippyTopProvider();
+ XPCOMUtils.defineLazyGetter(
+ this,
+ "_currentSearchHostname",
+ getShortURLForCurrentSearch
+ );
+ this.dedupe = new Dedupe(this._dedupeKey);
+ this.frecentCache = new lazy.LinksCache(
+ lazy.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 lazy.LinksCache(
+ lazy.NewTabUtils.pinnedLinks,
+ "links",
+ [...CACHED_LINK_PROPS_TO_MIGRATE, ...PINNED_FAVICON_PROPS_TO_MIGRATE]
+ );
+ lazy.PageThumbs.addExpirationFilter(this);
+ this._nimbusChangeListener = this._nimbusChangeListener.bind(this);
+ }
+
+ _nimbusChangeListener(event, reason) {
+ // The Nimbus API current doesn't specify the changed variable(s) in the
+ // listener callback, so we have to refresh unconditionally on every change
+ // of the `newtab` feature. It should be a manageable overhead given the
+ // current update cadence (6 hours) of Nimbus.
+ //
+ // Skip the experiment and rollout loading reasons since this feature has
+ // `isEarlyStartup` enabled, the feature variables are already available
+ // before the experiment or rollout loads.
+ if (
+ !["feature-experiment-loaded", "feature-rollout-loaded"].includes(reason)
+ ) {
+ this._contile.refresh();
+ }
+ }
+
+ init() {
+ // If the feed was previously disabled PREFS_INITIAL_VALUES was never received
+ this._readDefaults({ isStartup: true });
+ this._storage = this.store.dbStorage.getDbTable("sectionPrefs");
+ this._contile.refresh();
+ Services.obs.addObserver(this, "browser-search-engine-modified");
+ Services.obs.addObserver(this, "browser-region-updated");
+ Services.prefs.addObserver(REMOTE_SETTING_DEFAULTS_PREF, this);
+ Services.prefs.addObserver(DEFAULT_SITES_OVERRIDE_PREF, this);
+ Services.prefs.addObserver(DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH, this);
+ lazy.NimbusFeatures.newtab.onUpdate(this._nimbusChangeListener);
+ }
+
+ uninit() {
+ lazy.PageThumbs.removeExpirationFilter(this);
+ Services.obs.removeObserver(this, "browser-search-engine-modified");
+ Services.obs.removeObserver(this, "browser-region-updated");
+ Services.prefs.removeObserver(REMOTE_SETTING_DEFAULTS_PREF, this);
+ Services.prefs.removeObserver(DEFAULT_SITES_OVERRIDE_PREF, this);
+ Services.prefs.removeObserver(DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH, this);
+ lazy.NimbusFeatures.newtab.offUpdate(this._nimbusChangeListener);
+ }
+
+ 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.
+ // We also need to drop search shortcuts when their engine gets removed / hidden.
+ 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-updated":
+ this._readDefaults();
+ break;
+ case "nsPref:changed":
+ if (
+ data === REMOTE_SETTING_DEFAULTS_PREF ||
+ data === DEFAULT_SITES_OVERRIDE_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 = false;
+
+ if (!Services.prefs.getBoolPref(REMOTE_SETTING_DEFAULTS_PREF)) {
+ this.refreshDefaults(
+ this.store.getState().Prefs.values[DEFAULT_SITES_PREF],
+ { isStartup }
+ );
+ return;
+ }
+
+ // Try using default top sites from enterprise policies or tests. The pref
+ // is locked when set via enterprise policy. Tests have no default sites
+ // unless they set them via this pref.
+ if (
+ Services.prefs.prefIsLocked(DEFAULT_SITES_OVERRIDE_PREF) ||
+ Cu.isInAutomation
+ ) {
+ let sites = Services.prefs.getStringPref(DEFAULT_SITES_OVERRIDE_PREF, "");
+ this.refreshDefaults(sites, { isStartup });
+ return;
+ }
+
+ // Clear out the array of any previous defaults.
+ DEFAULT_TOP_SITES.length = 0;
+
+ // Read defaults from contile.
+ const contileEnabled = lazy.NimbusFeatures.newtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_ENABLED
+ );
+ let hasContileTiles = false;
+ if (contileEnabled) {
+ let sponsoredPosition = 1;
+ for (let site of this._contile.sites) {
+ let hostname = shortURL(site);
+ let link = {
+ isDefault: true,
+ url: site.url,
+ hostname,
+ sendAttributionRequest: false,
+ label: site.name,
+ show_sponsored_label: hostname !== "yandex",
+ sponsored_position: sponsoredPosition++,
+ sponsored_click_url: site.click_url,
+ sponsored_impression_url: site.impression_url,
+ sponsored_tile_id: site.id,
+ partner: SPONSORED_TILE_PARTNER_AMP,
+ };
+ if (site.image_url && site.image_size >= MIN_FAVICON_SIZE) {
+ // Only use the image from Contile if it's hi-res, otherwise, fallback
+ // to the built-in favicons.
+ link.favicon = site.image_url;
+ link.faviconSize = site.image_size;
+ }
+ DEFAULT_TOP_SITES.push(link);
+ }
+ hasContileTiles = sponsoredPosition > 1;
+ }
+
+ // Read defaults from remote settings.
+ this._useRemoteSetting = true;
+ let remoteSettingData = await this._getRemoteConfig();
+
+ const sponsoredBlocklist = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF, "[]")
+ );
+
+ for (let siteData of remoteSettingData) {
+ let hostname = shortURL(siteData);
+ // Drop default sites when Contile already provided a sponsored one with
+ // the same host name.
+ if (
+ contileEnabled &&
+ DEFAULT_TOP_SITES.findIndex(site => site.hostname === hostname) > -1
+ ) {
+ continue;
+ }
+ // Also drop those sponsored sites that were blocked by the user before
+ // with the same hostname.
+ if (
+ siteData.sponsored_position &&
+ sponsoredBlocklist.includes(hostname)
+ ) {
+ continue;
+ }
+ let link = {
+ isDefault: true,
+ url: siteData.url,
+ hostname,
+ 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) {
+ if (contileEnabled && hasContileTiles) {
+ continue;
+ }
+ const {
+ sponsored_position,
+ sponsored_tile_id,
+ sponsored_impression_url,
+ sponsored_click_url,
+ } = siteData;
+ link = {
+ sponsored_position,
+ sponsored_tile_id,
+ sponsored_impression_url,
+ sponsored_click_url,
+ show_sponsored_label: link.hostname !== "yandex",
+ ...link,
+ };
+ }
+ 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 lazy.RemoteSettings("top-sites");
+ this._remoteConfig.on("sync", () => {
+ this._readDefaults();
+ });
+ }
+
+ let result = [];
+ let failed = false;
+ try {
+ result = await this._remoteConfig.get();
+ } catch (ex) {
+ console.error(ex);
+ failed = true;
+ }
+ if (!result.length) {
+ console.error("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(lazy.Region.home)) {
+ return false;
+ }
+ if (
+ topsite.include_regions?.length &&
+ !topsite.include_regions.includes(lazy.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 && shortURL(s) === 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;
+ }
+
+ /**
+ * Fetch topsites spocs from the DiscoveryStream feed.
+ *
+ * @returns {Array} An array of sponsored tile objects.
+ */
+ fetchDiscoveryStreamSpocs() {
+ let sponsored = [];
+ const { DiscoveryStream } = this.store.getState();
+ if (DiscoveryStream) {
+ const discoveryStreamSpocs =
+ DiscoveryStream.spocs.data["sponsored-topsites"]?.items || [];
+ // Find the first component of a type and remove it from layout
+ const findSponsoredTopsitesPositions = name => {
+ for (const row of DiscoveryStream.layout) {
+ for (const component of row.components) {
+ if (component.placement?.name === name) {
+ return component.spocs.positions;
+ }
+ }
+ }
+ return null;
+ };
+
+ // Get positions from layout for now. This could be improved if we store position data in state.
+ const discoveryStreamSpocPositions =
+ findSponsoredTopsitesPositions("sponsored-topsites");
+
+ if (discoveryStreamSpocPositions?.length) {
+ function 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
+ // For now we wrap this in single quotes because this is being used in a url() css rule, and otherwise would cause a parsing error.
+ return `'https://img-getpocket.cdn.mozilla.net/${width}x${height}/filters:format(jpeg):quality(60):no_upscale():strip_exif()/${encodeURIComponent(
+ url
+ )}'`;
+ }
+
+ // We need to loop through potential spocs and set their positions.
+ // If we run out of spocs or positions, we stop.
+ // First, we need to know which array is shortest. This is our exit condition.
+ const minLength = Math.min(
+ discoveryStreamSpocPositions.length,
+ discoveryStreamSpocs.length
+ );
+ // Loop until we run out of spocs or positions.
+ for (let i = 0; i < minLength; i++) {
+ const positionIndex = discoveryStreamSpocPositions[i].index;
+ const spoc = discoveryStreamSpocs[i];
+ const link = {
+ favicon: reformatImageURL(spoc.raw_image_src, 96, 96),
+ faviconSize: 96,
+ type: "SPOC",
+ label: spoc.title || spoc.sponsor,
+ title: spoc.title || spoc.sponsor,
+ url: spoc.url,
+ flightId: spoc.flight_id,
+ id: spoc.id,
+ guid: spoc.id,
+ shim: spoc.shim,
+ // For now we are assuming position based on intended position.
+ // Actual position can shift based on other content.
+ // We send the intended position in the ping.
+ pos: positionIndex,
+ // Set this so that SPOC topsites won't be shown in the URL bar.
+ // See Bug 1822027. Note that `sponsored_position` is 1-based.
+ sponsored_position: positionIndex + 1,
+ // This is used for topsites deduping.
+ hostname: shortURL({ url: spoc.url }),
+ partner: SPONSORED_TILE_PARTNER_MOZ_SALES,
+ };
+ sponsored.push(link);
+ }
+ }
+ }
+ return sponsored;
+ }
+
+ // 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 = 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 contileSponsored = [];
+ let notBlockedDefaultSites = [];
+ for (let link of DEFAULT_TOP_SITES) {
+ // For sponsored Yandex links, default filtering is reversed: we only
+ // show them if Yandex is the default search engine.
+ if (link.sponsored_position && link.hostname === "yandex") {
+ if (link.hostname !== this._currentSearchHostname) {
+ continue;
+ }
+ } else if (this.shouldFilterSearchTile(link.hostname)) {
+ continue;
+ }
+ // Drop blocked default sites.
+ if (
+ lazy.NewTabUtils.blockedLinks.isBlocked({
+ url: link.url,
+ })
+ ) {
+ continue;
+ }
+ // If we've previously blocked a search shortcut, remove the default top site
+ // that matches the hostname
+ const searchProvider = getSearchProvider(shortURL(link));
+ if (
+ searchProvider &&
+ lazy.NewTabUtils.blockedLinks.isBlocked({ url: searchProvider.url })
+ ) {
+ continue;
+ }
+ if (link.sponsored_position) {
+ if (!prefValues[SHOW_SPONSORED_PREF]) {
+ continue;
+ }
+ contileSponsored[link.sponsored_position - 1] = link;
+
+ // Unpin search shortcut if present for the sponsored link to be shown
+ // instead.
+ this._unpinSearchShortcut(link.hostname);
+ } else {
+ notBlockedDefaultSites.push(
+ searchShortcutsExperiment
+ ? await this.topSiteToSearchTopSite(link)
+ : link
+ );
+ }
+ }
+
+ const discoverySponsored = this.fetchDiscoveryStreamSpocs();
+
+ const sponsored = await this._mergeSponsoredLinks({
+ [SPONSORED_TILE_PARTNER_AMP]: contileSponsored,
+ [SPONSORED_TILE_PARTNER_MOZ_SALES]: discoverySponsored,
+ });
+
+ this._maybeCapSponsoredLinks(sponsored);
+
+ // 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;
+ }
+
+ // Drop pinned search shortcuts when their engine has been removed / hidden.
+ if (link.searchTopSite) {
+ const searchProvider = getSearchProvider(shortURL(link));
+ if (
+ !searchProvider ||
+ !(await checkHasSearchEngine(searchProvider.keyword))
+ ) {
+ return null;
+ }
+ }
+
+ // 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 {
+ lazy.NewTabUtils.activityStreamProvider._faviconBytesToDataURI(
+ await lazy.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 = lazy.FilterAdult.filter(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 if (withPinned[index]?.sponsored_position) {
+ // We currently want DiscoveryStream spocs to replace existing spocs.
+ 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;
+ }
+
+ /**
+ * Cap sponsored links if they're more than the specified maximum.
+ *
+ * @param {Array} links An array of sponsored links. Capping will be performed in-place.
+ */
+ _maybeCapSponsoredLinks(links) {
+ // Set maximum sponsored top sites
+ const maxSponsored =
+ lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_MAX_SPONSORED
+ ) ?? MAX_NUM_SPONSORED;
+ if (links.length > maxSponsored) {
+ links.length = maxSponsored;
+ }
+ }
+
+ /**
+ * Merge sponsored links from all the partners using SOV if present.
+ * For each tile position, the user is assigned to one partner via stable sampling.
+ * If the chosen partner doesn't have a tile to serve, another tile from a different
+ * partner is used as the replacement.
+ *
+ * @param {Object} sponsoredLinks An object with sponsored links from all the partners.
+ * @returns {Array} An array of merged sponsored links.
+ */
+ async _mergeSponsoredLinks(sponsoredLinks) {
+ if (
+ !this._contile.sov ||
+ !lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_SOV_ENABLED
+ )
+ ) {
+ return Object.values(sponsoredLinks).flat();
+ }
+
+ const sampleInput = `${lazy.contextId}-${this._contile.sov.name}`;
+ let sponsored = [];
+
+ for (const allocation of this._contile.sov.allocations) {
+ let link = null;
+ let chosenPartner = null;
+ const ratios = allocation.allocation.map(alloc => alloc.percentage);
+ if (ratios.length) {
+ const index = await lazy.Sampling.ratioSample(sampleInput, ratios);
+ chosenPartner = allocation.allocation[index].partner;
+ // Unknown partners are allowed so that new parters can be added to Shepherd
+ // sooner without waiting for client changes.
+ link = sponsoredLinks[chosenPartner]?.shift();
+ }
+
+ if (!link) {
+ // If the chosen partner doesn't have a tile for this postion, choose any
+ // one from another group. For simplicity, we do _not_ do resampling here
+ // against the remaining partners.
+ for (const partner of SPONSORED_TILE_PARTNERS) {
+ if (
+ partner === chosenPartner ||
+ sponsoredLinks[partner].length === 0
+ ) {
+ continue;
+ }
+ link = sponsoredLinks[partner].shift();
+ break;
+ }
+
+ if (!link) {
+ // No more links to be added across all the partners, just return.
+ return sponsored;
+ }
+ }
+
+ // Update the position fields. Note that postion is also 1-based in SOV.
+ link.sponsored_position = allocation.position;
+ if (link.pos !== undefined) {
+ // Pocket `pos` is 0-based.
+ link.pos = allocation.position - 1;
+ }
+ sponsored.push(link);
+ }
+ // add the remaining contile sponsoredLinks when nimbus variable present
+ if (
+ lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_MAX_NUM_SPONSORED
+ )
+ ) {
+ return sponsored.concat(sponsoredLinks[SPONSORED_TILE_PARTNER_AMP]);
+ }
+
+ return sponsored;
+ }
+
+ /**
+ * 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 = {};
+ console.error("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 lazy.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 lazy.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;
+ }
+ lazy.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) {
+ lazy.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;
+ lazy.NewTabUtils.pinnedLinks.unpin(site);
+ this._broadcastPinnedSitesUpdated();
+ }
+
+ unpinAllSearchShortcuts() {
+ Services.prefs.clearUserPref(
+ `browser.newtabpage.activity-stream.${SEARCH_SHORTCUTS_HAVE_PINNED_PREF}`
+ );
+ for (let pinnedLink of lazy.NewTabUtils.pinnedLinks.links) {
+ if (pinnedLink && pinnedLink.searchTopSite) {
+ lazy.NewTabUtils.pinnedLinks.unpin(pinnedLink);
+ }
+ }
+ this.pinnedCache.expire();
+ }
+
+ _unpinSearchShortcut(vendor) {
+ for (let pinnedLink of lazy.NewTabUtils.pinnedLinks.links) {
+ if (
+ pinnedLink &&
+ pinnedLink.searchTopSite &&
+ shortURL(pinnedLink) === vendor
+ ) {
+ lazy.NewTabUtils.pinnedLinks.unpin(pinnedLink);
+ this.pinnedCache.expire();
+
+ const prevInsertedShortcuts = this.store
+ .getState()
+ .Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF].split(",");
+ this.store.dispatch(
+ ac.SetPref(
+ SEARCH_SHORTCUTS_HAVE_PINNED_PREF,
+ prevInsertedShortcuts.filter(s => s !== vendor).join(",")
+ )
+ );
+ break;
+ }
+ }
+ }
+
+ /**
+ * 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++) {
+ const link = this._linksWithDefaults[i];
+ if (
+ link &&
+ link.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 = lazy.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 }) => {
+ lazy.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 = lazy.NewTabUtils.pinnedLinks.links.findIndex(link => !link);
+ if (
+ index < 0 &&
+ lazy.NewTabUtils.pinnedLinks.links.length + 1 < numberOfSlots
+ ) {
+ // pinnedLinks can have less slots than the total available.
+ index = lazy.NewTabUtils.pinnedLinks.links.length;
+ }
+ if (index >= 0) {
+ lazy.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 });
+ this._contile.periodicUpdate();
+ break;
+ // All these actions mean we need new top sites
+ case at.PLACES_HISTORY_CLEARED:
+ case at.PLACES_LINKS_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:
+ this.refresh({ broadcast: true });
+ break;
+ case SHOW_SPONSORED_PREF:
+ if (
+ lazy.NimbusFeatures.newtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_ENABLED
+ )
+ ) {
+ this._contile.refresh();
+ } else {
+ this.refresh({ broadcast: true });
+ }
+ if (!action.data.value) {
+ this._contile._resetContileCachePrefs();
+ }
+
+ 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.DISCOVERY_STREAM_SPOCS_UPDATE:
+ // Refresh to update sponsored topsites.
+ this.refresh({ broadcast: true, isStartup: action.meta.isStartup });
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+}
+
+const EXPORTED_SYMBOLS = [
+ "TopSitesFeed",
+ "DEFAULT_TOP_SITES",
+ "ContileIntegration",
+];
diff --git a/browser/components/newtab/lib/TopStoriesFeed.jsm b/browser/components/newtab/lib/TopStoriesFeed.jsm
new file mode 100644
index 0000000000..aa51b2a4f8
--- /dev/null
+++ b/browser/components/newtab/lib/TopStoriesFeed.jsm
@@ -0,0 +1,746 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+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 { PersistentCache } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PersistentCache.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ pktApi: "chrome://pocket/content/pktApi.sys.mjs",
+});
+
+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 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 PREF_USER_TOPSTORIES = "feeds.section.topstories";
+const MAX_LIFETIME_CAP = 500; // Guard against misconfiguration on the server
+const DISCOVERY_STREAM_PREF = "discoverystream.config";
+
+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.show_spocs = options.show_spocs;
+ this.storiesLastUpdated = 0;
+ this.topicsLastUpdated = 0;
+ this.storiesLoaded = false;
+ this.dispatchPocketCta(this._prefs.get("pocketCta"), false);
+
+ // 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) {
+ console.error(`Problem initializing top stories feed: ${e.message}`);
+ }
+ }
+
+ init() {
+ SectionsManager.onceInitialized(this.onInit.bind(this));
+ }
+
+ async clearCache() {
+ await this.cache.set("stories", {});
+ await this.cache.set("topics", {});
+ await this.cache.set("spocs", {});
+ }
+
+ uninit() {
+ this.storiesLoaded = false;
+ SectionsManager.disableSection(SECTION_ID);
+ }
+
+ getPocketState(target) {
+ const action = {
+ type: at.POCKET_LOGGED_IN,
+ data: lazy.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 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);
+ this.cleanUpCampaignImpressionPref();
+ }
+ this.storiesLastUpdated = Date.now();
+ body._timestamp = this.storiesLastUpdated;
+ this.cache.set("stories", body);
+ } catch (error) {
+ console.error(`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;
+
+ 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);
+ 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 => !lazy.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,
+ score: 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.compareScore);
+
+ 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) {
+ console.error(`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 = {}) {
+ this.spocsPerNewTabs = settings.spocsPerNewTabs || 1; // Probability of a new tab getting a spoc [0,1]
+ this.recsExpireTime = settings.recsExpireTime;
+ }
+
+ // We 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 (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();
+ }
+
+ 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.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));
+ }
+ });
+ }
+ 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);
+ }
+ break;
+ }
+ }
+}
+
+const EXPORTED_SYMBOLS = [
+ "TopStoriesFeed",
+ "STORIES_UPDATE_TIME",
+ "TOPICS_UPDATE_TIME",
+ "SECTION_ID",
+ "SPOC_IMPRESSION_TRACKING_PREF",
+ "REC_IMPRESSION_TRACKING_PREF",
+ "DEFAULT_RECS_EXPIRE_TIME",
+];
diff --git a/browser/components/newtab/lib/UTEventReporting.sys.mjs b/browser/components/newtab/lib/UTEventReporting.sys.mjs
new file mode 100644
index 0000000000..8da7824415
--- /dev/null
+++ b/browser/components/newtab/lib/UTEventReporting.sys.mjs
@@ -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/. */
+
+/**
+ * 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",
+];
+
+export 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);
+ }
+}
diff --git a/browser/components/newtab/lib/cache-worker.js b/browser/components/newtab/lib/cache-worker.js
new file mode 100644
index 0000000000..afed78cb00
--- /dev/null
+++ b/browser/components/newtab/lib/cache-worker.js
@@ -0,0 +1,205 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 = () => {};
+
+/* import-globals-from /toolkit/components/workerloader/require.js */
+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 JSMs 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;
+
+ /* import-globals-from ../vendor/react.js */
+ /* import-globals-from ../vendor/react-dom.js */
+ /* import-globals-from ../vendor/react-dom-server.js */
+ /* import-globals-from ../vendor/redux.js */
+ /* import-globals-from ../vendor/react-transition-group.js */
+ /* import-globals-from ../vendor/prop-types.js */
+ /* import-globals-from ../vendor/react-redux.js */
+ /* import-globals-from ../data/content/activity-stream.bundle.js */
+ 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));
+self.addEventListener("unhandledrejection", function (error) {
+ throw error.reason;
+});
diff --git a/browser/components/newtab/loaders/inject-loader.js b/browser/components/newtab/loaders/inject-loader.js
new file mode 100644
index 0000000000..8729baf270
--- /dev/null
+++ b/browser/components/newtab/loaders/inject-loader.js
@@ -0,0 +1,59 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.urlToRequest(this.resourcePath) || {}
+ );
+
+ 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/metrics.yaml b/browser/components/newtab/metrics.yaml
new file mode 100644
index 0000000000..0b301bf013
--- /dev/null
+++ b/browser/components/newtab/metrics.yaml
@@ -0,0 +1,1221 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Adding a new metric? We have docs for that!
+# https://firefox-source-docs.mozilla.org/toolkit/components/glean/user/new_definitions_file.html
+
+---
+$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0
+$tags:
+ - 'Firefox :: New Tab Page'
+
+newtab:
+ locale:
+ type: string
+ description: >
+ The application's locale as of when newtab's TelemetryFeed was init.
+ Comes from `Services.local.appLocaleAsBCP47`.
+ Looks like `en-US`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+ lifetime: application
+
+ newtab_category:
+ type: string
+ description: >
+ The current setting of the newtab page.
+ One of ["enabled", "disabled", "extension"] or any value from
+ SiteClassifier like "known-hijacker" or "social-media".
+ Similar to Activity Stream's PAGE_TAKEOVER_DATA event's
+ `newtab_url_category`.
+ Sampled once after newtab init.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+ lifetime: application
+
+ homepage_category:
+ type: string
+ description: >
+ The current setting of the home page.
+ One of ["enabled", "disabled", "extension"] or any value from
+ SiteClassifier like "known-hijacker" or "social-media".
+ Similar to Activity Stream's PAGE_TAKEOVER_DATA event's
+ `home_url_category`.
+ Sampled once after newtab init.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+ lifetime: application
+
+ opened:
+ type: event
+ description: >
+ Recorded when newtab UI is opened via `about:newtab` or `about:home` or
+ `about:welcome` and has been made visible (see `visibility_event_rcvd_ts`
+ in
+ [detect-user-session-start.js](https://searchfox.org/mozilla-central/source/browser/components/newtab/content-src/lib/detect-user-session-start.js)).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: &newtab_visit_id
+ description: >
+ The id of this newtab visit.
+ Allows you to separate multiple simultaneous newtabs and
+ build an event timeline of actions taken from this newtab.
+ type: string
+ source:
+ description: >
+ The source that opened this newtab.
+ One of
+ * `about:newtab`
+ * `about:home`
+ * `about:welcome`
+ * `other`
+ (See `ONBOARDING_ALLOWED_PAGE_VALUES`).
+ type: string
+ send_in_pings:
+ - newtab
+
+ closed:
+ type: event
+ description: >
+ Recorded when newtab UI is closed by
+ * navigation
+ * closing the tab
+
+ Doesn't mean that the newtab was ever visible to a user.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: *newtab_visit_id
+ send_in_pings:
+ - newtab
+ blocked_sponsors:
+ type: string_list
+ description: >
+ The advertiser names that have been dismissed by the user.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1828234
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1828234#c1
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ - ttran@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+ lifetime: application
+
+newtab.search:
+ enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether the search input is enabled on the newtab.
+ Corresponds to the value of the
+ `browser.newtabpage.activity-stream.showSearch` pref.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+topsites:
+ enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether "topsites" is enabled on the newtab.
+ AKA the "Shortcuts" section.
+ Corresponds to the value of the
+ `browser.newtabpage.activity-stream.feeds.topsites` pref.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ sponsored_enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether sponsored topsites are enabled on the newtab.
+ AKA the "Sponsored Shortcuts" section.
+ Corresponds to the value of the
+ `browser.newtabpage.activity-stream.showSponsoredTopSites` pref.
+ Can be `true` even if topsites.enabled is `false`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ impression:
+ type: event
+ description: >
+ Recorded when topsite tiles are loaded.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1820707
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1820707#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1821556#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1824842#c7
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ advertiser_name: &advertiser_name
+ description: >
+ The name of the advertiser of the tile
+ type: string
+ tile_id: &tile_id
+ description: >
+ The tile id of the advertiser provided by Contile
+ type: string
+ newtab_visit_id: *newtab_visit_id
+ is_sponsored: &is_sponsored
+ description: Whether the topsite tile was sponsored.
+ type: boolean
+ position: &topsite_position
+ description: The position (0-index) of the topsite tile.
+ type: quantity
+ send_in_pings:
+ - newtab
+
+ click:
+ type: event
+ description: >
+ Recorded when a topsite tile is clicked.
+ Only happens on click. Not on middle-click. Not on "Open in new Tab"-like
+ options in the context menu.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1820707
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786670#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1820707#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1821556#c3
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1824842#c7
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ advertiser_name: *advertiser_name
+ tile_id: *tile_id
+ newtab_visit_id: *newtab_visit_id
+ is_sponsored: *is_sponsored
+ position: *topsite_position
+ send_in_pings:
+ - newtab
+
+ rows:
+ lifetime: application
+ type: quantity
+ unit: integer
+ description: >
+ The number of topsite tile rows configured to be shown on the newtab
+ page. Corresponds to the value of the
+ `browser.newtabpage.activity-stream.topSitesRows` pref. This is not the
+ number of rows actually seen by the user: if the browser window is
+ partially off-screen, or isn't wide enough to accommodate eight tiles per
+ row, the actual number of rows may be different.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1821556
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1821556#c3
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+pocket:
+ is_signed_in:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether the Firefox user is signed in to Pocket.
+ Does not correspond to a pref, so its value is resampled at newtab's
+ component init and whenever there is a Discovery Stream user event.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether Pocket is enabled on the newtab.
+ AKA the "Recommended by Pocket" section.
+ Corresponds to the value of the
+ `browser.newtabpage.activity-stream.feeds.section.topstories` pref.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ sponsored_stories_enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Whether Pocket sponsored stories are enabled on the newtab.
+ Corresponds to the value of the
+ `browser.newtabpage.activity-stream.showSponsored` pref.
+ Can be `true` even if pocket.enabled is `false`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ impression:
+ type: event
+ description: >
+ Recorded when a pocket tile is visible to the user.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: *newtab_visit_id
+ is_sponsored: &is_sponsored_pocket
+ description: Whether the pocket tile was sponsored (has an ad shim).
+ type: boolean
+ position: &pocket_position
+ description: The position (0-index) of the pocket tile.
+ type: quantity
+ send_in_pings:
+ - newtab
+
+ click:
+ type: event
+ description: >
+ Recorded when a pocket tile is clicked.
+ Only happens on click. Not on middle-click. Not on "Open in new Tab"-like
+ options in the context menu.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: *newtab_visit_id
+ is_sponsored: *is_sponsored_pocket
+ position: *pocket_position
+ send_in_pings:
+ - newtab
+
+ save:
+ type: event
+ description: >
+ Recorded when a user decides to save a pocket tile.
+ Does not mean it ends up successfully saved.
+ Just that the user clicked on "Save to Pocket" in the little pocket
+ tile menu.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: *newtab_visit_id
+ is_sponsored: *is_sponsored_pocket
+ position: *pocket_position
+ send_in_pings:
+ - newtab
+
+ topic_click:
+ type: event
+ description: >
+ Recorded when a pocket "Popular Topic" is clicked.
+ Only happens on click. Not on middle-click. Not on "Open in new Tab"-like
+ options in the context menu.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - anicholson@mozilla.com
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - najiang@mozilla.com
+ - lina@mozilla.com
+ expires: never
+ extra_keys:
+ newtab_visit_id: *newtab_visit_id
+ topic:
+ description: The topic that was clicked on. Like "entertainment".
+ type: string
+ send_in_pings:
+ - newtab
+
+
+messaging_system:
+ event_context_parse_error:
+ type: counter
+ lifetime: ping
+ description: |
+ How often we failed to parse event_context as JSON.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_reason:
+ type: string
+ lifetime: ping
+ description: |
+ The event_context's `reason`. Likely something like
+ "welcome-window-closed" or "app-shut-down",.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_page:
+ type: string
+ lifetime: ping
+ description: |
+ The event_context's `page`. Almost always "about:welcome".
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_source:
+ type: string
+ lifetime: ping
+ description: |
+ The event_context's `source`. Likely something like "primary_button".
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_context:
+ type: text
+ lifetime: ping
+ description: |
+ The stringified JSON of `event_context`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ message_id:
+ type: text
+ lifetime: ping
+ description: |
+ A string identifier of the message in Activity Stream Router.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event:
+ type: string
+ description: >
+ The type of event. Any user defined string
+ (e.g. “click”, “share”, “delete”, “more_items”)
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ ping_type:
+ type: string
+ description: >
+ Type of event the ping is capturing.
+ e.g. "cfr", "whats-new-panel", "onboarding"
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ page:
+ type: string
+ description: >
+ One of [”about:newtab”, “about:home”, “about:welcome”,
+ “unknown” (which either means not-applicable or is a bug)].
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ source:
+ type: string
+ description: >
+ The source of the interaction described by the other metrics.
+ e.g. "frecent_links", "newtab", "CFR"
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ client_id:
+ type: uuid
+ lifetime: ping
+ description: |
+ The client_id according to Telemetry.
+ Might not always have a value due to policy around specific types of
+ ping being sent. Value may be the canary client id
+ `c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0`
+ in pings near when the data upload pref is disabled (if Telemetry gets
+ to go first), or between when a client_id has been removed and when it
+ has been regenerated.
+ Present only in some circumstances (see
+ [bug 1484035]https://bugzilla.mozilla.org/show_bug.cgi?id=1484035)).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1755549
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1484035
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1755549
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ locale:
+ type: string
+ lifetime: ping
+ description: >
+ The locale as supplied to the messaging system by
+ `Services.locale.appLocaleAsBCP47`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ browser_session_id:
+ type: uuid
+ lifetime: ping
+ # Disable yamllint for long lines.
+ # yamllint disable
+ description: >
+ The Legacy Telemetry browser "session id".
+ Identifies a specific period from application start to shutdown.
+ See [the "main" ping docs](https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/data/main-ping.html)
+ for details.
+ # yamllint enable
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ impression_id:
+ type: uuid
+ lifetime: ping
+ description: >
+ The unique impression identifier for a specific client.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ bucket_id:
+ type: string
+ lifetime: ping
+ description: >
+ A name shared between multiple messages that may individually be too
+ targetted.
+ e.g. a message that gets shown on specific websites or a message asking
+ about personal information.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ action:
+ type: string
+ lifetime: ping
+ description: >
+ What type of action resulted in the event.
+ One of "IMPRESSION" or "DISMISS".
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+
+ cfr_action:
+ type: text
+ lifetime: ping
+ description: >
+ The Contextual Feature Recommender's action.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ addon_version:
+ type: string
+ lifetime: ping
+ description: >
+ Used to hold the system addon's version,
+ now is almost certainly an echo of the app's build id.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ unknown_key_count:
+ type: counter
+ description: |
+ The sum of all unknown keys counted.
+ Useful for testing.
+ Can be removed after bug 1600008 is resolved.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - chutten@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ unknown_keys:
+ type: labeled_counter
+ description: |
+ Ping keys supplied to the messaging system for which
+ we did not have a corresponding metric mapped to how often they attempted
+ to be recorded.
+ You may have forgotten to define an appropriate metric in
+ `browser/components/newtab/metrics.yaml`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ glean_ping_for_ping_failures:
+ type: counter
+ description: |
+ How often something went awry within
+ `AboutWelcome.submitGleanPingForPing`, preventing ping submission.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ - chutten@mozilla.com
+ expires: never
+ send_in_pings:
+ - metrics
+
+ invalid_nested_data:
+ type: labeled_counter
+ description: |
+ We received a ping with non-scalar data on a field of this name.
+ If this is existing pre-PingCentre-replacement data, you may need to
+ augment the logic in
+ `AboutWelcome.submitGleanPingForPing` like the other `handledKeys`.
+ If this is for new, post-PingCentre-replacement data, you should
+ probably prefer a flat structure.
+ If you're unsure, please ask in
+ [the #glean channel](https://chat.mozilla.org/#/room/#glean:mozilla.org).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ - chutten@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+
+messaging_system.attribution:
+ source:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's source, possibly derived from the utm parameter of the same
+ name.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ medium:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's medium, possibly derived from the utm parameter of the same
+ name.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ campaign:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's campaign, possibly derived from the utm parameter of the
+ same name.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ content:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's content, possibly derived from the utm parameter of the
+ same name.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ experiment:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's experiment key.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ variation:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's variation key.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ ua:
+ type: string
+ lifetime: ping
+ description: |
+ Attribution's ua key.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ dltoken:
+ type: string
+ lifetime: ping
+ description: |
+ String representation of the dltoken identifying the particular
+ installer used to install this Firefox.
+ Likely a UUID, if present.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ msstoresignedin:
+ type: string
+ lifetime: ping
+ description: |
+ Either the string "true" or the string "false" to indicate whether the
+ attributed install came from the Microsoft store and, if so, whether the
+ user was signed in at the time.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1756209
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1756209
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ dlsource:
+ type: string
+ lifetime: ping
+ description: |
+ Mozilla-specific download "source" name. Could be something like
+ "mozillaci" to identify that the installer came from
+ `{archive|ftp}.mozilla.org`.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1819997
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1819997
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ unknown_keys:
+ type: labeled_counter
+ description: |
+ Attribution keys supplied to the messaging system for which
+ we did not have a corresponding metric, and the count of how
+ often that happened.
+ Either add this key to a list of known attribution keys in
+ `AboutWelcomeTelemetry` to suppress or define an appropriate metric in
+ `browser/components/newtab/metrics.yaml` to collect.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - dmosedale@mozilla.com
+ - pmcmanis@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
diff --git a/browser/components/newtab/moz.build b/browser/components/newtab/moz.build
new file mode 100644
index 0000000000..f910767a1f
--- /dev/null
+++ b/browser/components/newtab/moz.build
@@ -0,0 +1,58 @@
+# -*- 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",
+]
+
+TESTING_JS_MODULES += [
+ "content-src/asrouter/schemas/FxMSCommon.schema.json",
+ "content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json",
+ "content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json",
+ "content-src/asrouter/templates/CFR/templates/InfoBar.schema.json",
+ "content-src/asrouter/templates/OnboardingMessage/ProtectionsPanelMessage.schema.json",
+ "content-src/asrouter/templates/OnboardingMessage/Spotlight.schema.json",
+ "content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json",
+ "content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json",
+ "content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json",
+ "content-src/asrouter/templates/PBNewtab/NewtabPromoMessage.schema.json",
+ "content-src/asrouter/templates/ToastNotification/ToastNotification.schema.json",
+ "test/InflightAssetsMessageProvider.jsm",
+]
+
+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.sys.mjs",
+ "actors/ASRouterParent.sys.mjs",
+]
+
+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..4d2a9539ce
--- /dev/null
+++ b/browser/components/newtab/package-lock.json
@@ -0,0 +1,12021 @@
+{
+ "name": "activity-streams",
+ "version": "1.14.3",
+ "lockfileVersion": 2,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "activity-streams",
+ "version": "1.14.3",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@fluent/bundle": "0.17.1",
+ "@fluent/react": "0.15.0",
+ "react": "16.13.1",
+ "react-dom": "16.13.1",
+ "react-redux": "7.2.6",
+ "react-transition-group": "4.4.2",
+ "redux": "4.1.2"
+ },
+ "devDependencies": {
+ "@babel/core": "7.16.0",
+ "@babel/plugin-proposal-class-properties": "7.16.0",
+ "@babel/plugin-proposal-nullish-coalescing-operator": "7.16.0",
+ "@babel/plugin-proposal-optional-chaining": "7.16.0",
+ "@babel/preset-react": "7.16.0",
+ "@jsdevtools/coverage-istanbul-loader": "^3.0.5",
+ "acorn": "8.5.0",
+ "babel-loader": "8.2.3",
+ "babel-plugin-jsm-to-esmodules": "0.6.0",
+ "buffer": "6.0.3",
+ "chai": "4.3.4",
+ "chai-json-schema": "1.5.1",
+ "enzyme": "3.11.0",
+ "enzyme-adapter-react-16": "1.15.6",
+ "joi-browser": "13.4.0",
+ "karma": "6.3.8",
+ "karma-chai": "0.1.0",
+ "karma-coverage-istanbul-reporter": "3.0.3",
+ "karma-firefox-launcher": "2.1.2",
+ "karma-json-reporter": "1.2.1",
+ "karma-mocha": "2.0.1",
+ "karma-mocha-reporter": "2.2.5",
+ "karma-sinon": "1.0.5",
+ "karma-sourcemap-loader": "0.3.8",
+ "karma-webpack": "5.0.0",
+ "loader-utils": "3.2.0",
+ "lodash": "4.17.21",
+ "minimist": "1.2.5",
+ "mocha": "9.1.3",
+ "mock-raf": "1.0.1",
+ "npm-run-all": "4.1.5",
+ "postcss-scss": "4.0.6",
+ "prop-types": "15.7.2",
+ "raw-loader": "4.0.2",
+ "react-test-renderer": "17.0.2",
+ "rimraf": "3.0.2",
+ "sass": "1.43.4",
+ "shelljs": "0.8.4",
+ "sinon": "12.0.1",
+ "stream-browserify": "3.0.0",
+ "util": "0.10.4",
+ "webpack": "5.56.0",
+ "webpack-cli": "4.9.1",
+ "yamscripts": "0.1.0"
+ },
+ "engines": {
+ "//": "when changing node versions, also edit .nvmrc",
+ "firefox": ">=45.0 <=*",
+ "node": "16.19.*",
+ "npm": "8.19.3"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.0.tgz",
+ "integrity": "sha512-IF4EOMEV+bfYwOmNxGzSnjR2EmQod7f1UXOpZM3l4i4o4QNwzjtJAu/HxdjHq0aYBvdqMuQEY1eg0nqW9ZPORA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/highlight": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.16.0.tgz",
+ "integrity": "sha512-DGjt2QZse5SGd9nfOSqO4WLJ8NN/oHkijbXbPrxuoJO3oIPJL3TciZs9FX+cOHNiY9E9l0opL8g7BmLe3T+9ew==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.16.0.tgz",
+ "integrity": "sha512-mYZEvshBRHGsIAiyH5PzCFTCfbWfoYbO/jcSdXQSUQu1/pW0xDZAUP7KEc32heqWTAfAHhV9j1vH8Sav7l+JNQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/generator": "^7.16.0",
+ "@babel/helper-compilation-targets": "^7.16.0",
+ "@babel/helper-module-transforms": "^7.16.0",
+ "@babel/helpers": "^7.16.0",
+ "@babel/parser": "^7.16.0",
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0",
+ "convert-source-map": "^1.7.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.1.2",
+ "semver": "^6.3.0",
+ "source-map": "^0.5.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core/node_modules/semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.0.tgz",
+ "integrity": "sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0",
+ "jsesc": "^2.5.1",
+ "source-map": "^0.5.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-annotate-as-pure": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.0.tgz",
+ "integrity": "sha512-ItmYF9vR4zA8cByDocY05o0LGUkp1zhbTQOH1NFyl5xXEqlTJQCEJjieriw+aFpxo16swMxUnUiKS7a/r4vtHg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.16.3.tgz",
+ "integrity": "sha512-vKsoSQAyBmxS35JUOOt+07cLc6Nk/2ljLIHwmq2/NM6hdioUaqEXq/S+nXvbvXbZkNDlWOymPanJGOc4CBjSJA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/compat-data": "^7.16.0",
+ "@babel/helper-validator-option": "^7.14.5",
+ "browserslist": "^4.17.5",
+ "semver": "^6.3.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets/node_modules/semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/@babel/helper-create-class-features-plugin": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.16.0.tgz",
+ "integrity": "sha512-XLwWvqEaq19zFlF5PTgOod4bUA+XbkR4WLQBct1bkzmxJGB0ZEJaoKF4c8cgH9oBtCDuYJ8BP5NB9uFiEgO5QA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-function-name": "^7.16.0",
+ "@babel/helper-member-expression-to-functions": "^7.16.0",
+ "@babel/helper-optimise-call-expression": "^7.16.0",
+ "@babel/helper-replace-supers": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-function-name": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.0.tgz",
+ "integrity": "sha512-BZh4mEk1xi2h4HFjWUXRQX5AEx4rvaZxHgax9gcjdLWdkjsY7MKt5p0otjsg5noXw+pB+clMCjw+aEVYADMjog==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-get-function-arity": "^7.16.0",
+ "@babel/template": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-get-function-arity": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.0.tgz",
+ "integrity": "sha512-ASCquNcywC1NkYh/z7Cgp3w31YW8aojjYIlNg4VeJiHkqyP4AzIvr4qx7pYDb4/s8YcsZWqqOSxgkvjUz1kpDQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-hoist-variables": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.0.tgz",
+ "integrity": "sha512-1AZlpazjUR0EQZQv3sgRNfM9mEVWPK3M6vlalczA+EECcPz3XPh6VplbErL5UoMpChhSck5wAJHthlj1bYpcmg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-member-expression-to-functions": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.16.0.tgz",
+ "integrity": "sha512-bsjlBFPuWT6IWhl28EdrQ+gTvSvj5tqVP5Xeftp07SEuz5pLnsXZuDkDD3Rfcxy0IsHmbZ+7B2/9SHzxO0T+sQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.16.0.tgz",
+ "integrity": "sha512-kkH7sWzKPq0xt3H1n+ghb4xEMP8k0U7XV3kkB+ZGy69kDk2ySFW1qPi06sjKzFY3t1j6XbJSqr4mF9L7CYVyhg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.16.0.tgz",
+ "integrity": "sha512-My4cr9ATcaBbmaEa8M0dZNA74cfI6gitvUAskgDtAFmAqyFKDSHQo5YstxPbN+lzHl2D9l/YOEFqb2mtUh4gfA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.16.0",
+ "@babel/helper-replace-supers": "^7.16.0",
+ "@babel/helper-simple-access": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0",
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-optimise-call-expression": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.16.0.tgz",
+ "integrity": "sha512-SuI467Gi2V8fkofm2JPnZzB/SUuXoJA5zXe/xzyPP2M04686RzFKFHPK6HDVN6JvWBIEW8tt9hPR7fXdn2Lgpw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.14.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.14.5.tgz",
+ "integrity": "sha512-/37qQCE3K0vvZKwoK4XU/irIJQdIfCJuhU5eKnNxpFDsOkgFaUAwbv+RYw6eYgsC0E4hS7r5KqGULUogqui0fQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-replace-supers": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.16.0.tgz",
+ "integrity": "sha512-TQxuQfSCdoha7cpRNJvfaYxxxzmbxXw/+6cS7V02eeDYyhxderSoMVALvwupA54/pZcOTtVeJ0xccp1nGWladA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-member-expression-to-functions": "^7.16.0",
+ "@babel/helper-optimise-call-expression": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-simple-access": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.16.0.tgz",
+ "integrity": "sha512-o1rjBT/gppAqKsYfUdfHq5Rk03lMQrkPHG1OWzHWpLgVXRH4HnMM9Et9CVdIqwkCQlobnGHEJMsgWP/jE1zUiw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-skip-transparent-expression-wrappers": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.16.0.tgz",
+ "integrity": "sha512-+il1gTy0oHwUsBQZyJvukbB4vPMdcYBrFHa0Uc4AizLxbq6BOYC51Rv4tWocX9BLBDLZ4kc6qUFpQ6HRgL+3zw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-split-export-declaration": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.0.tgz",
+ "integrity": "sha512-0YMMRpuDFNGTHNRiiqJX19GjNXA4H0E8jZ2ibccfSxaCogbm3am5WN/2nQNj0YnQwGWM1J06GOcQ2qnh3+0paw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.15.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz",
+ "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.14.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.14.5.tgz",
+ "integrity": "sha512-OX8D5eeX4XwcroVW45NMvoYaIuFI+GQpA2a8Gi+X/U/cDUIRsV37qQfF905F0htTRCREQIB4KqPeaveRJUl3Ow==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.16.3.tgz",
+ "integrity": "sha512-Xn8IhDlBPhvYTvgewPKawhADichOsbkZuzN7qz2BusOM0brChsyXMDJvldWaYMMUNiCQdQzNEioXTp3sC8Nt8w==",
+ "dev": true,
+ "dependencies": {
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.3",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/highlight": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.0.tgz",
+ "integrity": "sha512-t8MH41kUQylBtu2+4IQA3atqevA2lRgqA2wyVB/YiWmsDSuylZZuXOUy9ric30hfzauEFfdsuk/eXTRrGrfd0g==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "chalk": "^2.0.0",
+ "js-tokens": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.3.tgz",
+ "integrity": "sha512-dcNwU1O4sx57ClvLBVFbEgx0UZWfd0JQX5X6fxFRCLHelFBGXFfSz6Y0FAq2PEwUqlqLkdVjVr4VASEOuUnLJw==",
+ "dev": true,
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-proposal-class-properties": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.0.tgz",
+ "integrity": "sha512-mCF3HcuZSY9Fcx56Lbn+CGdT44ioBMMvjNVldpKtj8tpniETdLjnxdHI1+sDWXIM1nNt+EanJOZ3IG9lzVjs7A==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-create-class-features-plugin": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-proposal-nullish-coalescing-operator": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.0.tgz",
+ "integrity": "sha512-3bnHA8CAFm7cG93v8loghDYyQ8r97Qydf63BeYiGgYbjKKB/XP53W15wfRC7dvKfoiJ34f6Rbyyx2btExc8XsQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-proposal-optional-chaining": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.0.tgz",
+ "integrity": "sha512-Y4rFpkZODfHrVo70Uaj6cC1JJOt3Pp0MdWSwIKtb8z1/lsjl9AmnB7ErRFV+QNGIfcY1Eruc2UMx5KaRnXjMyg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0",
+ "@babel/plugin-syntax-optional-chaining": "^7.8.3"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-syntax-jsx": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.16.0.tgz",
+ "integrity": "sha512-8zv2+xiPHwly31RK4RmnEYY5zziuF3O7W2kIDW+07ewWDh6Oi0dRq8kwvulRkFgt6DB97RlKs5c1y068iPlCUg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.14.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@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,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.8.0"
+ }
+ },
+ "node_modules/@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,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.8.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-display-name": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.16.0.tgz",
+ "integrity": "sha512-FJFdJAqaCpndL+pIf0aeD/qlQwT7QXOvR6Cc8JPvNhKJBi2zc/DPc4g05Y3fbD/0iWAMQFGij4+Xw+4L/BMpTg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.14.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.16.0.tgz",
+ "integrity": "sha512-rqDgIbukZ44pqq7NIRPGPGNklshPkvlmvqjdx3OZcGPk4zGIenYkxDTvl3LsSL8gqcc3ZzGmXPE6hR/u/voNOw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-module-imports": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/plugin-syntax-jsx": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-development": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.16.0.tgz",
+ "integrity": "sha512-qq65iSqBRq0Hr3wq57YG2AmW0H6wgTnIzpffTphrUWUgLCOK+zf1f7G0vuOiXrp7dU1qq+fQBoqZ3wCDAkhFzw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/plugin-transform-react-jsx": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-pure-annotations": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.16.0.tgz",
+ "integrity": "sha512-NC/Bj2MG+t8Ef5Pdpo34Ay74X4Rt804h5y81PwOpfPtmAK3i6CizmQqwyBQzIepz1Yt8wNr2Z2L7Lu3qBMfZMA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/preset-react": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.16.0.tgz",
+ "integrity": "sha512-d31IFW2bLRB28uL1WoElyro8RH5l6531XfxMtCeCmp6RVAF1uTfxxUA0LH1tXl+psZdwfmIbwoG4U5VwgbhtLw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/helper-validator-option": "^7.14.5",
+ "@babel/plugin-transform-react-display-name": "^7.16.0",
+ "@babel/plugin-transform-react-jsx": "^7.16.0",
+ "@babel/plugin-transform-react-jsx-development": "^7.16.0",
+ "@babel/plugin-transform-react-pure-annotations": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.14.8",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.14.8.tgz",
+ "integrity": "sha512-twj3L8Og5SaCRCErB4x4ajbvBIVV77CGeFglHpeg5WC5FF8TZzBWXtTJ4MqaD9QszLYTtr+IsaAL2rEUevb+eg==",
+ "dependencies": {
+ "regenerator-runtime": "^0.13.4"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.0.tgz",
+ "integrity": "sha512-MnZdpFD/ZdYhXwiunMqqgyZyucaYsbL0IrjoGjaVhGilz+x8YB++kRfygSOIj1yOtWKPlx7NBp+9I1RQSgsd5A==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/parser": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.3.tgz",
+ "integrity": "sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/generator": "^7.16.0",
+ "@babel/helper-function-name": "^7.16.0",
+ "@babel/helper-hoist-variables": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0",
+ "@babel/parser": "^7.16.3",
+ "@babel/types": "^7.16.0",
+ "debug": "^4.1.0",
+ "globals": "^11.1.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.16.0.tgz",
+ "integrity": "sha512-PJgg/k3SdLsGb3hhisFvtLOw5ts113klrpLuIPtCJIU+BB24fqq6lf8RWqKJEjzqXR9AEH1rIb5XTqwBHB+kQg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "to-fast-properties": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@discoveryjs/json-ext": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.6.tgz",
+ "integrity": "sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/@fluent/bundle": {
+ "version": "0.17.1",
+ "resolved": "https://registry.npmjs.org/@fluent/bundle/-/bundle-0.17.1.tgz",
+ "integrity": "sha512-CRFNT9QcSFAeFDneTF59eyv3JXFGhIIN4boUO2y22YmsuuKLyDk+N1I/NQUYz9Ab63e6V7T6vItoZIG/2oOOuw==",
+ "engines": {
+ "node": ">=12.0.0",
+ "npm": ">=7.0.0"
+ }
+ },
+ "node_modules/@fluent/react": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@fluent/react/-/react-0.15.0.tgz",
+ "integrity": "sha512-qUMfaHman+UciOELQc5hnFAv0VerUR6+9gEBCRk9RR66XS13syt91ZElNOTHWe2Ofv70cxAGaJ5Yff4MRPg5Ow==",
+ "dependencies": {
+ "@fluent/sequence": "^0.8.0",
+ "cached-iterable": "^0.3.0"
+ },
+ "engines": {
+ "node": ">=14.0.0",
+ "npm": ">=7.0.0"
+ },
+ "peerDependencies": {
+ "@fluent/bundle": ">=0.16.0 <0.18.0",
+ "react": ">=16.8.0"
+ }
+ },
+ "node_modules/@fluent/react/node_modules/cached-iterable": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/cached-iterable/-/cached-iterable-0.3.0.tgz",
+ "integrity": "sha512-MDqM6TpBVebZD4UDtmlFp8EjVtRcsB6xt9aRdWymjk0fWVUUGgmt/V7o0H0gkI2Tkvv8B0ucjidZm4mLosdlWw==",
+ "engines": {
+ "node": ">=8.9.0"
+ }
+ },
+ "node_modules/@fluent/sequence": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/@fluent/sequence/-/sequence-0.8.0.tgz",
+ "integrity": "sha512-eV5QlEEVV/wR3AFQLXO67x4yPRPQXyqke0c8yucyMSeW36B3ecZyVFlY1UprzrfFV8iPJB4TAehDy/dLGbvQ1Q==",
+ "engines": {
+ "node": ">=14.0.0",
+ "npm": ">=7.0.0"
+ },
+ "peerDependencies": {
+ "@fluent/bundle": ">= 0.13.0"
+ }
+ },
+ "node_modules/@istanbuljs/schema": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz",
+ "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@jsdevtools/coverage-istanbul-loader/-/coverage-istanbul-loader-3.0.5.tgz",
+ "integrity": "sha512-EUCPEkaRPvmHjWAAZkWMT7JDzpw7FKB00WTISaiXsbNOd5hCHg77XLA8sLYLFDo1zepYLo2w7GstN8YBqRXZfA==",
+ "dev": true,
+ "dependencies": {
+ "convert-source-map": "^1.7.0",
+ "istanbul-lib-instrument": "^4.0.3",
+ "loader-utils": "^2.0.0",
+ "merge-source-map": "^1.1.0",
+ "schema-utils": "^2.7.0"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/istanbul-lib-coverage": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz",
+ "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/istanbul-lib-instrument": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz",
+ "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/core": "^7.7.5",
+ "@istanbuljs/schema": "^0.1.2",
+ "istanbul-lib-coverage": "^3.0.0",
+ "semver": "^6.3.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/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
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/loader-utils": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz",
+ "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==",
+ "dev": true,
+ "dependencies": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^2.1.2"
+ },
+ "engines": {
+ "node": ">=8.9.0"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/schema-utils": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz",
+ "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.5",
+ "ajv": "^6.12.4",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 8.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
+ "node_modules/@jsdevtools/coverage-istanbul-loader/node_modules/semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/@sinonjs/commons": {
+ "version": "1.8.3",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz",
+ "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==",
+ "dev": true,
+ "dependencies": {
+ "type-detect": "4.0.8"
+ }
+ },
+ "node_modules/@sinonjs/fake-timers": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-8.1.0.tgz",
+ "integrity": "sha512-OAPJUAtgeINhh/TAlUID4QTs53Njm7xzddaVlEs/SXwgtiD1tW22zAB/W1wdqfrpmikgaWQ9Fw6Ws+hsiRm5Vg==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^1.7.0"
+ }
+ },
+ "node_modules/@sinonjs/samsam": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.0.2.tgz",
+ "integrity": "sha512-jxPRPp9n93ci7b8hMfJOFDPRLFYadN6FSpeROFTR4UNF4i5b+EK6m4QXPO46BDhFgRy1JuS87zAnFOzCUwMJcQ==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^1.6.0",
+ "lodash.get": "^4.4.2",
+ "type-detect": "^4.0.8"
+ }
+ },
+ "node_modules/@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
+ },
+ "node_modules/@types/component-emitter": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz",
+ "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==",
+ "dev": true
+ },
+ "node_modules/@types/cookie": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz",
+ "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==",
+ "dev": true
+ },
+ "node_modules/@types/cors": {
+ "version": "2.8.12",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz",
+ "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==",
+ "dev": true
+ },
+ "node_modules/@types/eslint": {
+ "version": "8.2.1",
+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.2.1.tgz",
+ "integrity": "sha512-UP9rzNn/XyGwb5RQ2fok+DzcIRIYwc16qTXse5+Smsy8MOIccCChT15KAwnsgQx4PzJkaMq4myFyZ4CL5TjhIQ==",
+ "dev": true,
+ "dependencies": {
+ "@types/estree": "*",
+ "@types/json-schema": "*"
+ }
+ },
+ "node_modules/@types/eslint-scope": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.2.tgz",
+ "integrity": "sha512-TzgYCWoPiTeRg6RQYgtuW7iODtVoKu3RVL72k3WohqhjfaOLK5Mg2T4Tg1o2bSfu0vPkoI48wdQFv5b/Xe04wQ==",
+ "dev": true,
+ "dependencies": {
+ "@types/eslint": "*",
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "0.0.50",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.50.tgz",
+ "integrity": "sha512-C6N5s2ZFtuZRj54k2/zyRhNDjJwwcViAM3Nbm8zjBpbqAdZ00mr0CFxvSKeO8Y/e03WVFLpQMdHYVfUd6SB+Hw==",
+ "dev": true
+ },
+ "node_modules/@types/hoist-non-react-statics": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
+ "integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
+ "dependencies": {
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0"
+ }
+ },
+ "node_modules/@types/json-schema": {
+ "version": "7.0.7",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz",
+ "integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA==",
+ "dev": true
+ },
+ "node_modules/@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
+ },
+ "node_modules/@types/prop-types": {
+ "version": "15.7.4",
+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.4.tgz",
+ "integrity": "sha512-rZ5drC/jWjrArrS8BR6SIr4cWpW09RNTYt9AMZo3Jwwif+iacXAqgVjm0B0Bv/S1jhDXKHqRVNCbACkJ89RAnQ=="
+ },
+ "node_modules/@types/react": {
+ "version": "17.0.34",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-17.0.34.tgz",
+ "integrity": "sha512-46FEGrMjc2+8XhHXILr+3+/sTe3OfzSPU9YGKILLrUYbQ1CLQC9Daqo1KzENGXAWwrFwiY0l4ZbF20gRvgpWTg==",
+ "dependencies": {
+ "@types/prop-types": "*",
+ "@types/scheduler": "*",
+ "csstype": "^3.0.2"
+ }
+ },
+ "node_modules/@types/react-redux": {
+ "version": "7.1.20",
+ "resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.20.tgz",
+ "integrity": "sha512-q42es4c8iIeTgcnB+yJgRTTzftv3eYYvCZOh1Ckn2eX/3o5TdsQYKUWpLoLuGlcY/p+VAhV9IOEZJcWk/vfkXw==",
+ "dependencies": {
+ "@types/hoist-non-react-statics": "^3.3.0",
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0",
+ "redux": "^4.0.0"
+ }
+ },
+ "node_modules/@types/scheduler": {
+ "version": "0.16.2",
+ "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
+ "integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
+ },
+ "node_modules/@ungap/promise-all-settled": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz",
+ "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/ast": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz",
+ "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/helper-numbers": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/floating-point-hex-parser": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz",
+ "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-api-error": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz",
+ "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-buffer": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz",
+ "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-numbers": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz",
+ "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/floating-point-hex-parser": "1.11.1",
+ "@webassemblyjs/helper-api-error": "1.11.1",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webassemblyjs/helper-wasm-bytecode": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz",
+ "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-wasm-section": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz",
+ "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/ieee754": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz",
+ "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==",
+ "dev": true,
+ "dependencies": {
+ "@xtuc/ieee754": "^1.2.0"
+ }
+ },
+ "node_modules/@webassemblyjs/leb128": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.1.tgz",
+ "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==",
+ "dev": true,
+ "dependencies": {
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webassemblyjs/utf8": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.1.tgz",
+ "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/wasm-edit": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz",
+ "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/helper-wasm-section": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1",
+ "@webassemblyjs/wasm-opt": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1",
+ "@webassemblyjs/wast-printer": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-gen": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz",
+ "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/ieee754": "1.11.1",
+ "@webassemblyjs/leb128": "1.11.1",
+ "@webassemblyjs/utf8": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-opt": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz",
+ "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-parser": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz",
+ "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-api-error": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/ieee754": "1.11.1",
+ "@webassemblyjs/leb128": "1.11.1",
+ "@webassemblyjs/utf8": "1.11.1"
+ }
+ },
+ "node_modules/@webassemblyjs/wast-printer": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz",
+ "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webpack-cli/configtest": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.1.0.tgz",
+ "integrity": "sha512-ttOkEkoalEHa7RaFYpM0ErK1xc4twg3Am9hfHhL7MVqlHebnkYd2wuI/ZqTDj0cVzZho6PdinY0phFZV3O0Mzg==",
+ "dev": true
+ },
+ "node_modules/@webpack-cli/info": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.4.0.tgz",
+ "integrity": "sha512-F6b+Man0rwE4n0409FyAJHStYA5OIZERxmnUfLVwv0mc0V1wLad3V7jqRlMkgKBeAq07jUvglacNaa6g9lOpuw==",
+ "dev": true,
+ "dependencies": {
+ "envinfo": "^7.7.3"
+ }
+ },
+ "node_modules/@webpack-cli/serve": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.6.0.tgz",
+ "integrity": "sha512-ZkVeqEmRpBV2GHvjjUZqEai2PpUbuq8Bqd//vEYsp63J8WyexI8ppCqVS3Zs0QADf6aWuPdU+0XsPI647PVlQA==",
+ "dev": true
+ },
+ "node_modules/@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
+ },
+ "node_modules/@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
+ },
+ "node_modules/accepts": {
+ "version": "1.3.7",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
+ "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
+ "dev": true,
+ "dependencies": {
+ "mime-types": "~2.1.24",
+ "negotiator": "0.6.2"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.5.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.5.0.tgz",
+ "integrity": "sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==",
+ "dev": true,
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-import-assertions": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz",
+ "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==",
+ "dev": true
+ },
+ "node_modules/airbnb-prop-types": {
+ "version": "2.16.0",
+ "resolved": "https://registry.npmjs.org/airbnb-prop-types/-/airbnb-prop-types-2.16.0.tgz",
+ "integrity": "sha512-7WHOFolP/6cS96PhKNrslCLMYAI8yB1Pp6u6XmxozQOiZbsI5ycglZr5cHhBFfuRcQQjzCMith5ZPZdYiJCxUg==",
+ "dev": true,
+ "dependencies": {
+ "array.prototype.find": "^2.1.1",
+ "function.prototype.name": "^1.1.2",
+ "is-regex": "^1.1.0",
+ "object-is": "^1.1.2",
+ "object.assign": "^4.1.0",
+ "object.entries": "^1.1.2",
+ "prop-types": "^15.7.2",
+ "prop-types-exact": "^1.2.0",
+ "react-is": "^16.13.1"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/es-abstract/node_modules/object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "node_modules/airbnb-prop-types/node_modules/object-is": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.4.tgz",
+ "integrity": "sha512-1ZvAZ4wlF7IyPVOcE1Omikt7UpaFlOQq0HlSti+ZvDH3UiD2brwGMwDbyV43jao2bKJ+4+WdPJHSd7kgzKYVqg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/object.entries": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.3.tgz",
+ "integrity": "sha512-ym7h7OZebNS96hn5IJeyUmaWhaSM4SVtAPPfNLQEI2MYWCO2egsITb9nab2+i/Pwibx+R0mtn+ltKJXRSeTMGg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/airbnb-prop-types/node_modules/react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true
+ },
+ "node_modules/ajv-keywords": {
+ "version": "3.5.2",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
+ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
+ "dev": true
+ },
+ "node_modules/ansi-colors": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz",
+ "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==",
+ "dev": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/anymatch": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz",
+ "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==",
+ "dev": true,
+ "dependencies": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/argparse": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
+ "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
+ "dev": true,
+ "dependencies": {
+ "sprintf-js": "~1.0.2"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/array.prototype.find": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/array.prototype.find/-/array.prototype.find-2.1.1.tgz",
+ "integrity": "sha512-mi+MYNJYLTx2eNYy+Yh6raoQacCsNeeMUaspFPh9Y141lFSsWxxB8V9mM2ye+eqiRs917J6/pJ4M9ZPzenWckA==",
+ "dev": true,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/babel-loader": {
+ "version": "8.2.3",
+ "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.2.3.tgz",
+ "integrity": "sha512-n4Zeta8NC3QAsuyiizu0GkmRcQ6clkV9WFUnUf1iXP//IeSKbWjofW3UHyZVwlOB4y039YQKefawyTn64Zwbuw==",
+ "dev": true,
+ "dependencies": {
+ "find-cache-dir": "^3.3.1",
+ "loader-utils": "^1.4.0",
+ "make-dir": "^3.1.0",
+ "schema-utils": "^2.6.5"
+ },
+ "engines": {
+ "node": ">= 8.9"
+ }
+ },
+ "node_modules/babel-loader/node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "node_modules/babel-loader/node_modules/find-cache-dir": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz",
+ "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==",
+ "dev": true,
+ "dependencies": {
+ "commondir": "^1.0.1",
+ "make-dir": "^3.0.2",
+ "pkg-dir": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/babel-loader/node_modules/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
+ },
+ "node_modules/babel-loader/node_modules/json5": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
+ "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
+ "dev": true,
+ "dependencies": {
+ "minimist": "^1.2.0"
+ },
+ "bin": {
+ "json5": "lib/cli.js"
+ }
+ },
+ "node_modules/babel-loader/node_modules/loader-utils": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz",
+ "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==",
+ "dev": true,
+ "dependencies": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/babel-loader/node_modules/make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "dev": true,
+ "dependencies": {
+ "semver": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/babel-loader/node_modules/pkg-dir": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
+ "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
+ "dev": true,
+ "dependencies": {
+ "find-up": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/babel-loader/node_modules/schema-utils": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz",
+ "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.5",
+ "ajv": "^6.12.4",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 8.9.0"
+ }
+ },
+ "node_modules/babel-loader/node_modules/semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/balanced-match": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
+ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
+ "dev": true
+ },
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.1.tgz",
+ "integrity": "sha512-vFIUq7FdLtjZMhATwDul5RZWv2jpXQ09Pd6jcVEOvIsqCWTRFD/ONHNfyOS8dA/Ippi5dsIgpyKWKZaAKZltbA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "dev": true
+ },
+ "node_modules/base64id": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
+ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
+ "dev": true,
+ "engines": {
+ "node": "^4.5.0 || >= 5.9"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/body-parser/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/body-parser/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "node_modules/boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
+ "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
+ "dev": true,
+ "dependencies": {
+ "fill-range": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/browserslist": {
+ "version": "4.17.6",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.17.6.tgz",
+ "integrity": "sha512-uPgz3vyRTlEiCv4ee9KlsKgo2V6qPk7Jsn0KAn2OBqbqKo3iNcPEC1Ti6J4dwnz+aIRfEEEuOzC9IBk8tXUomw==",
+ "dev": true,
+ "dependencies": {
+ "caniuse-lite": "^1.0.30001274",
+ "electron-to-chromium": "^1.3.886",
+ "escalade": "^3.1.1",
+ "node-releases": "^2.0.1",
+ "picocolors": "^1.0.0"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "dev": true,
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/bytes": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
+ "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/call-bind": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
+ "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2"
+ }
+ },
+ "node_modules/camelcase": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz",
+ "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001425",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001425.tgz",
+ "integrity": "sha512-/pzFv0OmNG6W0ym80P3NtapU0QEiDS3VuYAZMGoLLqiC7f6FJFe1MjpQDREGApeenD9wloeytmVDj+JLXPC6qw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ }
+ ]
+ },
+ "node_modules/chai": {
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz",
+ "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==",
+ "dev": true,
+ "dependencies": {
+ "assertion-error": "^1.1.0",
+ "check-error": "^1.0.2",
+ "deep-eql": "^3.0.1",
+ "get-func-name": "^2.0.0",
+ "pathval": "^1.1.1",
+ "type-detect": "^4.0.5"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "jsonpointer.js": "0.4.0",
+ "tv4": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/check-error": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz",
+ "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=",
+ "dev": true,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "3.5.2",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz",
+ "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==",
+ "dev": true,
+ "dependencies": {
+ "anymatch": "~3.1.2",
+ "braces": "~3.0.2",
+ "glob-parent": "~5.1.2",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.6.0"
+ },
+ "engines": {
+ "node": ">= 8.10.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/chokidar/node_modules/binary-extensions": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
+ "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/chokidar/node_modules/fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/chokidar/node_modules/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,
+ "dependencies": {
+ "binary-extensions": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/chokidar/node_modules/readdirp": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
+ "dev": true,
+ "dependencies": {
+ "picomatch": "^2.2.1"
+ },
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/chrome-trace-event": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz",
+ "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.0"
+ }
+ },
+ "node_modules/cliui": {
+ "version": "7.0.4",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz",
+ "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==",
+ "dev": true,
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^7.0.0"
+ }
+ },
+ "node_modules/cliui/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cliui/node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cliui/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cliui/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "is-plain-object": "^2.0.4",
+ "kind-of": "^6.0.2",
+ "shallow-clone": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=",
+ "dev": true
+ },
+ "node_modules/colorette": {
+ "version": "2.0.16",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz",
+ "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==",
+ "dev": true
+ },
+ "node_modules/colors": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz",
+ "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.1.90"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/commondir": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
+ "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=",
+ "dev": true
+ },
+ "node_modules/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
+ },
+ "node_modules/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
+ },
+ "node_modules/connect": {
+ "version": "3.7.0",
+ "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz",
+ "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==",
+ "dev": true,
+ "dependencies": {
+ "debug": "2.6.9",
+ "finalhandler": "1.1.2",
+ "parseurl": "~1.3.3",
+ "utils-merge": "1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.10.0"
+ }
+ },
+ "node_modules/connect/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/connect/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "safe-buffer": "~5.1.1"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.1.tgz",
+ "integrity": "sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cors": {
+ "version": "2.8.5",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
+ "dev": true,
+ "dependencies": {
+ "object-assign": "^4",
+ "vary": "^1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
+ "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
+ "dev": true,
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/cross-spawn/node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cross-spawn/node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cross-spawn/node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cross-spawn/node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/css-select": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz",
+ "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=",
+ "dev": true,
+ "dependencies": {
+ "boolbase": "~1.0.0",
+ "css-what": "2.1",
+ "domutils": "1.5.1",
+ "nth-check": "~1.0.1"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.8.tgz",
+ "integrity": "sha512-jXKhWqXPmlUeoQnF/EhTtTl4C9SnrxSH/jZUih3jmO6lBKr99rP3/+FmrMj4EFpOXzMtXHAZkd3x0E6h6Fgflw=="
+ },
+ "node_modules/custom-event": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz",
+ "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=",
+ "dev": true
+ },
+ "node_modules/date-format": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-3.0.0.tgz",
+ "integrity": "sha512-eyTcpKOcamdhWJXj56DpQMo1ylSQpcGtGKXcU0Tb97+K56/CF5amAqqqNj0+KvA0iw2ynxtHWFsPDSClCxe48w==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
+ "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.1.2"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decamelize": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz",
+ "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "type-detect": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "object-keys": "^1.0.12"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/depd": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
+ "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/di": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz",
+ "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=",
+ "dev": true
+ },
+ "node_modules/diff": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz",
+ "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
+ "node_modules/discontinuous-range": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
+ "integrity": "sha1-44Mx8IRLukm5qctxx3FYWqsbxlo=",
+ "dev": true
+ },
+ "node_modules/dom-helpers": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
+ "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
+ "dependencies": {
+ "@babel/runtime": "^7.8.7",
+ "csstype": "^3.0.2"
+ }
+ },
+ "node_modules/dom-serialize": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz",
+ "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=",
+ "dev": true,
+ "dependencies": {
+ "custom-event": "~1.0.0",
+ "ent": "~2.2.0",
+ "extend": "^3.0.0",
+ "void-elements": "^2.0.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "domelementtype": "^1.3.0",
+ "entities": "^1.1.1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz",
+ "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==",
+ "dev": true
+ },
+ "node_modules/domhandler": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz",
+ "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==",
+ "dev": true,
+ "dependencies": {
+ "domelementtype": "1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
+ "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=",
+ "dev": true,
+ "dependencies": {
+ "dom-serializer": "0",
+ "domelementtype": "1"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=",
+ "dev": true
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.3.894",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.894.tgz",
+ "integrity": "sha512-WY8pA4irAZ4cm/Pr7YFPtPLVqj3nU6d0SbfoHF6M7HZNONfPdAnYAarumqQ75go2LuN72uO9wGuCEqnfya/ytg==",
+ "dev": true
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true
+ },
+ "node_modules/emojis-list": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz",
+ "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==",
+ "dev": true,
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/encodeurl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
+ "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/engine.io": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.0.1.tgz",
+ "integrity": "sha512-Y53UaciUh2Rmx5MiogtMxOQcfh7pnemday+Bb4QDg0Wjmnvo/VTvuEyNGQgYmh8L7VOe8Je1QuiqjLNDelMqLA==",
+ "dev": true,
+ "dependencies": {
+ "@types/cookie": "^0.4.1",
+ "@types/cors": "^2.8.12",
+ "@types/node": ">=10.0.0",
+ "accepts": "~1.3.4",
+ "base64id": "2.0.0",
+ "cookie": "~0.4.1",
+ "cors": "~2.8.5",
+ "debug": "~4.3.1",
+ "engine.io-parser": "~5.0.0",
+ "ws": "~8.2.3"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/engine.io-parser": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.1.tgz",
+ "integrity": "sha512-j4p3WwJrG2k92VISM0op7wiq60vO92MlF3CRGxhKHy9ywG1/Dkc72g0dXeDQ+//hrcDn8gqQzoEkdO9FN0d9AA==",
+ "dev": true,
+ "dependencies": {
+ "base64-arraybuffer": "~1.0.1"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/enhanced-resolve": {
+ "version": "5.8.3",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.8.3.tgz",
+ "integrity": "sha512-EGAbGvH7j7Xt2nc0E7D99La1OiEs8LnyimkRgwExpUMScN6O+3x9tIWs7PLQZVNx4YD+00skHXPXi1yQHpAmZA==",
+ "dev": true,
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/enhanced-resolve/node_modules/graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "dev": true
+ },
+ "node_modules/ent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz",
+ "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=",
+ "dev": true
+ },
+ "node_modules/entities": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz",
+ "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==",
+ "dev": true
+ },
+ "node_modules/envinfo": {
+ "version": "7.8.1",
+ "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.8.1.tgz",
+ "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==",
+ "dev": true,
+ "bin": {
+ "envinfo": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "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"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16": {
+ "version": "1.15.6",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-react-16/-/enzyme-adapter-react-16-1.15.6.tgz",
+ "integrity": "sha512-yFlVJCXh8T+mcQo8M6my9sPgeGzj85HSHi6Apgf1Cvq/7EL/J9+1JoJmJsRxZgyTvPMAqOEpRSu/Ii/ZpyOk0g==",
+ "dev": true,
+ "dependencies": {
+ "enzyme-adapter-utils": "^1.14.0",
+ "enzyme-shallow-equal": "^1.0.4",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.2",
+ "object.values": "^1.1.2",
+ "prop-types": "^15.7.2",
+ "react-is": "^16.13.1",
+ "react-test-renderer": "^16.0.0-0",
+ "semver": "^5.7.0"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/enzyme-shallow-equal": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/enzyme-shallow-equal/-/enzyme-shallow-equal-1.0.4.tgz",
+ "integrity": "sha512-MttIwB8kKxypwHvRynuC3ahyNc+cFbR8mjVIltnmzQ0uKGqmsfO4bfBuLxb0beLNPhjblUEYvEbsg+VSygvF1Q==",
+ "dev": true,
+ "dependencies": {
+ "has": "^1.0.3",
+ "object-is": "^1.1.2"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/object-is": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.4.tgz",
+ "integrity": "sha512-1ZvAZ4wlF7IyPVOcE1Omikt7UpaFlOQq0HlSti+ZvDH3UiD2brwGMwDbyV43jao2bKJ+4+WdPJHSd7kgzKYVqg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/object.values": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.2.tgz",
+ "integrity": "sha512-MYC0jvJopr8EK6dPBiO8Nb9mvjdypOachO5REGk6MXzujbBrAisKo3HmdEI6kZDL6fC31Mwee/5YbtMebixeag==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/react-test-renderer": {
+ "version": "16.14.0",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-16.14.0.tgz",
+ "integrity": "sha512-L8yPjqPE5CZO6rKsKXRO/rVPiaCOy0tQQJbC+UjPNlobl5mad59lvPjwFsQHTvL03caVDIVr9x9/OSgDe6I5Eg==",
+ "dev": true,
+ "dependencies": {
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2",
+ "react-is": "^16.8.6",
+ "scheduler": "^0.19.1"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/scheduler": {
+ "version": "0.19.1",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
+ "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
+ "dev": true,
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ },
+ "node_modules/enzyme-adapter-utils": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-utils/-/enzyme-adapter-utils-1.14.0.tgz",
+ "integrity": "sha512-F/z/7SeLt+reKFcb7597IThpDp0bmzcH1E9Oabqv+o01cID2/YInlqHbFl7HzWBl4h3OdZYedtwNDOmSKkk0bg==",
+ "dev": true,
+ "dependencies": {
+ "airbnb-prop-types": "^2.16.0",
+ "function.prototype.name": "^1.1.3",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.2",
+ "object.fromentries": "^2.0.3",
+ "prop-types": "^15.7.2",
+ "semver": "^5.7.1"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/function.prototype.name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.3.tgz",
+ "integrity": "sha512-H51qkbNSp8mtkJt+nyW1gyStBiKZxfRqySNUR99ylq6BPXHKI4SEvIlTKp4odLfjRKJV04DFWMU3G/YRlQOsag==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "functions-have-names": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "has": "^1.0.3",
+ "object-is": "^1.0.2"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "is-arrayish": "^0.2.1"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "0.9.3",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-0.9.3.tgz",
+ "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "is-callable": "^1.1.4",
+ "is-date-object": "^1.0.1",
+ "is-symbol": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",
+ "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=",
+ "dev": true
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/eslint-scope": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
+ "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",
+ "dev": true,
+ "dependencies": {
+ "esrecurse": "^4.3.0",
+ "estraverse": "^4.1.1"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/eslint-scope/node_modules/esrecurse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
+ "dev": true,
+ "dependencies": {
+ "estraverse": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/eslint-scope/node_modules/esrecurse/node_modules/estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/estraverse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",
+ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/eventemitter3": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
+ "dev": true
+ },
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
+ "node_modules/execa": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",
+ "dev": true,
+ "dependencies": {
+ "cross-spawn": "^7.0.3",
+ "get-stream": "^6.0.0",
+ "human-signals": "^2.1.0",
+ "is-stream": "^2.0.0",
+ "merge-stream": "^2.0.0",
+ "npm-run-path": "^4.0.1",
+ "onetime": "^5.1.2",
+ "signal-exit": "^3.0.3",
+ "strip-final-newline": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/execa/node_modules/onetime": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
+ "dev": true,
+ "dependencies": {
+ "mimic-fn": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "dev": true
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "dev": true
+ },
+ "node_modules/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
+ },
+ "node_modules/fastest-levenshtein": {
+ "version": "1.0.16",
+ "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz",
+ "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 4.9.1"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/fill-range/node_modules/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,
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/finalhandler": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
+ "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
+ "dev": true,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/finalhandler/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/finalhandler/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "node_modules/find-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
+ "dev": true,
+ "dependencies": {
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/flat": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz",
+ "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==",
+ "dev": true,
+ "bin": {
+ "flat": "cli.js"
+ }
+ },
+ "node_modules/flatted": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz",
+ "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==",
+ "dev": true
+ },
+ "node_modules/follow-redirects": {
+ "version": "1.14.5",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.5.tgz",
+ "integrity": "sha512-wtphSXy7d4/OR+MvIFbCVBDzZ5520qV8XfPklSN5QtxuMUJZ+b0Wnst1e1lCDocfzuCkHqj8k0FpZqO+UIaKNA==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
+ "node_modules/fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
+ "dev": true
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
+ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "functions-have-names": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": "6.* || 8.* || >= 10.*"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
+ "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "node_modules/get-stream": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/glob": {
+ "version": "7.1.6",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz",
+ "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==",
+ "dev": true,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/glob-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "dev": true,
+ "dependencies": {
+ "is-glob": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/glob-to-regexp": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
+ "dev": true
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/growl": {
+ "version": "1.10.5",
+ "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz",
+ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.x"
+ }
+ },
+ "node_modules/has": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
+ "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "bin": {
+ "he": "bin/he"
+ }
+ },
+ "node_modules/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==",
+ "dependencies": {
+ "react-is": "^16.7.0"
+ }
+ },
+ "node_modules/hosted-git-info": {
+ "version": "2.8.9",
+ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz",
+ "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "array-filter": "^1.0.0"
+ }
+ },
+ "node_modules/html-escaper": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
+ "dev": true
+ },
+ "node_modules/htmlparser2": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz",
+ "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==",
+ "dev": true,
+ "dependencies": {
+ "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"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/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,
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "depd": "~1.1.2",
+ "inherits": "2.0.3",
+ "setprototypeof": "1.1.1",
+ "statuses": ">= 1.5.0 < 2",
+ "toidentifier": "1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/http-errors/node_modules/inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
+ "dev": true
+ },
+ "node_modules/http-proxy": {
+ "version": "1.18.1",
+ "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz",
+ "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==",
+ "dev": true,
+ "dependencies": {
+ "eventemitter3": "^4.0.0",
+ "follow-redirects": "^1.0.0",
+ "requires-port": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/human-signals": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.17.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "dev": true
+ },
+ "node_modules/import-local": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.0.3.tgz",
+ "integrity": "sha512-bE9iaUY3CXH8Cwfan/abDKAxe1KGT9kyGsBPqf6DMK/z0a2OzAsrukeYNgIH6cH5Xr452jb1TUL8rSfCLjZ9uA==",
+ "dev": true,
+ "dependencies": {
+ "pkg-dir": "^4.2.0",
+ "resolve-cwd": "^3.0.0"
+ },
+ "bin": {
+ "import-local-fixture": "fixtures/cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/import-local/node_modules/pkg-dir": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
+ "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
+ "dev": true,
+ "dependencies": {
+ "find-up": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
+ "dev": true,
+ "dependencies": {
+ "once": "^1.3.0",
+ "wrappy": "1"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "dev": true
+ },
+ "node_modules/interpret": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz",
+ "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
+ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=",
+ "dev": true
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-docker": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
+ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
+ "dev": true,
+ "bin": {
+ "is-docker": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-glob": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+ "dev": true,
+ "dependencies": {
+ "is-extglob": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-negative-zero": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz",
+ "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-plain-obj": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz",
+ "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "isobject": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-stream": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/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,
+ "dependencies": {
+ "has-symbols": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-unicode-supported": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
+ "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/is-wsl": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
+ "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
+ "dev": true,
+ "dependencies": {
+ "is-docker": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/isbinaryfile": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.8.tgz",
+ "integrity": "sha512-53h6XFniq77YdW+spoRrebh0mnmTxRPTlcuIArO57lmMdq4uBKFKaeTjnb92oYWrSn/LVL+LT+Hap2tFQj8V+w==",
+ "dev": true,
+ "engines": {
+ "node": ">= 8.0.0"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
+ "dev": true
+ },
+ "node_modules/isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/istanbul-lib-report": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz",
+ "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==",
+ "dev": true,
+ "dependencies": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^3.0.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/istanbul-lib-coverage": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz",
+ "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "dev": true,
+ "dependencies": {
+ "semver": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "debug": "^4.1.1",
+ "istanbul-lib-coverage": "^2.0.5",
+ "make-dir": "^2.1.0",
+ "rimraf": "^2.6.3",
+ "source-map": "^0.6.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/istanbul-lib-source-maps/node_modules/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,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/istanbul-lib-source-maps/node_modules/rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "dependencies": {
+ "glob": "^7.1.3"
+ },
+ "bin": {
+ "rimraf": "bin.js"
+ }
+ },
+ "node_modules/istanbul-lib-source-maps/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/istanbul-reports": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.2.tgz",
+ "integrity": "sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw==",
+ "dev": true,
+ "dependencies": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/jest-worker": {
+ "version": "27.4.5",
+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.4.5.tgz",
+ "integrity": "sha512-f2s8kEdy15cv9r7q4KkzGXvlY0JTcmCbMHZBfSQDwW77REr45IDWwd0lksDFeVHH2jJ5pqb90T77XscrjeGzzg==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*",
+ "merge-stream": "^2.0.0",
+ "supports-color": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/jest-worker/node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/jest-worker/node_modules/supports-color": {
+ "version": "8.1.1",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
+ },
+ "node_modules/jsesc": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz",
+ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==",
+ "dev": true,
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/json5": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz",
+ "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==",
+ "dev": true,
+ "dependencies": {
+ "minimist": "^1.2.5"
+ },
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/json5/node_modules/minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ },
+ "node_modules/jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=",
+ "dev": true,
+ "dependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/just-extend": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.2.1.tgz",
+ "integrity": "sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg==",
+ "dev": true
+ },
+ "node_modules/karma": {
+ "version": "6.3.8",
+ "resolved": "https://registry.npmjs.org/karma/-/karma-6.3.8.tgz",
+ "integrity": "sha512-10wBBU9S0lBHhbCNfmmbWQaY5C1bXlKdnvzN2QKThujCI/+DKaezrI08l6bfTlpJ92VsEboq3zYKpXwK6DOi3A==",
+ "dev": true,
+ "dependencies": {
+ "body-parser": "^1.19.0",
+ "braces": "^3.0.2",
+ "chokidar": "^3.5.1",
+ "colors": "^1.4.0",
+ "connect": "^3.7.0",
+ "di": "^0.0.1",
+ "dom-serialize": "^2.2.1",
+ "glob": "^7.1.7",
+ "graceful-fs": "^4.2.6",
+ "http-proxy": "^1.18.1",
+ "isbinaryfile": "^4.0.8",
+ "lodash": "^4.17.21",
+ "log4js": "^6.3.0",
+ "mime": "^2.5.2",
+ "minimatch": "^3.0.4",
+ "qjobs": "^1.2.0",
+ "range-parser": "^1.2.1",
+ "rimraf": "^3.0.2",
+ "socket.io": "^4.2.0",
+ "source-map": "^0.6.1",
+ "tmp": "^0.2.1",
+ "ua-parser-js": "^0.7.30",
+ "yargs": "^16.1.1"
+ },
+ "bin": {
+ "karma": "bin/karma"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/karma-chai": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/karma-chai/-/karma-chai-0.1.0.tgz",
+ "integrity": "sha1-vuWtQEAFF4Ea40u5RfdikJEIt5o=",
+ "dev": true
+ },
+ "node_modules/karma-coverage-istanbul-reporter": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-3.0.3.tgz",
+ "integrity": "sha512-wE4VFhG/QZv2Y4CdAYWDbMmcAHeS926ZIji4z+FkB2aF/EposRb6DP6G5ncT/wXhqUfAb/d7kZrNKPonbvsATw==",
+ "dev": true,
+ "dependencies": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "istanbul-lib-report": "^3.0.0",
+ "istanbul-lib-source-maps": "^3.0.6",
+ "istanbul-reports": "^3.0.2",
+ "minimatch": "^3.0.4"
+ }
+ },
+ "node_modules/karma-coverage-istanbul-reporter/node_modules/istanbul-lib-coverage": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz",
+ "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/karma-firefox-launcher": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/karma-firefox-launcher/-/karma-firefox-launcher-2.1.2.tgz",
+ "integrity": "sha512-VV9xDQU1QIboTrjtGVD4NCfzIH7n01ZXqy/qpBhnOeGVOkG5JYPEm8kuSd7psHE6WouZaQ9Ool92g8LFweSNMA==",
+ "dev": true,
+ "dependencies": {
+ "is-wsl": "^2.2.0",
+ "which": "^2.0.1"
+ }
+ },
+ "node_modules/karma-firefox-launcher/node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/karma-mocha": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/karma-mocha/-/karma-mocha-2.0.1.tgz",
+ "integrity": "sha512-Tzd5HBjm8his2OA4bouAsATYEpZrp9vC7z5E5j4C5Of5Rrs1jY67RAwXNcVmd/Bnk1wgvQRou0zGVLey44G4tQ==",
+ "dev": true,
+ "dependencies": {
+ "minimist": "^1.2.3"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "chalk": "^2.1.0",
+ "log-symbols": "^2.1.0",
+ "strip-ansi": "^4.0.0"
+ }
+ },
+ "node_modules/karma-mocha-reporter/node_modules/ansi-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
+ "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/karma-mocha-reporter/node_modules/strip-ansi": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
+ "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/karma-mocha/node_modules/minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.10.0"
+ }
+ },
+ "node_modules/karma-sourcemap-loader": {
+ "version": "0.3.8",
+ "resolved": "https://registry.npmjs.org/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.8.tgz",
+ "integrity": "sha512-zorxyAakYZuBcHRJE+vbrK2o2JXLFWK8VVjiT/6P+ltLBUGUvqTEkUiQ119MGdOrK7mrmxXHZF1/pfT6GgIZ6g==",
+ "dev": true,
+ "dependencies": {
+ "graceful-fs": "^4.1.2"
+ }
+ },
+ "node_modules/karma-webpack": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/karma-webpack/-/karma-webpack-5.0.0.tgz",
+ "integrity": "sha512-+54i/cd3/piZuP3dr54+NcFeKOPnys5QeM1IY+0SPASwrtHsliXUiCL50iW+K9WWA7RvamC4macvvQ86l3KtaA==",
+ "dev": true,
+ "dependencies": {
+ "glob": "^7.1.3",
+ "minimatch": "^3.0.4",
+ "webpack-merge": "^4.1.5"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/karma/node_modules/glob": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz",
+ "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==",
+ "dev": true,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/karma/node_modules/graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "dev": true
+ },
+ "node_modules/karma/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/loader-runner": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.2.0.tgz",
+ "integrity": "sha512-92+huvxMvYlMzMt0iIOukcwYBFpkYJdpl2xsZ7LrlayO7E8SOv+JJUEK17B/dJIHAOLMfh2dZZ/Y18WgmGtYNw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.11.5"
+ }
+ },
+ "node_modules/loader-utils": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.0.tgz",
+ "integrity": "sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "node_modules/locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
+ "dev": true,
+ "dependencies": {
+ "p-locate": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/lodash": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
+ "dev": true
+ },
+ "node_modules/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
+ },
+ "node_modules/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
+ },
+ "node_modules/lodash.get": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
+ "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=",
+ "dev": true
+ },
+ "node_modules/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
+ },
+ "node_modules/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,
+ "dependencies": {
+ "chalk": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/log4js": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.3.0.tgz",
+ "integrity": "sha512-Mc8jNuSFImQUIateBFwdOQcmC6Q5maU0VVvdC2R6XMb66/VnT+7WS4D/0EeNMZu1YODmJe5NIn2XftCzEocUgw==",
+ "dev": true,
+ "dependencies": {
+ "date-format": "^3.0.0",
+ "debug": "^4.1.1",
+ "flatted": "^2.0.1",
+ "rfdc": "^1.1.4",
+ "streamroller": "^2.2.4"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/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==",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "pify": "^4.0.1",
+ "semver": "^5.6.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/memorystream": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
+ "integrity": "sha1-htcJCzDORV1j+64S3aUaR93K+bI=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.10.0"
+ }
+ },
+ "node_modules/merge-source-map": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/merge-source-map/-/merge-source-map-1.1.0.tgz",
+ "integrity": "sha512-Qkcp7P2ygktpMPh2mCQZaf3jhN6D3Z/qVZHSdWvQ+2Ef5HgRAPBO57A77+ENm0CPx2+1Ce/MYKi3ymqdfuqibw==",
+ "dev": true,
+ "dependencies": {
+ "source-map": "^0.6.1"
+ }
+ },
+ "node_modules/merge-source-map/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/merge-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
+ "dev": true
+ },
+ "node_modules/mime": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
+ "dev": true,
+ "bin": {
+ "mime": "cli.js"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.51.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
+ "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.34",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
+ "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==",
+ "dev": true,
+ "dependencies": {
+ "mime-db": "1.51.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
+ "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+ "dev": true,
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ },
+ "node_modules/mocha": {
+ "version": "9.1.3",
+ "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.3.tgz",
+ "integrity": "sha512-Xcpl9FqXOAYqI3j79pEtHBBnQgVXIhpULjGQa7DVb0Po+VzmSIK9kanAiWLHoRR/dbZ2qpdPshuXr8l1VaHCzw==",
+ "dev": true,
+ "dependencies": {
+ "@ungap/promise-all-settled": "1.1.2",
+ "ansi-colors": "4.1.1",
+ "browser-stdout": "1.3.1",
+ "chokidar": "3.5.2",
+ "debug": "4.3.2",
+ "diff": "5.0.0",
+ "escape-string-regexp": "4.0.0",
+ "find-up": "5.0.0",
+ "glob": "7.1.7",
+ "growl": "1.10.5",
+ "he": "1.2.0",
+ "js-yaml": "4.1.0",
+ "log-symbols": "4.1.0",
+ "minimatch": "3.0.4",
+ "ms": "2.1.3",
+ "nanoid": "3.1.25",
+ "serialize-javascript": "6.0.0",
+ "strip-json-comments": "3.1.1",
+ "supports-color": "8.1.1",
+ "which": "2.0.2",
+ "workerpool": "6.1.5",
+ "yargs": "16.2.0",
+ "yargs-parser": "20.2.4",
+ "yargs-unparser": "2.0.0"
+ },
+ "bin": {
+ "_mocha": "bin/_mocha",
+ "mocha": "bin/mocha"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ }
+ },
+ "node_modules/mocha/node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/mocha/node_modules/argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "dev": true
+ },
+ "node_modules/mocha/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "dev": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/chalk/node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/mocha/node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/mocha/node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
+ },
+ "node_modules/mocha/node_modules/debug": {
+ "version": "4.3.2",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",
+ "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.1.2"
+ },
+ "engines": {
+ "node": ">=6.0"
+ }
+ },
+ "node_modules/mocha/node_modules/debug/node_modules/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
+ },
+ "node_modules/mocha/node_modules/escape-string-regexp": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/find-up": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
+ "dev": true,
+ "dependencies": {
+ "locate-path": "^6.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/glob": {
+ "version": "7.1.7",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz",
+ "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==",
+ "dev": true,
+ "dependencies": {
+ "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"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/mocha/node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/mocha/node_modules/js-yaml": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
+ "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
+ "dev": true,
+ "dependencies": {
+ "argparse": "^2.0.1"
+ },
+ "bin": {
+ "js-yaml": "bin/js-yaml.js"
+ }
+ },
+ "node_modules/mocha/node_modules/locate-path": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
+ "dev": true,
+ "dependencies": {
+ "p-locate": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/log-symbols": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
+ "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==",
+ "dev": true,
+ "dependencies": {
+ "chalk": "^4.1.0",
+ "is-unicode-supported": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true
+ },
+ "node_modules/mocha/node_modules/p-limit": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+ "dev": true,
+ "dependencies": {
+ "yocto-queue": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/p-locate": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
+ "dev": true,
+ "dependencies": {
+ "p-limit": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/serialize-javascript": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz",
+ "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==",
+ "dev": true,
+ "dependencies": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "node_modules/mocha/node_modules/supports-color": {
+ "version": "8.1.1",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/mocha/node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/mocha/node_modules/yargs-parser": {
+ "version": "20.2.4",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz",
+ "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "object-assign": "^3.0.0"
+ }
+ },
+ "node_modules/mock-raf/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/moo": {
+ "version": "0.5.1",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.1.tgz",
+ "integrity": "sha512-I1mnb5xn4fO80BH9BLcF0yLypy2UKl+Cb01Fu0hJRkJjlCRtxZMWkTdAtDd5ZqCOxtCkhmRwyI57vWT+1iZ67w==",
+ "dev": true
+ },
+ "node_modules/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
+ },
+ "node_modules/nanoid": {
+ "version": "3.1.25",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.25.tgz",
+ "integrity": "sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q==",
+ "dev": true,
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/nearley": {
+ "version": "2.19.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.19.1.tgz",
+ "integrity": "sha512-xq47GIUGXxU9vQg7g/y1o1xuKnkO7ev4nRWqftmQrLkfnE/FjRqDaGOUakM8XHPn/6pW3bGjU2wgoJyId90rqg==",
+ "dev": true,
+ "dependencies": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6",
+ "semver": "^5.4.1"
+ },
+ "bin": {
+ "nearley-railroad": "bin/nearley-railroad.js",
+ "nearley-test": "bin/nearley-test.js",
+ "nearley-unparse": "bin/nearley-unparse.js",
+ "nearleyc": "bin/nearleyc.js"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/neo-async": {
+ "version": "2.6.2",
+ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
+ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
+ "dev": true
+ },
+ "node_modules/nice-try": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",
+ "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
+ "dev": true
+ },
+ "node_modules/nise": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.0.tgz",
+ "integrity": "sha512-W5WlHu+wvo3PaKLsJJkgPup2LrsXCcm7AWwyNZkUnn5rwPkuPBi3Iwk5SQtN0mv+K65k7nKKjwNQ30wg3wLAQQ==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^1.7.0",
+ "@sinonjs/fake-timers": "^7.0.4",
+ "@sinonjs/text-encoding": "^0.7.1",
+ "just-extend": "^4.0.2",
+ "path-to-regexp": "^1.7.0"
+ }
+ },
+ "node_modules/nise/node_modules/@sinonjs/fake-timers": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-7.1.2.tgz",
+ "integrity": "sha512-iQADsW4LBMISqZ6Ci1dupJL9pprqwcVFTcOsEmQOEhW+KLCVn/Y4Jrvg2k19fIHCp+iFprriYPTdRcQR8NbUPg==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^1.7.0"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.1.tgz",
+ "integrity": "sha512-CqyzN6z7Q6aMeF/ktcMVTzhAHCEpf8SOarwpzpf8pNBY2k5/oM34UHldUwp8VKI7uxct2HxSRdJjBaZeESzcxA==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "hosted-git-info": "^2.1.4",
+ "resolve": "^1.10.0",
+ "semver": "2 || 3 || 4 || 5",
+ "validate-npm-package-license": "^3.0.1"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "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"
+ },
+ "bin": {
+ "npm-run-all": "bin/npm-run-all/index.js",
+ "run-p": "bin/run-p/index.js",
+ "run-s": "bin/run-s/index.js"
+ },
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/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,
+ "dependencies": {
+ "nice-try": "^1.0.4",
+ "path-key": "^2.0.1",
+ "semver": "^5.5.0",
+ "shebang-command": "^1.2.0",
+ "which": "^1.2.9"
+ },
+ "engines": {
+ "node": ">=4.8"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/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,
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "parse-json": "^4.0.0",
+ "pify": "^3.0.0",
+ "strip-bom": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/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,
+ "dependencies": {
+ "error-ex": "^1.3.1",
+ "json-parse-better-errors": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/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,
+ "dependencies": {
+ "pify": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/pify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz",
+ "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/npm-run-all/node_modules/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,
+ "dependencies": {
+ "load-json-file": "^4.0.0",
+ "normalize-package-data": "^2.3.2",
+ "path-type": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/npm-run-path": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",
+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",
+ "dev": true,
+ "dependencies": {
+ "path-key": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/npm-run-path/node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "boolbase": "~1.0.0"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.2",
+ "function-bind": "^1.1.1",
+ "has-symbols": "^1.0.0",
+ "object-keys": "^1.0.11"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.3.tgz",
+ "integrity": "sha512-IDUSMXs6LOSJBWE++L0lzIbSqHl9KDCfff2x/JSEIDtEUavUnyMYC2ZGay/04Zq4UT8lvd4xNhU4/YHKibAOlw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries/node_modules/es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries/node_modules/is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries/node_modules/is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries/node_modules/object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "node_modules/object.fromentries/node_modules/object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
+ "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
+ "dev": true,
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
+ "dev": true,
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "dev": true,
+ "dependencies": {
+ "p-try": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
+ "dev": true,
+ "dependencies": {
+ "p-limit": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/parse5": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-3.0.3.tgz",
+ "integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
+ "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/path-parse": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "isarray": "0.0.1"
+ }
+ },
+ "node_modules/path-to-regexp/node_modules/isarray": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
+ "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=",
+ "dev": true
+ },
+ "node_modules/pathval": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz",
+ "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==",
+ "dev": true,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=",
+ "dev": true
+ },
+ "node_modules/picocolors": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz",
+ "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==",
+ "dev": true
+ },
+ "node_modules/picomatch": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "dev": true,
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/pidtree": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.0.tgz",
+ "integrity": "sha512-9CT4NFlDcosssyg8KVFltgokyKZIFjoBxw8CTGy+5F38Y1eQWrt8tRayiUOXE+zVKQnYu5BR8JjCtvK3BcnBhg==",
+ "dev": true,
+ "bin": {
+ "pidtree": "bin/pidtree.js"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/pify": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
+ "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==",
+ "dev": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.4.23",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.23.tgz",
+ "integrity": "sha512-bQ3qMcpF6A/YjR55xtoTr0jGOlnPOKAIMdOWiv0EIT6HVPEaJiJB4NLljSbiHoC2RX7DN5Uvjtpbg1NPdwv1oA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "peer": true,
+ "dependencies": {
+ "nanoid": "^3.3.6",
+ "picocolors": "^1.0.0",
+ "source-map-js": "^1.0.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postcss-scss": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/postcss-scss/-/postcss-scss-4.0.6.tgz",
+ "integrity": "sha512-rLDPhJY4z/i4nVFZ27j9GqLxj1pwxE80eAzUNRMXtcpipFYIeowerzBgG3yJhMtObGEXidtIgbUpQ3eLDsf5OQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss-scss"
+ }
+ ],
+ "engines": {
+ "node": ">=12.0"
+ },
+ "peerDependencies": {
+ "postcss": "^8.4.19"
+ }
+ },
+ "node_modules/postcss/node_modules/nanoid": {
+ "version": "3.3.6",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz",
+ "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "peer": true,
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/prop-types": {
+ "version": "15.7.2",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",
+ "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",
+ "dependencies": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.8.1"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "has": "^1.0.3",
+ "object.assign": "^4.1.0",
+ "reflect.ownkeys": "^0.2.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.9"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.7.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
+ "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/raf": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
+ "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
+ "dev": true,
+ "dependencies": {
+ "performance-now": "^2.1.0"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/randexp": {
+ "version": "0.4.6",
+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",
+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",
+ "dev": true,
+ "dependencies": {
+ "discontinuous-range": "1.0.0",
+ "ret": "~0.1.10"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
+ "node_modules/randombytes": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
+ "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
+ "dev": true,
+ "dependencies": {
+ "safe-buffer": "^5.1.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "bytes": "3.1.0",
+ "http-errors": "1.7.2",
+ "iconv-lite": "0.4.24",
+ "unpipe": "1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/raw-loader": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-4.0.2.tgz",
+ "integrity": "sha512-ZnScIV3ag9A4wPX/ZayxL/jZH+euYb6FcUinPcgiQW0+UBtEv0O6Q3lGd3cqJ+GHH+rksEv3Pj99oxJ3u3VIKA==",
+ "dev": true,
+ "dependencies": {
+ "loader-utils": "^2.0.0",
+ "schema-utils": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/raw-loader/node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "node_modules/raw-loader/node_modules/ajv-keywords": {
+ "version": "3.5.2",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
+ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
+ "dev": true
+ },
+ "node_modules/raw-loader/node_modules/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
+ },
+ "node_modules/raw-loader/node_modules/loader-utils": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz",
+ "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==",
+ "dev": true,
+ "dependencies": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^2.1.2"
+ },
+ "engines": {
+ "node": ">=8.9.0"
+ }
+ },
+ "node_modules/raw-loader/node_modules/schema-utils": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.0.0.tgz",
+ "integrity": "sha512-6D82/xSzO094ajanoOSbe4YvXWMfn2A//8Y1+MUqFAJul5Bs+yn36xbK9OtNDcRVSBJ9jjeoXftM6CfztsjOAA==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.6",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/react": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-16.13.1.tgz",
+ "integrity": "sha512-YMZQQq32xHLX0bz5Mnibv1/LHb3Sqzngu7xstSM+vrkE5Kzr9xE0yMByK5kMoTK30YVJE61WfbxIFFvfeDKT1w==",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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==",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2",
+ "scheduler": "^0.19.1"
+ }
+ },
+ "node_modules/react-dom/node_modules/scheduler": {
+ "version": "0.19.1",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
+ "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ },
+ "node_modules/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=="
+ },
+ "node_modules/react-redux": {
+ "version": "7.2.6",
+ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.6.tgz",
+ "integrity": "sha512-10RPdsz0UUrRL1NZE0ejTkucnclYSgXp5q+tB5SWx2qeG2ZJQJyymgAhwKy73yiL/13btfB6fPr+rgbMAaZIAQ==",
+ "dependencies": {
+ "@babel/runtime": "^7.15.4",
+ "@types/react-redux": "^7.1.20",
+ "hoist-non-react-statics": "^3.3.2",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.7.2",
+ "react-is": "^17.0.2"
+ }
+ },
+ "node_modules/react-redux/node_modules/@babel/runtime": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.3.tgz",
+ "integrity": "sha512-WBwekcqacdY2e9AF/Q7WLFUWmdJGJTkbjqTjoMDgXkVZ3ZRUvOPsLb5KdwISoQVsbP+DQzVZW4Zhci0DvpbNTQ==",
+ "dependencies": {
+ "regenerator-runtime": "^0.13.4"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/react-redux/node_modules/react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
+ },
+ "node_modules/react-shallow-renderer": {
+ "version": "16.14.1",
+ "resolved": "https://registry.npmjs.org/react-shallow-renderer/-/react-shallow-renderer-16.14.1.tgz",
+ "integrity": "sha512-rkIMcQi01/+kxiTE9D3fdS959U1g7gs+/rborw++42m1O9FAQiNI/UNRZExVUoAOprn4umcXf+pFRou8i4zuBg==",
+ "dev": true,
+ "dependencies": {
+ "object-assign": "^4.1.1",
+ "react-is": "^16.12.0 || ^17.0.0"
+ }
+ },
+ "node_modules/react-test-renderer": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-17.0.2.tgz",
+ "integrity": "sha512-yaQ9cB89c17PUb0x6UfWRs7kQCorVdHlutU1boVPEsB8IDZH6n9tHxMacc3y0JoXOJUsZb/t/Mb8FUWMKaM7iQ==",
+ "dev": true,
+ "dependencies": {
+ "object-assign": "^4.1.1",
+ "react-is": "^17.0.2",
+ "react-shallow-renderer": "^16.13.1",
+ "scheduler": "^0.20.2"
+ }
+ },
+ "node_modules/react-test-renderer/node_modules/react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
+ "dev": true
+ },
+ "node_modules/react-transition-group": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.2.tgz",
+ "integrity": "sha512-/RNYfRAMlZwDSr6z4zNKV6xu53/e2BuaBbGhbyYIXTrmgu/bGHzmqOs7mJSJBHy9Ud+ApHx3QjrkKSp1pxvlFg==",
+ "dependencies": {
+ "@babel/runtime": "^7.5.5",
+ "dom-helpers": "^5.0.1",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.6.2"
+ }
+ },
+ "node_modules/rechoir": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz",
+ "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=",
+ "dev": true,
+ "dependencies": {
+ "resolve": "^1.1.6"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/redux": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/redux/-/redux-4.1.2.tgz",
+ "integrity": "sha512-SH8PglcebESbd/shgf6mii6EIoRM0zrQyjcuQ+ojmfxjTtE0z9Y8pa62iA/OJ58qjP6j27uyW4kUF4jl/jd6sw==",
+ "dependencies": {
+ "@babel/runtime": "^7.9.2"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/regenerator-runtime": {
+ "version": "0.13.7",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz",
+ "integrity": "sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew=="
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/requires-port": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
+ "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=",
+ "dev": true
+ },
+ "node_modules/resolve": {
+ "version": "1.15.1",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz",
+ "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==",
+ "dev": true,
+ "dependencies": {
+ "path-parse": "^1.0.6"
+ }
+ },
+ "node_modules/resolve-cwd": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz",
+ "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==",
+ "dev": true,
+ "dependencies": {
+ "resolve-from": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/resolve-cwd/node_modules/resolve-from": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
+ "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
+ "node_modules/rfdc": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz",
+ "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==",
+ "dev": true
+ },
+ "node_modules/rimraf": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
+ "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
+ "dev": true,
+ "dependencies": {
+ "glob": "^7.1.3"
+ },
+ "bin": {
+ "rimraf": "bin.js"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "lodash.flattendeep": "^4.4.0",
+ "nearley": "^2.7.10"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true
+ },
+ "node_modules/sass": {
+ "version": "1.43.4",
+ "resolved": "https://registry.npmjs.org/sass/-/sass-1.43.4.tgz",
+ "integrity": "sha512-/ptG7KE9lxpGSYiXn7Ar+lKOv37xfWsZRtFYal2QHNigyVQDx685VFT/h7ejVr+R8w7H4tmUgtulsKl5YpveOg==",
+ "dev": true,
+ "dependencies": {
+ "chokidar": ">=3.0.0 <4.0.0"
+ },
+ "bin": {
+ "sass": "sass.js"
+ },
+ "engines": {
+ "node": ">=8.9.0"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz",
+ "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==",
+ "dev": true,
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ },
+ "node_modules/semver": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
+ "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/serialize-javascript": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz",
+ "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==",
+ "dev": true,
+ "dependencies": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
+ "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==",
+ "dev": true
+ },
+ "node_modules/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,
+ "dependencies": {
+ "kind-of": "^6.0.2"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "shebang-regex": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/shelljs": {
+ "version": "0.8.4",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.4.tgz",
+ "integrity": "sha512-7gk3UZ9kOfPLIAbslLzyWeGiEqx9e3rxwZM0KE6EL8GlGwjym9Mrlx5/p33bWTu9YG6vcS4MBxYZDHYr5lr8BQ==",
+ "dev": true,
+ "dependencies": {
+ "glob": "^7.0.0",
+ "interpret": "^1.0.0",
+ "rechoir": "^0.6.2"
+ },
+ "bin": {
+ "shjs": "bin/shjs"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/signal-exit": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz",
+ "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==",
+ "dev": true
+ },
+ "node_modules/sinon": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/sinon/-/sinon-12.0.1.tgz",
+ "integrity": "sha512-iGu29Xhym33ydkAT+aNQFBINakjq69kKO6ByPvTsm3yyIACfyQttRTP03aBP/I8GfhFmLzrnKwNNkr0ORb1udg==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^1.8.3",
+ "@sinonjs/fake-timers": "^8.1.0",
+ "@sinonjs/samsam": "^6.0.2",
+ "diff": "^5.0.0",
+ "nise": "^5.1.0",
+ "supports-color": "^7.2.0"
+ }
+ },
+ "node_modules/sinon/node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/sinon/node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/socket.io": {
+ "version": "4.3.2",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.3.2.tgz",
+ "integrity": "sha512-6S5tV4jcY6dbZ/lLzD6EkvNWI3s81JO6ABP/EpvOlK1NPOcIj3AS4khi6xXw6JlZCASq82HQV4SapfmVMMl2dg==",
+ "dev": true,
+ "dependencies": {
+ "accepts": "~1.3.4",
+ "base64id": "~2.0.0",
+ "debug": "~4.3.2",
+ "engine.io": "~6.0.0",
+ "socket.io-adapter": "~2.3.2",
+ "socket.io-parser": "~4.0.4"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/socket.io-adapter": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.2.tgz",
+ "integrity": "sha512-PBZpxUPYjmoogY0aoaTmo1643JelsaS1CiAwNjRVdrI0X9Seuc19Y2Wife8k88avW6haG8cznvwbubAZwH4Mtg==",
+ "dev": true
+ },
+ "node_modules/socket.io-parser": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz",
+ "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==",
+ "dev": true,
+ "dependencies": {
+ "@types/component-emitter": "^1.2.10",
+ "component-emitter": "~1.3.0",
+ "debug": "~4.3.1"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/source-map": {
+ "version": "0.5.7",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
+ "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
+ "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
+ "dev": true,
+ "peer": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/source-map-support": {
+ "version": "0.5.21",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+ "dev": true,
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "source-map": "^0.6.0"
+ }
+ },
+ "node_modules/source-map-support/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/spdx-correct": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz",
+ "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==",
+ "dev": true,
+ "dependencies": {
+ "spdx-expression-parse": "^3.0.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/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,
+ "dependencies": {
+ "spdx-exceptions": "^2.1.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "node_modules/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
+ },
+ "node_modules/sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
+ "dev": true
+ },
+ "node_modules/statuses": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
+ "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/stream-browserify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz",
+ "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==",
+ "dev": true,
+ "dependencies": {
+ "inherits": "~2.0.4",
+ "readable-stream": "^3.5.0"
+ }
+ },
+ "node_modules/stream-browserify/node_modules/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,
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/streamroller": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-2.2.4.tgz",
+ "integrity": "sha512-OG79qm3AujAM9ImoqgWEY1xG4HX+Lw+yY6qZj9R1K2mhF5bEmQ849wvrb+4vt4jLMLzwXttJlQbOdPOQVRv7DQ==",
+ "dev": true,
+ "dependencies": {
+ "date-format": "^2.1.0",
+ "debug": "^4.1.1",
+ "fs-extra": "^8.1.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/streamroller/node_modules/date-format": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-2.1.0.tgz",
+ "integrity": "sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA==",
+ "dev": true,
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/streamroller/node_modules/fs-extra": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
+ "dev": true,
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/string.prototype.trimend": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.3.tgz",
+ "integrity": "sha512-ayH0pB+uf0U28CtjlLvL7NaohvR1amUvVZk+y3DYb0Ey2PUV5zPkkKy9+U1ndVEIXO8hNg18eIv9Jntbii+dKw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "function-bind": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "function-bind": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/string.prototype.trimstart": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.3.tgz",
+ "integrity": "sha512-oBIBUy5lea5tt0ovtOFiEQaBkoBBkyJhZXzJYrSmDo5IUUqbOPvVezuRs/agBIdZ2p2Eo1FD6bD9USyBLfl3xg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "node_modules/strip-bom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
+ "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/strip-final-newline": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",
+ "dev": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/strip-json-comments": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/tapable": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz",
+ "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/terser": {
+ "version": "5.10.0",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.10.0.tgz",
+ "integrity": "sha512-AMmF99DMfEDiRJfxfY5jj5wNH/bYO09cniSqhfoyxc8sFoYIgkJy86G04UoZU5VjlpnplVu0K6Tx6E9b5+DlHA==",
+ "dev": true,
+ "dependencies": {
+ "commander": "^2.20.0",
+ "source-map": "~0.7.2",
+ "source-map-support": "~0.5.20"
+ },
+ "bin": {
+ "terser": "bin/terser"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/terser-webpack-plugin": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.0.tgz",
+ "integrity": "sha512-LPIisi3Ol4chwAaPP8toUJ3L4qCM1G0wao7L3qNv57Drezxj6+VEyySpPw4B1HSO2Eg/hDY/MNF5XihCAoqnsQ==",
+ "dev": true,
+ "dependencies": {
+ "jest-worker": "^27.4.1",
+ "schema-utils": "^3.1.1",
+ "serialize-javascript": "^6.0.0",
+ "source-map": "^0.6.1",
+ "terser": "^5.7.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/terser-webpack-plugin/node_modules/@types/json-schema": {
+ "version": "7.0.9",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz",
+ "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==",
+ "dev": true
+ },
+ "node_modules/terser-webpack-plugin/node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "node_modules/terser-webpack-plugin/node_modules/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
+ },
+ "node_modules/terser-webpack-plugin/node_modules/schema-utils": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz",
+ "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/terser-webpack-plugin/node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/terser/node_modules/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,
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/tmp": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz",
+ "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==",
+ "dev": true,
+ "dependencies": {
+ "rimraf": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8.17.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/toidentifier": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
+ "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/tv4": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tv4/-/tv4-1.3.0.tgz",
+ "integrity": "sha1-0CDIRvrdUMhVq7JeuuzGj8EPeWM=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "media-typer": "0.3.0",
+ "mime-types": "~2.1.24"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/ua-parser-js": {
+ "version": "0.7.31",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.31.tgz",
+ "integrity": "sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==",
+ "dev": true,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">= 4.0.0"
+ }
+ },
+ "node_modules/unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "node_modules/util": {
+ "version": "0.10.4",
+ "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz",
+ "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==",
+ "dev": true,
+ "dependencies": {
+ "inherits": "2.0.3"
+ }
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
+ "dev": true
+ },
+ "node_modules/util/node_modules/inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
+ "dev": true
+ },
+ "node_modules/utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/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,
+ "dependencies": {
+ "spdx-correct": "^3.0.0",
+ "spdx-expression-parse": "^3.0.0"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/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,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/watchpack": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.3.1.tgz",
+ "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==",
+ "dev": true,
+ "dependencies": {
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.1.2"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack": {
+ "version": "5.56.0",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.56.0.tgz",
+ "integrity": "sha512-pJ7esw2AGkpZL0jqsEAKnDEfRZdrc9NVjAWA+d1mFkwj68ng9VQ6+Wnrl+kS5dlDHvrat5ASK5vd7wp6I7f53Q==",
+ "dev": true,
+ "dependencies": {
+ "@types/eslint-scope": "^3.7.0",
+ "@types/estree": "^0.0.50",
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/wasm-edit": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1",
+ "acorn": "^8.4.1",
+ "acorn-import-assertions": "^1.7.6",
+ "browserslist": "^4.14.5",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^5.8.3",
+ "es-module-lexer": "^0.9.0",
+ "eslint-scope": "5.1.1",
+ "events": "^3.2.0",
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.2.4",
+ "json-parse-better-errors": "^1.0.2",
+ "loader-runner": "^4.2.0",
+ "mime-types": "^2.1.27",
+ "neo-async": "^2.6.2",
+ "schema-utils": "^3.1.0",
+ "tapable": "^2.1.1",
+ "terser-webpack-plugin": "^5.1.3",
+ "watchpack": "^2.2.0",
+ "webpack-sources": "^3.2.0"
+ },
+ "bin": {
+ "webpack": "bin/webpack.js"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack-cli": {
+ "version": "4.9.1",
+ "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.9.1.tgz",
+ "integrity": "sha512-JYRFVuyFpzDxMDB+v/nanUdQYcZtqFPGzmlW4s+UkPMFhSpfRNmf1z4AwYcHJVdvEFAM7FFCQdNTpsBYhDLusQ==",
+ "dev": true,
+ "dependencies": {
+ "@discoveryjs/json-ext": "^0.5.0",
+ "@webpack-cli/configtest": "^1.1.0",
+ "@webpack-cli/info": "^1.4.0",
+ "@webpack-cli/serve": "^1.6.0",
+ "colorette": "^2.0.14",
+ "commander": "^7.0.0",
+ "execa": "^5.0.0",
+ "fastest-levenshtein": "^1.0.12",
+ "import-local": "^3.0.2",
+ "interpret": "^2.2.0",
+ "rechoir": "^0.7.0",
+ "webpack-merge": "^5.7.3"
+ },
+ "bin": {
+ "webpack-cli": "bin/cli.js"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack-cli/node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/webpack-cli/node_modules/interpret": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz",
+ "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/webpack-cli/node_modules/rechoir": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz",
+ "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==",
+ "dev": true,
+ "dependencies": {
+ "resolve": "^1.9.0"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/webpack-cli/node_modules/webpack-merge": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz",
+ "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==",
+ "dev": true,
+ "dependencies": {
+ "clone-deep": "^4.0.1",
+ "wildcard": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/webpack-merge": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.2.2.tgz",
+ "integrity": "sha512-TUE1UGoTX2Cd42j3krGYqObZbOD+xF7u28WB7tfUordytSjbWTIjK/8V0amkBfTYN4/pB/GIDlJZZ657BGG19g==",
+ "dev": true,
+ "dependencies": {
+ "lodash": "^4.17.15"
+ }
+ },
+ "node_modules/webpack-sources": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.2.tgz",
+ "integrity": "sha512-cp5qdmHnu5T8wRg2G3vZZHoJPN14aqQ89SyQ11NpGH5zEMDCclt49rzo+MaRazk7/UeILhAI+/sEtcM+7Fr0nw==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack/node_modules/@types/json-schema": {
+ "version": "7.0.9",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz",
+ "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==",
+ "dev": true
+ },
+ "node_modules/webpack/node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "node_modules/webpack/node_modules/graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "dev": true
+ },
+ "node_modules/webpack/node_modules/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
+ },
+ "node_modules/webpack/node_modules/schema-utils": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz",
+ "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ }
+ },
+ "node_modules/which": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
+ "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
+ "dev": true,
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "which": "bin/which"
+ }
+ },
+ "node_modules/wildcard": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz",
+ "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==",
+ "dev": true
+ },
+ "node_modules/workerpool": {
+ "version": "6.1.5",
+ "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.5.tgz",
+ "integrity": "sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw==",
+ "dev": true
+ },
+ "node_modules/wrap-ansi": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "dev": true,
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
+ },
+ "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
+ "dev": true
+ },
+ "node_modules/ws": {
+ "version": "8.2.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz",
+ "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/yamljs": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz",
+ "integrity": "sha512-C/FsVVhht4iPQYXOInoxUM/1ELSf9EsgKH34FofQOp6hwCPrW4vG4w5++TED3xRUo8gD7l0P1J1dLlDYzODsTQ==",
+ "dev": true,
+ "dependencies": {
+ "argparse": "^1.0.7",
+ "glob": "^7.0.5"
+ },
+ "bin": {
+ "json2yaml": "bin/json2yaml",
+ "yaml2json": "bin/yaml2json"
+ }
+ },
+ "node_modules/yamscripts": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yamscripts/-/yamscripts-0.1.0.tgz",
+ "integrity": "sha512-i4ThS58KwsK83qSrrc8YZiBqgdl3WewWcWZ4fPdrh7A+qiRU9kXMcIKzngOC7VpJ2nTsWvHG6TcK3JHXpBxACA==",
+ "dev": true,
+ "dependencies": {
+ "colors": "^1.3.2",
+ "fs-extra": "^7.0.0",
+ "minimist": "^1.2.0",
+ "yamljs": "^0.3.0"
+ },
+ "bin": {
+ "yamscripts": "bin/yamscripts.js"
+ }
+ },
+ "node_modules/yargs": {
+ "version": "16.2.0",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz",
+ "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==",
+ "dev": true,
+ "dependencies": {
+ "cliui": "^7.0.2",
+ "escalade": "^3.1.1",
+ "get-caller-file": "^2.0.5",
+ "require-directory": "^2.1.1",
+ "string-width": "^4.2.0",
+ "y18n": "^5.0.5",
+ "yargs-parser": "^20.2.2"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yargs-parser": {
+ "version": "20.2.9",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
+ "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yargs-unparser": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz",
+ "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==",
+ "dev": true,
+ "dependencies": {
+ "camelcase": "^6.0.0",
+ "decamelize": "^4.0.0",
+ "flat": "^5.0.2",
+ "is-plain-obj": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yargs/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/yargs/node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/yargs/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/yargs/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/yargs/node_modules/y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yocto-queue": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ }
+ }
+ },
+ "dependencies": {
+ "@babel/code-frame": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.0.tgz",
+ "integrity": "sha512-IF4EOMEV+bfYwOmNxGzSnjR2EmQod7f1UXOpZM3l4i4o4QNwzjtJAu/HxdjHq0aYBvdqMuQEY1eg0nqW9ZPORA==",
+ "dev": true,
+ "requires": {
+ "@babel/highlight": "^7.16.0"
+ }
+ },
+ "@babel/compat-data": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.16.0.tgz",
+ "integrity": "sha512-DGjt2QZse5SGd9nfOSqO4WLJ8NN/oHkijbXbPrxuoJO3oIPJL3TciZs9FX+cOHNiY9E9l0opL8g7BmLe3T+9ew==",
+ "dev": true
+ },
+ "@babel/core": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.16.0.tgz",
+ "integrity": "sha512-mYZEvshBRHGsIAiyH5PzCFTCfbWfoYbO/jcSdXQSUQu1/pW0xDZAUP7KEc32heqWTAfAHhV9j1vH8Sav7l+JNQ==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/generator": "^7.16.0",
+ "@babel/helper-compilation-targets": "^7.16.0",
+ "@babel/helper-module-transforms": "^7.16.0",
+ "@babel/helpers": "^7.16.0",
+ "@babel/parser": "^7.16.0",
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0",
+ "convert-source-map": "^1.7.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.1.2",
+ "semver": "^6.3.0",
+ "source-map": "^0.5.0"
+ },
+ "dependencies": {
+ "semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/generator": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.0.tgz",
+ "integrity": "sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0",
+ "jsesc": "^2.5.1",
+ "source-map": "^0.5.0"
+ }
+ },
+ "@babel/helper-annotate-as-pure": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.0.tgz",
+ "integrity": "sha512-ItmYF9vR4zA8cByDocY05o0LGUkp1zhbTQOH1NFyl5xXEqlTJQCEJjieriw+aFpxo16swMxUnUiKS7a/r4vtHg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-compilation-targets": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.16.3.tgz",
+ "integrity": "sha512-vKsoSQAyBmxS35JUOOt+07cLc6Nk/2ljLIHwmq2/NM6hdioUaqEXq/S+nXvbvXbZkNDlWOymPanJGOc4CBjSJA==",
+ "dev": true,
+ "requires": {
+ "@babel/compat-data": "^7.16.0",
+ "@babel/helper-validator-option": "^7.14.5",
+ "browserslist": "^4.17.5",
+ "semver": "^6.3.0"
+ },
+ "dependencies": {
+ "semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/helper-create-class-features-plugin": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.16.0.tgz",
+ "integrity": "sha512-XLwWvqEaq19zFlF5PTgOod4bUA+XbkR4WLQBct1bkzmxJGB0ZEJaoKF4c8cgH9oBtCDuYJ8BP5NB9uFiEgO5QA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-function-name": "^7.16.0",
+ "@babel/helper-member-expression-to-functions": "^7.16.0",
+ "@babel/helper-optimise-call-expression": "^7.16.0",
+ "@babel/helper-replace-supers": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0"
+ }
+ },
+ "@babel/helper-function-name": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.0.tgz",
+ "integrity": "sha512-BZh4mEk1xi2h4HFjWUXRQX5AEx4rvaZxHgax9gcjdLWdkjsY7MKt5p0otjsg5noXw+pB+clMCjw+aEVYADMjog==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-get-function-arity": "^7.16.0",
+ "@babel/template": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-get-function-arity": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.0.tgz",
+ "integrity": "sha512-ASCquNcywC1NkYh/z7Cgp3w31YW8aojjYIlNg4VeJiHkqyP4AzIvr4qx7pYDb4/s8YcsZWqqOSxgkvjUz1kpDQ==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-hoist-variables": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.0.tgz",
+ "integrity": "sha512-1AZlpazjUR0EQZQv3sgRNfM9mEVWPK3M6vlalczA+EECcPz3XPh6VplbErL5UoMpChhSck5wAJHthlj1bYpcmg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-member-expression-to-functions": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.16.0.tgz",
+ "integrity": "sha512-bsjlBFPuWT6IWhl28EdrQ+gTvSvj5tqVP5Xeftp07SEuz5pLnsXZuDkDD3Rfcxy0IsHmbZ+7B2/9SHzxO0T+sQ==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-module-imports": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.16.0.tgz",
+ "integrity": "sha512-kkH7sWzKPq0xt3H1n+ghb4xEMP8k0U7XV3kkB+ZGy69kDk2ySFW1qPi06sjKzFY3t1j6XbJSqr4mF9L7CYVyhg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-module-transforms": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.16.0.tgz",
+ "integrity": "sha512-My4cr9ATcaBbmaEa8M0dZNA74cfI6gitvUAskgDtAFmAqyFKDSHQo5YstxPbN+lzHl2D9l/YOEFqb2mtUh4gfA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-module-imports": "^7.16.0",
+ "@babel/helper-replace-supers": "^7.16.0",
+ "@babel/helper-simple-access": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0",
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-optimise-call-expression": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.16.0.tgz",
+ "integrity": "sha512-SuI467Gi2V8fkofm2JPnZzB/SUuXoJA5zXe/xzyPP2M04686RzFKFHPK6HDVN6JvWBIEW8tt9hPR7fXdn2Lgpw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-plugin-utils": {
+ "version": "7.14.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.14.5.tgz",
+ "integrity": "sha512-/37qQCE3K0vvZKwoK4XU/irIJQdIfCJuhU5eKnNxpFDsOkgFaUAwbv+RYw6eYgsC0E4hS7r5KqGULUogqui0fQ==",
+ "dev": true
+ },
+ "@babel/helper-replace-supers": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.16.0.tgz",
+ "integrity": "sha512-TQxuQfSCdoha7cpRNJvfaYxxxzmbxXw/+6cS7V02eeDYyhxderSoMVALvwupA54/pZcOTtVeJ0xccp1nGWladA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-member-expression-to-functions": "^7.16.0",
+ "@babel/helper-optimise-call-expression": "^7.16.0",
+ "@babel/traverse": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-simple-access": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.16.0.tgz",
+ "integrity": "sha512-o1rjBT/gppAqKsYfUdfHq5Rk03lMQrkPHG1OWzHWpLgVXRH4HnMM9Et9CVdIqwkCQlobnGHEJMsgWP/jE1zUiw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-skip-transparent-expression-wrappers": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.16.0.tgz",
+ "integrity": "sha512-+il1gTy0oHwUsBQZyJvukbB4vPMdcYBrFHa0Uc4AizLxbq6BOYC51Rv4tWocX9BLBDLZ4kc6qUFpQ6HRgL+3zw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-split-export-declaration": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.0.tgz",
+ "integrity": "sha512-0YMMRpuDFNGTHNRiiqJX19GjNXA4H0E8jZ2ibccfSxaCogbm3am5WN/2nQNj0YnQwGWM1J06GOcQ2qnh3+0paw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/helper-validator-identifier": {
+ "version": "7.15.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz",
+ "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==",
+ "dev": true
+ },
+ "@babel/helper-validator-option": {
+ "version": "7.14.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.14.5.tgz",
+ "integrity": "sha512-OX8D5eeX4XwcroVW45NMvoYaIuFI+GQpA2a8Gi+X/U/cDUIRsV37qQfF905F0htTRCREQIB4KqPeaveRJUl3Ow==",
+ "dev": true
+ },
+ "@babel/helpers": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.16.3.tgz",
+ "integrity": "sha512-Xn8IhDlBPhvYTvgewPKawhADichOsbkZuzN7qz2BusOM0brChsyXMDJvldWaYMMUNiCQdQzNEioXTp3sC8Nt8w==",
+ "dev": true,
+ "requires": {
+ "@babel/template": "^7.16.0",
+ "@babel/traverse": "^7.16.3",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/highlight": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.0.tgz",
+ "integrity": "sha512-t8MH41kUQylBtu2+4IQA3atqevA2lRgqA2wyVB/YiWmsDSuylZZuXOUy9ric30hfzauEFfdsuk/eXTRrGrfd0g==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "chalk": "^2.0.0",
+ "js-tokens": "^4.0.0"
+ }
+ },
+ "@babel/parser": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.3.tgz",
+ "integrity": "sha512-dcNwU1O4sx57ClvLBVFbEgx0UZWfd0JQX5X6fxFRCLHelFBGXFfSz6Y0FAq2PEwUqlqLkdVjVr4VASEOuUnLJw==",
+ "dev": true
+ },
+ "@babel/plugin-proposal-class-properties": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.0.tgz",
+ "integrity": "sha512-mCF3HcuZSY9Fcx56Lbn+CGdT44ioBMMvjNVldpKtj8tpniETdLjnxdHI1+sDWXIM1nNt+EanJOZ3IG9lzVjs7A==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-create-class-features-plugin": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5"
+ }
+ },
+ "@babel/plugin-proposal-nullish-coalescing-operator": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.0.tgz",
+ "integrity": "sha512-3bnHA8CAFm7cG93v8loghDYyQ8r97Qydf63BeYiGgYbjKKB/XP53W15wfRC7dvKfoiJ34f6Rbyyx2btExc8XsQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3"
+ }
+ },
+ "@babel/plugin-proposal-optional-chaining": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.0.tgz",
+ "integrity": "sha512-Y4rFpkZODfHrVo70Uaj6cC1JJOt3Pp0MdWSwIKtb8z1/lsjl9AmnB7ErRFV+QNGIfcY1Eruc2UMx5KaRnXjMyg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0",
+ "@babel/plugin-syntax-optional-chaining": "^7.8.3"
+ }
+ },
+ "@babel/plugin-syntax-jsx": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.16.0.tgz",
+ "integrity": "sha512-8zv2+xiPHwly31RK4RmnEYY5zziuF3O7W2kIDW+07ewWDh6Oi0dRq8kwvulRkFgt6DB97RlKs5c1y068iPlCUg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.14.5"
+ }
+ },
+ "@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.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.16.0.tgz",
+ "integrity": "sha512-FJFdJAqaCpndL+pIf0aeD/qlQwT7QXOvR6Cc8JPvNhKJBi2zc/DPc4g05Y3fbD/0iWAMQFGij4+Xw+4L/BMpTg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.14.5"
+ }
+ },
+ "@babel/plugin-transform-react-jsx": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.16.0.tgz",
+ "integrity": "sha512-rqDgIbukZ44pqq7NIRPGPGNklshPkvlmvqjdx3OZcGPk4zGIenYkxDTvl3LsSL8gqcc3ZzGmXPE6hR/u/voNOw==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-module-imports": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/plugin-syntax-jsx": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/plugin-transform-react-jsx-development": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.16.0.tgz",
+ "integrity": "sha512-qq65iSqBRq0Hr3wq57YG2AmW0H6wgTnIzpffTphrUWUgLCOK+zf1f7G0vuOiXrp7dU1qq+fQBoqZ3wCDAkhFzw==",
+ "dev": true,
+ "requires": {
+ "@babel/plugin-transform-react-jsx": "^7.16.0"
+ }
+ },
+ "@babel/plugin-transform-react-pure-annotations": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.16.0.tgz",
+ "integrity": "sha512-NC/Bj2MG+t8Ef5Pdpo34Ay74X4Rt804h5y81PwOpfPtmAK3i6CizmQqwyBQzIepz1Yt8wNr2Z2L7Lu3qBMfZMA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-annotate-as-pure": "^7.16.0",
+ "@babel/helper-plugin-utils": "^7.14.5"
+ }
+ },
+ "@babel/preset-react": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.16.0.tgz",
+ "integrity": "sha512-d31IFW2bLRB28uL1WoElyro8RH5l6531XfxMtCeCmp6RVAF1uTfxxUA0LH1tXl+psZdwfmIbwoG4U5VwgbhtLw==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.14.5",
+ "@babel/helper-validator-option": "^7.14.5",
+ "@babel/plugin-transform-react-display-name": "^7.16.0",
+ "@babel/plugin-transform-react-jsx": "^7.16.0",
+ "@babel/plugin-transform-react-jsx-development": "^7.16.0",
+ "@babel/plugin-transform-react-pure-annotations": "^7.16.0"
+ }
+ },
+ "@babel/runtime": {
+ "version": "7.14.8",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.14.8.tgz",
+ "integrity": "sha512-twj3L8Og5SaCRCErB4x4ajbvBIVV77CGeFglHpeg5WC5FF8TZzBWXtTJ4MqaD9QszLYTtr+IsaAL2rEUevb+eg==",
+ "requires": {
+ "regenerator-runtime": "^0.13.4"
+ }
+ },
+ "@babel/template": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.0.tgz",
+ "integrity": "sha512-MnZdpFD/ZdYhXwiunMqqgyZyucaYsbL0IrjoGjaVhGilz+x8YB++kRfygSOIj1yOtWKPlx7NBp+9I1RQSgsd5A==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/parser": "^7.16.0",
+ "@babel/types": "^7.16.0"
+ }
+ },
+ "@babel/traverse": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.3.tgz",
+ "integrity": "sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.16.0",
+ "@babel/generator": "^7.16.0",
+ "@babel/helper-function-name": "^7.16.0",
+ "@babel/helper-hoist-variables": "^7.16.0",
+ "@babel/helper-split-export-declaration": "^7.16.0",
+ "@babel/parser": "^7.16.3",
+ "@babel/types": "^7.16.0",
+ "debug": "^4.1.0",
+ "globals": "^11.1.0"
+ }
+ },
+ "@babel/types": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.16.0.tgz",
+ "integrity": "sha512-PJgg/k3SdLsGb3hhisFvtLOw5ts113klrpLuIPtCJIU+BB24fqq6lf8RWqKJEjzqXR9AEH1rIb5XTqwBHB+kQg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.15.7",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "@discoveryjs/json-ext": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.6.tgz",
+ "integrity": "sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==",
+ "dev": true
+ },
+ "@fluent/bundle": {
+ "version": "0.17.1",
+ "resolved": "https://registry.npmjs.org/@fluent/bundle/-/bundle-0.17.1.tgz",
+ "integrity": "sha512-CRFNT9QcSFAeFDneTF59eyv3JXFGhIIN4boUO2y22YmsuuKLyDk+N1I/NQUYz9Ab63e6V7T6vItoZIG/2oOOuw=="
+ },
+ "@fluent/react": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@fluent/react/-/react-0.15.0.tgz",
+ "integrity": "sha512-qUMfaHman+UciOELQc5hnFAv0VerUR6+9gEBCRk9RR66XS13syt91ZElNOTHWe2Ofv70cxAGaJ5Yff4MRPg5Ow==",
+ "requires": {
+ "@fluent/sequence": "^0.8.0",
+ "cached-iterable": "^0.3.0"
+ },
+ "dependencies": {
+ "cached-iterable": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/cached-iterable/-/cached-iterable-0.3.0.tgz",
+ "integrity": "sha512-MDqM6TpBVebZD4UDtmlFp8EjVtRcsB6xt9aRdWymjk0fWVUUGgmt/V7o0H0gkI2Tkvv8B0ucjidZm4mLosdlWw=="
+ }
+ }
+ },
+ "@fluent/sequence": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/@fluent/sequence/-/sequence-0.8.0.tgz",
+ "integrity": "sha512-eV5QlEEVV/wR3AFQLXO67x4yPRPQXyqke0c8yucyMSeW36B3ecZyVFlY1UprzrfFV8iPJB4TAehDy/dLGbvQ1Q==",
+ "requires": {}
+ },
+ "@istanbuljs/schema": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz",
+ "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==",
+ "dev": true
+ },
+ "@jsdevtools/coverage-istanbul-loader": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@jsdevtools/coverage-istanbul-loader/-/coverage-istanbul-loader-3.0.5.tgz",
+ "integrity": "sha512-EUCPEkaRPvmHjWAAZkWMT7JDzpw7FKB00WTISaiXsbNOd5hCHg77XLA8sLYLFDo1zepYLo2w7GstN8YBqRXZfA==",
+ "dev": true,
+ "requires": {
+ "convert-source-map": "^1.7.0",
+ "istanbul-lib-instrument": "^4.0.3",
+ "loader-utils": "^2.0.0",
+ "merge-source-map": "^1.1.0",
+ "schema-utils": "^2.7.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "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"
+ }
+ },
+ "istanbul-lib-coverage": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz",
+ "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==",
+ "dev": true
+ },
+ "istanbul-lib-instrument": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz",
+ "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==",
+ "dev": true,
+ "requires": {
+ "@babel/core": "^7.7.5",
+ "@istanbuljs/schema": "^0.1.2",
+ "istanbul-lib-coverage": "^3.0.0",
+ "semver": "^6.3.0"
+ }
+ },
+ "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
+ },
+ "loader-utils": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz",
+ "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==",
+ "dev": true,
+ "requires": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^2.1.2"
+ }
+ },
+ "schema-utils": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz",
+ "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.5",
+ "ajv": "^6.12.4",
+ "ajv-keywords": "^3.5.2"
+ }
+ },
+ "semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true
+ }
+ }
+ },
+ "@sinonjs/commons": {
+ "version": "1.8.3",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz",
+ "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==",
+ "dev": true,
+ "requires": {
+ "type-detect": "4.0.8"
+ }
+ },
+ "@sinonjs/fake-timers": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-8.1.0.tgz",
+ "integrity": "sha512-OAPJUAtgeINhh/TAlUID4QTs53Njm7xzddaVlEs/SXwgtiD1tW22zAB/W1wdqfrpmikgaWQ9Fw6Ws+hsiRm5Vg==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.7.0"
+ }
+ },
+ "@sinonjs/samsam": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.0.2.tgz",
+ "integrity": "sha512-jxPRPp9n93ci7b8hMfJOFDPRLFYadN6FSpeROFTR4UNF4i5b+EK6m4QXPO46BDhFgRy1JuS87zAnFOzCUwMJcQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.6.0",
+ "lodash.get": "^4.4.2",
+ "type-detect": "^4.0.8"
+ }
+ },
+ "@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/component-emitter": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz",
+ "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==",
+ "dev": true
+ },
+ "@types/cookie": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz",
+ "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==",
+ "dev": true
+ },
+ "@types/cors": {
+ "version": "2.8.12",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz",
+ "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==",
+ "dev": true
+ },
+ "@types/eslint": {
+ "version": "8.2.1",
+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.2.1.tgz",
+ "integrity": "sha512-UP9rzNn/XyGwb5RQ2fok+DzcIRIYwc16qTXse5+Smsy8MOIccCChT15KAwnsgQx4PzJkaMq4myFyZ4CL5TjhIQ==",
+ "dev": true,
+ "requires": {
+ "@types/estree": "*",
+ "@types/json-schema": "*"
+ }
+ },
+ "@types/eslint-scope": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.2.tgz",
+ "integrity": "sha512-TzgYCWoPiTeRg6RQYgtuW7iODtVoKu3RVL72k3WohqhjfaOLK5Mg2T4Tg1o2bSfu0vPkoI48wdQFv5b/Xe04wQ==",
+ "dev": true,
+ "requires": {
+ "@types/eslint": "*",
+ "@types/estree": "*"
+ }
+ },
+ "@types/estree": {
+ "version": "0.0.50",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.50.tgz",
+ "integrity": "sha512-C6N5s2ZFtuZRj54k2/zyRhNDjJwwcViAM3Nbm8zjBpbqAdZ00mr0CFxvSKeO8Y/e03WVFLpQMdHYVfUd6SB+Hw==",
+ "dev": true
+ },
+ "@types/hoist-non-react-statics": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
+ "integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
+ "requires": {
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0"
+ }
+ },
+ "@types/json-schema": {
+ "version": "7.0.7",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz",
+ "integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA==",
+ "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
+ },
+ "@types/prop-types": {
+ "version": "15.7.4",
+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.4.tgz",
+ "integrity": "sha512-rZ5drC/jWjrArrS8BR6SIr4cWpW09RNTYt9AMZo3Jwwif+iacXAqgVjm0B0Bv/S1jhDXKHqRVNCbACkJ89RAnQ=="
+ },
+ "@types/react": {
+ "version": "17.0.34",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-17.0.34.tgz",
+ "integrity": "sha512-46FEGrMjc2+8XhHXILr+3+/sTe3OfzSPU9YGKILLrUYbQ1CLQC9Daqo1KzENGXAWwrFwiY0l4ZbF20gRvgpWTg==",
+ "requires": {
+ "@types/prop-types": "*",
+ "@types/scheduler": "*",
+ "csstype": "^3.0.2"
+ }
+ },
+ "@types/react-redux": {
+ "version": "7.1.20",
+ "resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.20.tgz",
+ "integrity": "sha512-q42es4c8iIeTgcnB+yJgRTTzftv3eYYvCZOh1Ckn2eX/3o5TdsQYKUWpLoLuGlcY/p+VAhV9IOEZJcWk/vfkXw==",
+ "requires": {
+ "@types/hoist-non-react-statics": "^3.3.0",
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0",
+ "redux": "^4.0.0"
+ }
+ },
+ "@types/scheduler": {
+ "version": "0.16.2",
+ "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
+ "integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
+ },
+ "@ungap/promise-all-settled": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz",
+ "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==",
+ "dev": true
+ },
+ "@webassemblyjs/ast": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz",
+ "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/helper-numbers": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1"
+ }
+ },
+ "@webassemblyjs/floating-point-hex-parser": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz",
+ "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-api-error": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz",
+ "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-buffer": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz",
+ "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-numbers": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz",
+ "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/floating-point-hex-parser": "1.11.1",
+ "@webassemblyjs/helper-api-error": "1.11.1",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/helper-wasm-bytecode": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz",
+ "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-wasm-section": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz",
+ "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1"
+ }
+ },
+ "@webassemblyjs/ieee754": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz",
+ "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==",
+ "dev": true,
+ "requires": {
+ "@xtuc/ieee754": "^1.2.0"
+ }
+ },
+ "@webassemblyjs/leb128": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.1.tgz",
+ "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==",
+ "dev": true,
+ "requires": {
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/utf8": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.1.tgz",
+ "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==",
+ "dev": true
+ },
+ "@webassemblyjs/wasm-edit": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz",
+ "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/helper-wasm-section": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1",
+ "@webassemblyjs/wasm-opt": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1",
+ "@webassemblyjs/wast-printer": "1.11.1"
+ }
+ },
+ "@webassemblyjs/wasm-gen": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz",
+ "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/ieee754": "1.11.1",
+ "@webassemblyjs/leb128": "1.11.1",
+ "@webassemblyjs/utf8": "1.11.1"
+ }
+ },
+ "@webassemblyjs/wasm-opt": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz",
+ "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-buffer": "1.11.1",
+ "@webassemblyjs/wasm-gen": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1"
+ }
+ },
+ "@webassemblyjs/wasm-parser": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz",
+ "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/helper-api-error": "1.11.1",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.1",
+ "@webassemblyjs/ieee754": "1.11.1",
+ "@webassemblyjs/leb128": "1.11.1",
+ "@webassemblyjs/utf8": "1.11.1"
+ }
+ },
+ "@webassemblyjs/wast-printer": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz",
+ "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.1",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webpack-cli/configtest": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.1.0.tgz",
+ "integrity": "sha512-ttOkEkoalEHa7RaFYpM0ErK1xc4twg3Am9hfHhL7MVqlHebnkYd2wuI/ZqTDj0cVzZho6PdinY0phFZV3O0Mzg==",
+ "dev": true
+ },
+ "@webpack-cli/info": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.4.0.tgz",
+ "integrity": "sha512-F6b+Man0rwE4n0409FyAJHStYA5OIZERxmnUfLVwv0mc0V1wLad3V7jqRlMkgKBeAq07jUvglacNaa6g9lOpuw==",
+ "dev": true,
+ "requires": {
+ "envinfo": "^7.7.3"
+ }
+ },
+ "@webpack-cli/serve": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.6.0.tgz",
+ "integrity": "sha512-ZkVeqEmRpBV2GHvjjUZqEai2PpUbuq8Bqd//vEYsp63J8WyexI8ppCqVS3Zs0QADf6aWuPdU+0XsPI647PVlQA==",
+ "dev": true
+ },
+ "@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
+ },
+ "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": "8.5.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.5.0.tgz",
+ "integrity": "sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==",
+ "dev": true
+ },
+ "acorn-import-assertions": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz",
+ "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==",
+ "dev": true
+ },
+ "airbnb-prop-types": {
+ "version": "2.16.0",
+ "resolved": "https://registry.npmjs.org/airbnb-prop-types/-/airbnb-prop-types-2.16.0.tgz",
+ "integrity": "sha512-7WHOFolP/6cS96PhKNrslCLMYAI8yB1Pp6u6XmxozQOiZbsI5ycglZr5cHhBFfuRcQQjzCMith5ZPZdYiJCxUg==",
+ "dev": true,
+ "requires": {
+ "array.prototype.find": "^2.1.1",
+ "function.prototype.name": "^1.1.2",
+ "is-regex": "^1.1.0",
+ "object-is": "^1.1.2",
+ "object.assign": "^4.1.0",
+ "object.entries": "^1.1.2",
+ "prop-types": "^15.7.2",
+ "prop-types-exact": "^1.2.0",
+ "react-is": "^16.13.1"
+ },
+ "dependencies": {
+ "es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ },
+ "dependencies": {
+ "object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ }
+ }
+ }
+ },
+ "is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true
+ },
+ "is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "object-is": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.4.tgz",
+ "integrity": "sha512-1ZvAZ4wlF7IyPVOcE1Omikt7UpaFlOQq0HlSti+ZvDH3UiD2brwGMwDbyV43jao2bKJ+4+WdPJHSd7kgzKYVqg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "object.entries": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.3.tgz",
+ "integrity": "sha512-ym7h7OZebNS96hn5IJeyUmaWhaSM4SVtAPPfNLQEI2MYWCO2egsITb9nab2+i/Pwibx+R0mtn+ltKJXRSeTMGg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ }
+ },
+ "react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true
+ }
+ }
+ },
+ "ajv-keywords": {
+ "version": "3.5.2",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
+ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
+ "dev": true
+ },
+ "ansi-colors": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz",
+ "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==",
+ "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": "3.1.2",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz",
+ "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==",
+ "dev": true,
+ "requires": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ }
+ },
+ "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"
+ }
+ },
+ "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.prototype.find": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/array.prototype.find/-/array.prototype.find-2.1.1.tgz",
+ "integrity": "sha512-mi+MYNJYLTx2eNYy+Yh6raoQacCsNeeMUaspFPh9Y141lFSsWxxB8V9mM2ye+eqiRs917J6/pJ4M9ZPzenWckA==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.4"
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "babel-loader": {
+ "version": "8.2.3",
+ "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.2.3.tgz",
+ "integrity": "sha512-n4Zeta8NC3QAsuyiizu0GkmRcQ6clkV9WFUnUf1iXP//IeSKbWjofW3UHyZVwlOB4y039YQKefawyTn64Zwbuw==",
+ "dev": true,
+ "requires": {
+ "find-cache-dir": "^3.3.1",
+ "loader-utils": "^1.4.0",
+ "make-dir": "^3.1.0",
+ "schema-utils": "^2.6.5"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "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"
+ }
+ },
+ "find-cache-dir": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz",
+ "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==",
+ "dev": true,
+ "requires": {
+ "commondir": "^1.0.1",
+ "make-dir": "^3.0.2",
+ "pkg-dir": "^4.1.0"
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "loader-utils": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz",
+ "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==",
+ "dev": true,
+ "requires": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^1.0.1"
+ }
+ },
+ "make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "dev": true,
+ "requires": {
+ "semver": "^6.0.0"
+ }
+ },
+ "pkg-dir": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
+ "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
+ "dev": true,
+ "requires": {
+ "find-up": "^4.0.0"
+ }
+ },
+ "schema-utils": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz",
+ "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.5",
+ "ajv": "^6.12.4",
+ "ajv-keywords": "^3.5.2"
+ }
+ },
+ "semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "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
+ },
+ "balanced-match": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
+ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
+ "dev": true
+ },
+ "base64-arraybuffer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.1.tgz",
+ "integrity": "sha512-vFIUq7FdLtjZMhATwDul5RZWv2jpXQ09Pd6jcVEOvIsqCWTRFD/ONHNfyOS8dA/Ippi5dsIgpyKWKZaAKZltbA==",
+ "dev": true
+ },
+ "base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "dev": true
+ },
+ "base64id": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
+ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
+ "dev": true
+ },
+ "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
+ },
+ "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": "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"
+ }
+ },
+ "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
+ },
+ "browserslist": {
+ "version": "4.17.6",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.17.6.tgz",
+ "integrity": "sha512-uPgz3vyRTlEiCv4ee9KlsKgo2V6qPk7Jsn0KAn2OBqbqKo3iNcPEC1Ti6J4dwnz+aIRfEEEuOzC9IBk8tXUomw==",
+ "dev": true,
+ "requires": {
+ "caniuse-lite": "^1.0.30001274",
+ "electron-to-chromium": "^1.3.886",
+ "escalade": "^3.1.1",
+ "node-releases": "^2.0.1",
+ "picocolors": "^1.0.0"
+ }
+ },
+ "buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "dev": true,
+ "requires": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "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
+ },
+ "bytes": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
+ "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==",
+ "dev": true
+ },
+ "call-bind": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
+ "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2"
+ }
+ },
+ "camelcase": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz",
+ "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==",
+ "dev": true
+ },
+ "caniuse-lite": {
+ "version": "1.0.30001425",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001425.tgz",
+ "integrity": "sha512-/pzFv0OmNG6W0ym80P3NtapU0QEiDS3VuYAZMGoLLqiC7f6FJFe1MjpQDREGApeenD9wloeytmVDj+JLXPC6qw==",
+ "dev": true
+ },
+ "chai": {
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz",
+ "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==",
+ "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.1",
+ "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": "3.5.2",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz",
+ "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==",
+ "dev": true,
+ "requires": {
+ "anymatch": "~3.1.2",
+ "braces": "~3.0.2",
+ "fsevents": "~2.3.2",
+ "glob-parent": "~5.1.2",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.6.0"
+ },
+ "dependencies": {
+ "binary-extensions": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
+ "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==",
+ "dev": true
+ },
+ "fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "optional": true
+ },
+ "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"
+ }
+ },
+ "readdirp": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
+ "dev": true,
+ "requires": {
+ "picomatch": "^2.2.1"
+ }
+ }
+ }
+ },
+ "chrome-trace-event": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz",
+ "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==",
+ "dev": true
+ },
+ "cliui": {
+ "version": "7.0.4",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz",
+ "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==",
+ "dev": true,
+ "requires": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^7.0.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ }
+ },
+ "strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^5.0.1"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "colorette": {
+ "version": "2.0.16",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz",
+ "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==",
+ "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
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ }
+ }
+ },
+ "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.4.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.1.tgz",
+ "integrity": "sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==",
+ "dev": true
+ },
+ "cors": {
+ "version": "2.8.5",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4",
+ "vary": "^1"
+ }
+ },
+ "cross-spawn": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
+ "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
+ "dev": true,
+ "requires": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "dependencies": {
+ "path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true
+ },
+ "shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "requires": {
+ "shebang-regex": "^3.0.0"
+ }
+ },
+ "shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true
+ },
+ "which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "requires": {
+ "isexe": "^2.0.0"
+ }
+ }
+ }
+ },
+ "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": "3.0.8",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.8.tgz",
+ "integrity": "sha512-jXKhWqXPmlUeoQnF/EhTtTl4C9SnrxSH/jZUih3jmO6lBKr99rP3/+FmrMj4EFpOXzMtXHAZkd3x0E6h6Fgflw=="
+ },
+ "custom-event": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz",
+ "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=",
+ "dev": true
+ },
+ "date-format": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-3.0.0.tgz",
+ "integrity": "sha512-eyTcpKOcamdhWJXj56DpQMo1ylSQpcGtGKXcU0Tb97+K56/CF5amAqqqNj0+KvA0iw2ynxtHWFsPDSClCxe48w==",
+ "dev": true
+ },
+ "debug": {
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
+ "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
+ "dev": true,
+ "requires": {
+ "ms": "2.1.2"
+ }
+ },
+ "decamelize": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz",
+ "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==",
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "depd": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
+ "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=",
+ "dev": true
+ },
+ "di": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz",
+ "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=",
+ "dev": true
+ },
+ "diff": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz",
+ "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==",
+ "dev": true
+ },
+ "discontinuous-range": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
+ "integrity": "sha1-44Mx8IRLukm5qctxx3FYWqsbxlo=",
+ "dev": true
+ },
+ "dom-helpers": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
+ "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
+ "requires": {
+ "@babel/runtime": "^7.8.7",
+ "csstype": "^3.0.2"
+ }
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=",
+ "dev": true
+ },
+ "electron-to-chromium": {
+ "version": "1.3.894",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.894.tgz",
+ "integrity": "sha512-WY8pA4irAZ4cm/Pr7YFPtPLVqj3nU6d0SbfoHF6M7HZNONfPdAnYAarumqQ75go2LuN72uO9wGuCEqnfya/ytg==",
+ "dev": true
+ },
+ "emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true
+ },
+ "emojis-list": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz",
+ "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==",
+ "dev": true
+ },
+ "encodeurl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
+ "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=",
+ "dev": true
+ },
+ "engine.io": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.0.1.tgz",
+ "integrity": "sha512-Y53UaciUh2Rmx5MiogtMxOQcfh7pnemday+Bb4QDg0Wjmnvo/VTvuEyNGQgYmh8L7VOe8Je1QuiqjLNDelMqLA==",
+ "dev": true,
+ "requires": {
+ "@types/cookie": "^0.4.1",
+ "@types/cors": "^2.8.12",
+ "@types/node": ">=10.0.0",
+ "accepts": "~1.3.4",
+ "base64id": "2.0.0",
+ "cookie": "~0.4.1",
+ "cors": "~2.8.5",
+ "debug": "~4.3.1",
+ "engine.io-parser": "~5.0.0",
+ "ws": "~8.2.3"
+ }
+ },
+ "engine.io-parser": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.1.tgz",
+ "integrity": "sha512-j4p3WwJrG2k92VISM0op7wiq60vO92MlF3CRGxhKHy9ywG1/Dkc72g0dXeDQ+//hrcDn8gqQzoEkdO9FN0d9AA==",
+ "dev": true,
+ "requires": {
+ "base64-arraybuffer": "~1.0.1"
+ }
+ },
+ "enhanced-resolve": {
+ "version": "5.8.3",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.8.3.tgz",
+ "integrity": "sha512-EGAbGvH7j7Xt2nc0E7D99La1OiEs8LnyimkRgwExpUMScN6O+3x9tIWs7PLQZVNx4YD+00skHXPXi1yQHpAmZA==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.2.0"
+ },
+ "dependencies": {
+ "graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "dev": true
+ }
+ }
+ },
+ "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
+ },
+ "envinfo": {
+ "version": "7.8.1",
+ "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.8.1.tgz",
+ "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==",
+ "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.6",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-react-16/-/enzyme-adapter-react-16-1.15.6.tgz",
+ "integrity": "sha512-yFlVJCXh8T+mcQo8M6my9sPgeGzj85HSHi6Apgf1Cvq/7EL/J9+1JoJmJsRxZgyTvPMAqOEpRSu/Ii/ZpyOk0g==",
+ "dev": true,
+ "requires": {
+ "enzyme-adapter-utils": "^1.14.0",
+ "enzyme-shallow-equal": "^1.0.4",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.2",
+ "object.values": "^1.1.2",
+ "prop-types": "^15.7.2",
+ "react-is": "^16.13.1",
+ "react-test-renderer": "^16.0.0-0",
+ "semver": "^5.7.0"
+ },
+ "dependencies": {
+ "enzyme-shallow-equal": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/enzyme-shallow-equal/-/enzyme-shallow-equal-1.0.4.tgz",
+ "integrity": "sha512-MttIwB8kKxypwHvRynuC3ahyNc+cFbR8mjVIltnmzQ0uKGqmsfO4bfBuLxb0beLNPhjblUEYvEbsg+VSygvF1Q==",
+ "dev": true,
+ "requires": {
+ "has": "^1.0.3",
+ "object-is": "^1.1.2"
+ }
+ },
+ "es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ }
+ },
+ "is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true
+ },
+ "is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "object-is": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.4.tgz",
+ "integrity": "sha512-1ZvAZ4wlF7IyPVOcE1Omikt7UpaFlOQq0HlSti+ZvDH3UiD2brwGMwDbyV43jao2bKJ+4+WdPJHSd7kgzKYVqg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ }
+ },
+ "object.values": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.2.tgz",
+ "integrity": "sha512-MYC0jvJopr8EK6dPBiO8Nb9mvjdypOachO5REGk6MXzujbBrAisKo3HmdEI6kZDL6fC31Mwee/5YbtMebixeag==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ }
+ },
+ "react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true
+ },
+ "react-test-renderer": {
+ "version": "16.14.0",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-16.14.0.tgz",
+ "integrity": "sha512-L8yPjqPE5CZO6rKsKXRO/rVPiaCOy0tQQJbC+UjPNlobl5mad59lvPjwFsQHTvL03caVDIVr9x9/OSgDe6I5Eg==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2",
+ "react-is": "^16.8.6",
+ "scheduler": "^0.19.1"
+ }
+ },
+ "scheduler": {
+ "version": "0.19.1",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
+ "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
+ "dev": true,
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ }
+ }
+ },
+ "enzyme-adapter-utils": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-utils/-/enzyme-adapter-utils-1.14.0.tgz",
+ "integrity": "sha512-F/z/7SeLt+reKFcb7597IThpDp0bmzcH1E9Oabqv+o01cID2/YInlqHbFl7HzWBl4h3OdZYedtwNDOmSKkk0bg==",
+ "dev": true,
+ "requires": {
+ "airbnb-prop-types": "^2.16.0",
+ "function.prototype.name": "^1.1.3",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.2",
+ "object.fromentries": "^2.0.3",
+ "prop-types": "^15.7.2",
+ "semver": "^5.7.1"
+ },
+ "dependencies": {
+ "es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ }
+ },
+ "function.prototype.name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.3.tgz",
+ "integrity": "sha512-H51qkbNSp8mtkJt+nyW1gyStBiKZxfRqySNUR99ylq6BPXHKI4SEvIlTKp4odLfjRKJV04DFWMU3G/YRlQOsag==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "functions-have-names": "^1.2.1"
+ }
+ },
+ "is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true
+ },
+ "is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.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"
+ }
+ },
+ "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-module-lexer": {
+ "version": "0.9.3",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-0.9.3.tgz",
+ "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "escalade": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",
+ "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==",
+ "dev": true
+ },
+ "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
+ },
+ "eslint-scope": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
+ "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",
+ "dev": true,
+ "requires": {
+ "esrecurse": "^4.3.0",
+ "estraverse": "^4.1.1"
+ },
+ "dependencies": {
+ "esrecurse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
+ "dev": true,
+ "requires": {
+ "estraverse": "^5.2.0"
+ },
+ "dependencies": {
+ "estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "dev": true
+ }
+ }
+ }
+ }
+ },
+ "estraverse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",
+ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
+ "dev": true
+ },
+ "eventemitter3": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
+ "dev": true
+ },
+ "events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "dev": true
+ },
+ "execa": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",
+ "dev": true,
+ "requires": {
+ "cross-spawn": "^7.0.3",
+ "get-stream": "^6.0.0",
+ "human-signals": "^2.1.0",
+ "is-stream": "^2.0.0",
+ "merge-stream": "^2.0.0",
+ "npm-run-path": "^4.0.1",
+ "onetime": "^5.1.2",
+ "signal-exit": "^3.0.3",
+ "strip-final-newline": "^2.0.0"
+ },
+ "dependencies": {
+ "onetime": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
+ "dev": true,
+ "requires": {
+ "mimic-fn": "^2.1.0"
+ }
+ }
+ }
+ },
+ "extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "dev": true
+ },
+ "fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "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
+ },
+ "fastest-levenshtein": {
+ "version": "1.0.16",
+ "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz",
+ "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==",
+ "dev": true
+ },
+ "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"
+ },
+ "dependencies": {
+ "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"
+ }
+ }
+ }
+ },
+ "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-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
+ "dev": true,
+ "requires": {
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
+ }
+ },
+ "flat": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz",
+ "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==",
+ "dev": true
+ },
+ "flatted": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz",
+ "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==",
+ "dev": true
+ },
+ "follow-redirects": {
+ "version": "1.14.5",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.5.tgz",
+ "integrity": "sha512-wtphSXy7d4/OR+MvIFbCVBDzZ5520qV8XfPklSN5QtxuMUJZ+b0Wnst1e1lCDocfzuCkHqj8k0FpZqO+UIaKNA==",
+ "dev": true
+ },
+ "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.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
+ "dev": true
+ },
+ "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
+ },
+ "gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "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-intrinsic": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
+ "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "get-stream": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
+ "dev": true
+ },
+ "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-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "dev": true,
+ "requires": {
+ "is-glob": "^4.0.1"
+ }
+ },
+ "glob-to-regexp": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
+ "dev": true
+ },
+ "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
+ },
+ "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
+ },
+ "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-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
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "hosted-git-info": {
+ "version": "2.8.9",
+ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz",
+ "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==",
+ "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.2",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
+ "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.1",
+ "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz",
+ "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==",
+ "dev": true,
+ "requires": {
+ "eventemitter3": "^4.0.0",
+ "follow-redirects": "^1.0.0",
+ "requires-port": "^1.0.0"
+ }
+ },
+ "human-signals": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",
+ "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.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "dev": true
+ },
+ "import-local": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.0.3.tgz",
+ "integrity": "sha512-bE9iaUY3CXH8Cwfan/abDKAxe1KGT9kyGsBPqf6DMK/z0a2OzAsrukeYNgIH6cH5Xr452jb1TUL8rSfCLjZ9uA==",
+ "dev": true,
+ "requires": {
+ "pkg-dir": "^4.2.0",
+ "resolve-cwd": "^3.0.0"
+ },
+ "dependencies": {
+ "pkg-dir": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
+ "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
+ "dev": true,
+ "requires": {
+ "find-up": "^4.0.0"
+ }
+ }
+ }
+ },
+ "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
+ },
+ "interpret": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz",
+ "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==",
+ "dev": true
+ },
+ "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-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-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-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-docker": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
+ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
+ "dev": true
+ },
+ "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.3",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-negative-zero": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz",
+ "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==",
+ "dev": true
+ },
+ "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
+ },
+ "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-obj": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz",
+ "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==",
+ "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"
+ }
+ },
+ "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-stream": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
+ "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-unicode-supported": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
+ "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==",
+ "dev": true
+ },
+ "is-wsl": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
+ "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
+ "dev": true,
+ "requires": {
+ "is-docker": "^2.0.0"
+ }
+ },
+ "isbinaryfile": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.8.tgz",
+ "integrity": "sha512-53h6XFniq77YdW+spoRrebh0mnmTxRPTlcuIArO57lmMdq4uBKFKaeTjnb92oYWrSn/LVL+LT+Hap2tFQj8V+w==",
+ "dev": true
+ },
+ "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": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "istanbul-lib-report": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz",
+ "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==",
+ "dev": true,
+ "requires": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^3.0.0",
+ "supports-color": "^7.1.0"
+ },
+ "dependencies": {
+ "has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true
+ },
+ "istanbul-lib-coverage": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz",
+ "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==",
+ "dev": true
+ },
+ "make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "dev": true,
+ "requires": {
+ "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
+ },
+ "supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^4.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": "3.0.2",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.2.tgz",
+ "integrity": "sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw==",
+ "dev": true,
+ "requires": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ }
+ },
+ "jest-worker": {
+ "version": "27.4.5",
+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.4.5.tgz",
+ "integrity": "sha512-f2s8kEdy15cv9r7q4KkzGXvlY0JTcmCbMHZBfSQDwW77REr45IDWwd0lksDFeVHH2jJ5pqb90T77XscrjeGzzg==",
+ "dev": true,
+ "requires": {
+ "@types/node": "*",
+ "merge-stream": "^2.0.0",
+ "supports-color": "^8.0.0"
+ },
+ "dependencies": {
+ "has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true
+ },
+ "supports-color": {
+ "version": "8.1.1",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^4.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-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
+ },
+ "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
+ },
+ "json5": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz",
+ "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.5"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "just-extend": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.2.1.tgz",
+ "integrity": "sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg==",
+ "dev": true
+ },
+ "karma": {
+ "version": "6.3.8",
+ "resolved": "https://registry.npmjs.org/karma/-/karma-6.3.8.tgz",
+ "integrity": "sha512-10wBBU9S0lBHhbCNfmmbWQaY5C1bXlKdnvzN2QKThujCI/+DKaezrI08l6bfTlpJ92VsEboq3zYKpXwK6DOi3A==",
+ "dev": true,
+ "requires": {
+ "body-parser": "^1.19.0",
+ "braces": "^3.0.2",
+ "chokidar": "^3.5.1",
+ "colors": "^1.4.0",
+ "connect": "^3.7.0",
+ "di": "^0.0.1",
+ "dom-serialize": "^2.2.1",
+ "glob": "^7.1.7",
+ "graceful-fs": "^4.2.6",
+ "http-proxy": "^1.18.1",
+ "isbinaryfile": "^4.0.8",
+ "lodash": "^4.17.21",
+ "log4js": "^6.3.0",
+ "mime": "^2.5.2",
+ "minimatch": "^3.0.4",
+ "qjobs": "^1.2.0",
+ "range-parser": "^1.2.1",
+ "rimraf": "^3.0.2",
+ "socket.io": "^4.2.0",
+ "source-map": "^0.6.1",
+ "tmp": "^0.2.1",
+ "ua-parser-js": "^0.7.30",
+ "yargs": "^16.1.1"
+ },
+ "dependencies": {
+ "glob": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz",
+ "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==",
+ "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"
+ }
+ },
+ "graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "dev": true
+ },
+ "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
+ }
+ }
+ },
+ "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": "3.0.3",
+ "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-3.0.3.tgz",
+ "integrity": "sha512-wE4VFhG/QZv2Y4CdAYWDbMmcAHeS926ZIji4z+FkB2aF/EposRb6DP6G5ncT/wXhqUfAb/d7kZrNKPonbvsATw==",
+ "dev": true,
+ "requires": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "istanbul-lib-report": "^3.0.0",
+ "istanbul-lib-source-maps": "^3.0.6",
+ "istanbul-reports": "^3.0.2",
+ "minimatch": "^3.0.4"
+ },
+ "dependencies": {
+ "istanbul-lib-coverage": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz",
+ "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==",
+ "dev": true
+ }
+ }
+ },
+ "karma-firefox-launcher": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/karma-firefox-launcher/-/karma-firefox-launcher-2.1.2.tgz",
+ "integrity": "sha512-VV9xDQU1QIboTrjtGVD4NCfzIH7n01ZXqy/qpBhnOeGVOkG5JYPEm8kuSd7psHE6WouZaQ9Ool92g8LFweSNMA==",
+ "dev": true,
+ "requires": {
+ "is-wsl": "^2.2.0",
+ "which": "^2.0.1"
+ },
+ "dependencies": {
+ "which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "requires": {
+ "isexe": "^2.0.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": "2.0.1",
+ "resolved": "https://registry.npmjs.org/karma-mocha/-/karma-mocha-2.0.1.tgz",
+ "integrity": "sha512-Tzd5HBjm8his2OA4bouAsATYEpZrp9vC7z5E5j4C5Of5Rrs1jY67RAwXNcVmd/Bnk1wgvQRou0zGVLey44G4tQ==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.3"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ }
+ }
+ },
+ "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.8",
+ "resolved": "https://registry.npmjs.org/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.8.tgz",
+ "integrity": "sha512-zorxyAakYZuBcHRJE+vbrK2o2JXLFWK8VVjiT/6P+ltLBUGUvqTEkUiQ119MGdOrK7mrmxXHZF1/pfT6GgIZ6g==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2"
+ }
+ },
+ "karma-webpack": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/karma-webpack/-/karma-webpack-5.0.0.tgz",
+ "integrity": "sha512-+54i/cd3/piZuP3dr54+NcFeKOPnys5QeM1IY+0SPASwrtHsliXUiCL50iW+K9WWA7RvamC4macvvQ86l3KtaA==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3",
+ "minimatch": "^3.0.4",
+ "webpack-merge": "^4.1.5"
+ }
+ },
+ "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
+ },
+ "loader-runner": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.2.0.tgz",
+ "integrity": "sha512-92+huvxMvYlMzMt0iIOukcwYBFpkYJdpl2xsZ7LrlayO7E8SOv+JJUEK17B/dJIHAOLMfh2dZZ/Y18WgmGtYNw==",
+ "dev": true
+ },
+ "loader-utils": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.0.tgz",
+ "integrity": "sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ==",
+ "dev": true
+ },
+ "locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
+ "dev": true,
+ "requires": {
+ "p-locate": "^4.1.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
+ "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.get": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
+ "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=",
+ "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
+ },
+ "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": "6.3.0",
+ "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.3.0.tgz",
+ "integrity": "sha512-Mc8jNuSFImQUIateBFwdOQcmC6Q5maU0VVvdC2R6XMb66/VnT+7WS4D/0EeNMZu1YODmJe5NIn2XftCzEocUgw==",
+ "dev": true,
+ "requires": {
+ "date-format": "^3.0.0",
+ "debug": "^4.1.1",
+ "flatted": "^2.0.1",
+ "rfdc": "^1.1.4",
+ "streamroller": "^2.2.4"
+ }
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "memorystream": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
+ "integrity": "sha1-htcJCzDORV1j+64S3aUaR93K+bI=",
+ "dev": true
+ },
+ "merge-source-map": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/merge-source-map/-/merge-source-map-1.1.0.tgz",
+ "integrity": "sha512-Qkcp7P2ygktpMPh2mCQZaf3jhN6D3Z/qVZHSdWvQ+2Ef5HgRAPBO57A77+ENm0CPx2+1Ce/MYKi3ymqdfuqibw==",
+ "dev": true,
+ "requires": {
+ "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
+ }
+ }
+ },
+ "merge-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
+ "dev": true
+ },
+ "mime": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
+ "dev": true
+ },
+ "mime-db": {
+ "version": "1.51.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
+ "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==",
+ "dev": true
+ },
+ "mime-types": {
+ "version": "2.1.34",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
+ "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==",
+ "dev": true,
+ "requires": {
+ "mime-db": "1.51.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
+ },
+ "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.5",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
+ "dev": true
+ },
+ "mocha": {
+ "version": "9.1.3",
+ "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.3.tgz",
+ "integrity": "sha512-Xcpl9FqXOAYqI3j79pEtHBBnQgVXIhpULjGQa7DVb0Po+VzmSIK9kanAiWLHoRR/dbZ2qpdPshuXr8l1VaHCzw==",
+ "dev": true,
+ "requires": {
+ "@ungap/promise-all-settled": "1.1.2",
+ "ansi-colors": "4.1.1",
+ "browser-stdout": "1.3.1",
+ "chokidar": "3.5.2",
+ "debug": "4.3.2",
+ "diff": "5.0.0",
+ "escape-string-regexp": "4.0.0",
+ "find-up": "5.0.0",
+ "glob": "7.1.7",
+ "growl": "1.10.5",
+ "he": "1.2.0",
+ "js-yaml": "4.1.0",
+ "log-symbols": "4.1.0",
+ "minimatch": "3.0.4",
+ "ms": "2.1.3",
+ "nanoid": "3.1.25",
+ "serialize-javascript": "6.0.0",
+ "strip-json-comments": "3.1.1",
+ "supports-color": "8.1.1",
+ "which": "2.0.2",
+ "workerpool": "6.1.5",
+ "yargs": "16.2.0",
+ "yargs-parser": "20.2.4",
+ "yargs-unparser": "2.0.0"
+ },
+ "dependencies": {
+ "ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "requires": {
+ "color-convert": "^2.0.1"
+ }
+ },
+ "argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "dev": true
+ },
+ "chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "dependencies": {
+ "supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^4.0.0"
+ }
+ }
+ }
+ },
+ "color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "requires": {
+ "color-name": "~1.1.4"
+ }
+ },
+ "color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
+ },
+ "debug": {
+ "version": "4.3.2",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",
+ "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",
+ "dev": true,
+ "requires": {
+ "ms": "2.1.2"
+ },
+ "dependencies": {
+ "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
+ }
+ }
+ },
+ "escape-string-regexp": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true
+ },
+ "find-up": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
+ "dev": true,
+ "requires": {
+ "locate-path": "^6.0.0",
+ "path-exists": "^4.0.0"
+ }
+ },
+ "glob": {
+ "version": "7.1.7",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz",
+ "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==",
+ "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"
+ }
+ },
+ "has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true
+ },
+ "js-yaml": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
+ "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
+ "dev": true,
+ "requires": {
+ "argparse": "^2.0.1"
+ }
+ },
+ "locate-path": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
+ "dev": true,
+ "requires": {
+ "p-locate": "^5.0.0"
+ }
+ },
+ "log-symbols": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
+ "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==",
+ "dev": true,
+ "requires": {
+ "chalk": "^4.1.0",
+ "is-unicode-supported": "^0.1.0"
+ }
+ },
+ "ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true
+ },
+ "p-limit": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+ "dev": true,
+ "requires": {
+ "yocto-queue": "^0.1.0"
+ }
+ },
+ "p-locate": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
+ "dev": true,
+ "requires": {
+ "p-limit": "^3.0.2"
+ }
+ },
+ "serialize-javascript": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz",
+ "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==",
+ "dev": true,
+ "requires": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "supports-color": {
+ "version": "8.1.1",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^4.0.0"
+ }
+ },
+ "which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "requires": {
+ "isexe": "^2.0.0"
+ }
+ },
+ "yargs-parser": {
+ "version": "20.2.4",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz",
+ "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==",
+ "dev": true
+ }
+ }
+ },
+ "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
+ },
+ "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
+ },
+ "nanoid": {
+ "version": "3.1.25",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.25.tgz",
+ "integrity": "sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q==",
+ "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.2",
+ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
+ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
+ "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": "5.1.0",
+ "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.0.tgz",
+ "integrity": "sha512-W5WlHu+wvo3PaKLsJJkgPup2LrsXCcm7AWwyNZkUnn5rwPkuPBi3Iwk5SQtN0mv+K65k7nKKjwNQ30wg3wLAQQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.7.0",
+ "@sinonjs/fake-timers": "^7.0.4",
+ "@sinonjs/text-encoding": "^0.7.1",
+ "just-extend": "^4.0.2",
+ "path-to-regexp": "^1.7.0"
+ },
+ "dependencies": {
+ "@sinonjs/fake-timers": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-7.1.2.tgz",
+ "integrity": "sha512-iQADsW4LBMISqZ6Ci1dupJL9pprqwcVFTcOsEmQOEhW+KLCVn/Y4Jrvg2k19fIHCp+iFprriYPTdRcQR8NbUPg==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.7.0"
+ }
+ }
+ }
+ },
+ "node-releases": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.1.tgz",
+ "integrity": "sha512-CqyzN6z7Q6aMeF/ktcMVTzhAHCEpf8SOarwpzpf8pNBY2k5/oM34UHldUwp8VKI7uxct2HxSRdJjBaZeESzcxA==",
+ "dev": true
+ },
+ "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": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ },
+ "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": "4.0.1",
+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",
+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",
+ "dev": true,
+ "requires": {
+ "path-key": "^3.0.0"
+ },
+ "dependencies": {
+ "path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
+ },
+ "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.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.3",
+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.3.tgz",
+ "integrity": "sha512-IDUSMXs6LOSJBWE++L0lzIbSqHl9KDCfff2x/JSEIDtEUavUnyMYC2ZGay/04Zq4UT8lvd4xNhU4/YHKibAOlw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.18.0-next.1",
+ "has": "^1.0.3"
+ },
+ "dependencies": {
+ "es-abstract": {
+ "version": "1.18.0-next.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz",
+ "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.2.2",
+ "is-negative-zero": "^2.0.1",
+ "is-regex": "^1.1.1",
+ "object-inspect": "^1.9.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.2",
+ "string.prototype.trimend": "^1.0.3",
+ "string.prototype.trimstart": "^1.0.3"
+ }
+ },
+ "is-callable": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
+ "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
+ "dev": true
+ },
+ "is-regex": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz",
+ "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "object-inspect": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz",
+ "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==",
+ "dev": true
+ },
+ "object.assign": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
+ "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3",
+ "has-symbols": "^1.0.1",
+ "object-keys": "^1.1.1"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "dev": true,
+ "requires": {
+ "p-try": "^2.0.0"
+ }
+ },
+ "p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
+ "dev": true,
+ "requires": {
+ "p-limit": "^2.2.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
+ },
+ "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": "*"
+ }
+ },
+ "parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "dev": true
+ },
+ "path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "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-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.7",
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
+ "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
+ }
+ }
+ },
+ "pathval": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz",
+ "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==",
+ "dev": true
+ },
+ "performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=",
+ "dev": true
+ },
+ "picocolors": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz",
+ "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==",
+ "dev": true
+ },
+ "picomatch": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "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
+ },
+ "postcss": {
+ "version": "8.4.23",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.23.tgz",
+ "integrity": "sha512-bQ3qMcpF6A/YjR55xtoTr0jGOlnPOKAIMdOWiv0EIT6HVPEaJiJB4NLljSbiHoC2RX7DN5Uvjtpbg1NPdwv1oA==",
+ "dev": true,
+ "peer": true,
+ "requires": {
+ "nanoid": "^3.3.6",
+ "picocolors": "^1.0.0",
+ "source-map-js": "^1.0.2"
+ },
+ "dependencies": {
+ "nanoid": {
+ "version": "3.3.6",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz",
+ "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==",
+ "dev": true,
+ "peer": true
+ }
+ }
+ },
+ "postcss-scss": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/postcss-scss/-/postcss-scss-4.0.6.tgz",
+ "integrity": "sha512-rLDPhJY4z/i4nVFZ27j9GqLxj1pwxE80eAzUNRMXtcpipFYIeowerzBgG3yJhMtObGEXidtIgbUpQ3eLDsf5OQ==",
+ "dev": true,
+ "requires": {}
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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.2",
+ "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-4.0.2.tgz",
+ "integrity": "sha512-ZnScIV3ag9A4wPX/ZayxL/jZH+euYb6FcUinPcgiQW0+UBtEv0O6Q3lGd3cqJ+GHH+rksEv3Pj99oxJ3u3VIKA==",
+ "dev": true,
+ "requires": {
+ "loader-utils": "^2.0.0",
+ "schema-utils": "^3.0.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "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"
+ }
+ },
+ "ajv-keywords": {
+ "version": "3.5.2",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
+ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
+ "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
+ },
+ "loader-utils": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz",
+ "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==",
+ "dev": true,
+ "requires": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^2.1.2"
+ }
+ },
+ "schema-utils": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.0.0.tgz",
+ "integrity": "sha512-6D82/xSzO094ajanoOSbe4YvXWMfn2A//8Y1+MUqFAJul5Bs+yn36xbK9OtNDcRVSBJ9jjeoXftM6CfztsjOAA==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.6",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ }
+ }
+ }
+ },
+ "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.6",
+ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.6.tgz",
+ "integrity": "sha512-10RPdsz0UUrRL1NZE0ejTkucnclYSgXp5q+tB5SWx2qeG2ZJQJyymgAhwKy73yiL/13btfB6fPr+rgbMAaZIAQ==",
+ "requires": {
+ "@babel/runtime": "^7.15.4",
+ "@types/react-redux": "^7.1.20",
+ "hoist-non-react-statics": "^3.3.2",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.7.2",
+ "react-is": "^17.0.2"
+ },
+ "dependencies": {
+ "@babel/runtime": {
+ "version": "7.16.3",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.3.tgz",
+ "integrity": "sha512-WBwekcqacdY2e9AF/Q7WLFUWmdJGJTkbjqTjoMDgXkVZ3ZRUvOPsLb5KdwISoQVsbP+DQzVZW4Zhci0DvpbNTQ==",
+ "requires": {
+ "regenerator-runtime": "^0.13.4"
+ }
+ },
+ "react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
+ }
+ }
+ },
+ "react-shallow-renderer": {
+ "version": "16.14.1",
+ "resolved": "https://registry.npmjs.org/react-shallow-renderer/-/react-shallow-renderer-16.14.1.tgz",
+ "integrity": "sha512-rkIMcQi01/+kxiTE9D3fdS959U1g7gs+/rborw++42m1O9FAQiNI/UNRZExVUoAOprn4umcXf+pFRou8i4zuBg==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4.1.1",
+ "react-is": "^16.12.0 || ^17.0.0"
+ }
+ },
+ "react-test-renderer": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-17.0.2.tgz",
+ "integrity": "sha512-yaQ9cB89c17PUb0x6UfWRs7kQCorVdHlutU1boVPEsB8IDZH6n9tHxMacc3y0JoXOJUsZb/t/Mb8FUWMKaM7iQ==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4.1.1",
+ "react-is": "^17.0.2",
+ "react-shallow-renderer": "^16.13.1",
+ "scheduler": "^0.20.2"
+ },
+ "dependencies": {
+ "react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
+ "dev": true
+ }
+ }
+ },
+ "react-transition-group": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.2.tgz",
+ "integrity": "sha512-/RNYfRAMlZwDSr6z4zNKV6xu53/e2BuaBbGhbyYIXTrmgu/bGHzmqOs7mJSJBHy9Ud+ApHx3QjrkKSp1pxvlFg==",
+ "requires": {
+ "@babel/runtime": "^7.5.5",
+ "dom-helpers": "^5.0.1",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.6.2"
+ }
+ },
+ "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"
+ }
+ },
+ "redux": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/redux/-/redux-4.1.2.tgz",
+ "integrity": "sha512-SH8PglcebESbd/shgf6mii6EIoRM0zrQyjcuQ+ojmfxjTtE0z9Y8pa62iA/OJ58qjP6j27uyW4kUF4jl/jd6sw==",
+ "requires": {
+ "@babel/runtime": "^7.9.2"
+ }
+ },
+ "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.7",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz",
+ "integrity": "sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew=="
+ },
+ "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
+ },
+ "requires-port": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
+ "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=",
+ "dev": true
+ },
+ "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": "3.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz",
+ "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==",
+ "dev": true,
+ "requires": {
+ "resolve-from": "^5.0.0"
+ },
+ "dependencies": {
+ "resolve-from": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
+ "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
+ "dev": true
+ }
+ }
+ },
+ "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.3.0",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz",
+ "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==",
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "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.43.4",
+ "resolved": "https://registry.npmjs.org/sass/-/sass-1.43.4.tgz",
+ "integrity": "sha512-/ptG7KE9lxpGSYiXn7Ar+lKOv37xfWsZRtFYal2QHNigyVQDx685VFT/h7ejVr+R8w7H4tmUgtulsKl5YpveOg==",
+ "dev": true,
+ "requires": {
+ "chokidar": ">=3.0.0 <4.0.0"
+ }
+ },
+ "scheduler": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz",
+ "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==",
+ "dev": true,
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ },
+ "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": "6.0.0",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz",
+ "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==",
+ "dev": true,
+ "requires": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "setprototypeof": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
+ "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "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.4",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.4.tgz",
+ "integrity": "sha512-7gk3UZ9kOfPLIAbslLzyWeGiEqx9e3rxwZM0KE6EL8GlGwjym9Mrlx5/p33bWTu9YG6vcS4MBxYZDHYr5lr8BQ==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.0.0",
+ "interpret": "^1.0.0",
+ "rechoir": "^0.6.2"
+ }
+ },
+ "signal-exit": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz",
+ "integrity": "sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==",
+ "dev": true
+ },
+ "sinon": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/sinon/-/sinon-12.0.1.tgz",
+ "integrity": "sha512-iGu29Xhym33ydkAT+aNQFBINakjq69kKO6ByPvTsm3yyIACfyQttRTP03aBP/I8GfhFmLzrnKwNNkr0ORb1udg==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.8.3",
+ "@sinonjs/fake-timers": "^8.1.0",
+ "@sinonjs/samsam": "^6.0.2",
+ "diff": "^5.0.0",
+ "nise": "^5.1.0",
+ "supports-color": "^7.2.0"
+ },
+ "dependencies": {
+ "has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true
+ },
+ "supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^4.0.0"
+ }
+ }
+ }
+ },
+ "socket.io": {
+ "version": "4.3.2",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.3.2.tgz",
+ "integrity": "sha512-6S5tV4jcY6dbZ/lLzD6EkvNWI3s81JO6ABP/EpvOlK1NPOcIj3AS4khi6xXw6JlZCASq82HQV4SapfmVMMl2dg==",
+ "dev": true,
+ "requires": {
+ "accepts": "~1.3.4",
+ "base64id": "~2.0.0",
+ "debug": "~4.3.2",
+ "engine.io": "~6.0.0",
+ "socket.io-adapter": "~2.3.2",
+ "socket.io-parser": "~4.0.4"
+ }
+ },
+ "socket.io-adapter": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.2.tgz",
+ "integrity": "sha512-PBZpxUPYjmoogY0aoaTmo1643JelsaS1CiAwNjRVdrI0X9Seuc19Y2Wife8k88avW6haG8cznvwbubAZwH4Mtg==",
+ "dev": true
+ },
+ "socket.io-parser": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz",
+ "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==",
+ "dev": true,
+ "requires": {
+ "@types/component-emitter": "^1.2.10",
+ "component-emitter": "~1.3.0",
+ "debug": "~4.3.1"
+ }
+ },
+ "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-js": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
+ "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
+ "dev": true,
+ "peer": true
+ },
+ "source-map-support": {
+ "version": "0.5.21",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+ "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
+ }
+ }
+ },
+ "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
+ },
+ "sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
+ "dev": true
+ },
+ "statuses": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
+ "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=",
+ "dev": true
+ },
+ "stream-browserify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz",
+ "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==",
+ "dev": true,
+ "requires": {
+ "inherits": "~2.0.4",
+ "readable-stream": "^3.5.0"
+ },
+ "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"
+ }
+ }
+ }
+ },
+ "streamroller": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-2.2.4.tgz",
+ "integrity": "sha512-OG79qm3AujAM9ImoqgWEY1xG4HX+Lw+yY6qZj9R1K2mhF5bEmQ849wvrb+4vt4jLMLzwXttJlQbOdPOQVRv7DQ==",
+ "dev": true,
+ "requires": {
+ "date-format": "^2.1.0",
+ "debug": "^4.1.1",
+ "fs-extra": "^8.1.0"
+ },
+ "dependencies": {
+ "date-format": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-2.1.0.tgz",
+ "integrity": "sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA==",
+ "dev": true
+ },
+ "fs-extra": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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.trimend": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.3.tgz",
+ "integrity": "sha512-ayH0pB+uf0U28CtjlLvL7NaohvR1amUvVZk+y3DYb0Ey2PUV5zPkkKy9+U1ndVEIXO8hNg18eIv9Jntbii+dKw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "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.prototype.trimstart": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.3.tgz",
+ "integrity": "sha512-oBIBUy5lea5tt0ovtOFiEQaBkoBBkyJhZXzJYrSmDo5IUUqbOPvVezuRs/agBIdZ2p2Eo1FD6bD9USyBLfl3xg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "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-final-newline": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",
+ "dev": true
+ },
+ "strip-json-comments": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "tapable": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz",
+ "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==",
+ "dev": true
+ },
+ "terser": {
+ "version": "5.10.0",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.10.0.tgz",
+ "integrity": "sha512-AMmF99DMfEDiRJfxfY5jj5wNH/bYO09cniSqhfoyxc8sFoYIgkJy86G04UoZU5VjlpnplVu0K6Tx6E9b5+DlHA==",
+ "dev": true,
+ "requires": {
+ "commander": "^2.20.0",
+ "source-map": "~0.7.2",
+ "source-map-support": "~0.5.20"
+ },
+ "dependencies": {
+ "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
+ }
+ }
+ },
+ "terser-webpack-plugin": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.0.tgz",
+ "integrity": "sha512-LPIisi3Ol4chwAaPP8toUJ3L4qCM1G0wao7L3qNv57Drezxj6+VEyySpPw4B1HSO2Eg/hDY/MNF5XihCAoqnsQ==",
+ "dev": true,
+ "requires": {
+ "jest-worker": "^27.4.1",
+ "schema-utils": "^3.1.1",
+ "serialize-javascript": "^6.0.0",
+ "source-map": "^0.6.1",
+ "terser": "^5.7.2"
+ },
+ "dependencies": {
+ "@types/json-schema": {
+ "version": "7.0.9",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz",
+ "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==",
+ "dev": true
+ },
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "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"
+ }
+ },
+ "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": "3.1.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz",
+ "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ }
+ },
+ "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
+ }
+ }
+ },
+ "tmp": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz",
+ "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==",
+ "dev": true,
+ "requires": {
+ "rimraf": "^3.0.0"
+ }
+ },
+ "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
+ },
+ "toidentifier": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
+ "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==",
+ "dev": true
+ },
+ "tv4": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tv4/-/tv4-1.3.0.tgz",
+ "integrity": "sha1-0CDIRvrdUMhVq7JeuuzGj8EPeWM=",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "ua-parser-js": {
+ "version": "0.7.31",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.31.tgz",
+ "integrity": "sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==",
+ "dev": true
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=",
+ "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": "2.3.1",
+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.3.1.tgz",
+ "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==",
+ "dev": true,
+ "requires": {
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.1.2"
+ }
+ },
+ "webpack": {
+ "version": "5.56.0",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.56.0.tgz",
+ "integrity": "sha512-pJ7esw2AGkpZL0jqsEAKnDEfRZdrc9NVjAWA+d1mFkwj68ng9VQ6+Wnrl+kS5dlDHvrat5ASK5vd7wp6I7f53Q==",
+ "dev": true,
+ "requires": {
+ "@types/eslint-scope": "^3.7.0",
+ "@types/estree": "^0.0.50",
+ "@webassemblyjs/ast": "1.11.1",
+ "@webassemblyjs/wasm-edit": "1.11.1",
+ "@webassemblyjs/wasm-parser": "1.11.1",
+ "acorn": "^8.4.1",
+ "acorn-import-assertions": "^1.7.6",
+ "browserslist": "^4.14.5",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^5.8.3",
+ "es-module-lexer": "^0.9.0",
+ "eslint-scope": "5.1.1",
+ "events": "^3.2.0",
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.2.4",
+ "json-parse-better-errors": "^1.0.2",
+ "loader-runner": "^4.2.0",
+ "mime-types": "^2.1.27",
+ "neo-async": "^2.6.2",
+ "schema-utils": "^3.1.0",
+ "tapable": "^2.1.1",
+ "terser-webpack-plugin": "^5.1.3",
+ "watchpack": "^2.2.0",
+ "webpack-sources": "^3.2.0"
+ },
+ "dependencies": {
+ "@types/json-schema": {
+ "version": "7.0.9",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz",
+ "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==",
+ "dev": true
+ },
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "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"
+ }
+ },
+ "graceful-fs": {
+ "version": "4.2.8",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz",
+ "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==",
+ "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": "3.1.1",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz",
+ "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ }
+ }
+ }
+ },
+ "webpack-cli": {
+ "version": "4.9.1",
+ "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.9.1.tgz",
+ "integrity": "sha512-JYRFVuyFpzDxMDB+v/nanUdQYcZtqFPGzmlW4s+UkPMFhSpfRNmf1z4AwYcHJVdvEFAM7FFCQdNTpsBYhDLusQ==",
+ "dev": true,
+ "requires": {
+ "@discoveryjs/json-ext": "^0.5.0",
+ "@webpack-cli/configtest": "^1.1.0",
+ "@webpack-cli/info": "^1.4.0",
+ "@webpack-cli/serve": "^1.6.0",
+ "colorette": "^2.0.14",
+ "commander": "^7.0.0",
+ "execa": "^5.0.0",
+ "fastest-levenshtein": "^1.0.12",
+ "import-local": "^3.0.2",
+ "interpret": "^2.2.0",
+ "rechoir": "^0.7.0",
+ "webpack-merge": "^5.7.3"
+ },
+ "dependencies": {
+ "commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "dev": true
+ },
+ "interpret": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz",
+ "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==",
+ "dev": true
+ },
+ "rechoir": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz",
+ "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==",
+ "dev": true,
+ "requires": {
+ "resolve": "^1.9.0"
+ }
+ },
+ "webpack-merge": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz",
+ "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==",
+ "dev": true,
+ "requires": {
+ "clone-deep": "^4.0.1",
+ "wildcard": "^2.0.0"
+ }
+ }
+ }
+ },
+ "webpack-merge": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.2.2.tgz",
+ "integrity": "sha512-TUE1UGoTX2Cd42j3krGYqObZbOD+xF7u28WB7tfUordytSjbWTIjK/8V0amkBfTYN4/pB/GIDlJZZ657BGG19g==",
+ "dev": true,
+ "requires": {
+ "lodash": "^4.17.15"
+ }
+ },
+ "webpack-sources": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.2.tgz",
+ "integrity": "sha512-cp5qdmHnu5T8wRg2G3vZZHoJPN14aqQ89SyQ11NpGH5zEMDCclt49rzo+MaRazk7/UeILhAI+/sEtcM+7Fr0nw==",
+ "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"
+ }
+ },
+ "wildcard": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz",
+ "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==",
+ "dev": true
+ },
+ "workerpool": {
+ "version": "6.1.5",
+ "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.5.tgz",
+ "integrity": "sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw==",
+ "dev": true
+ },
+ "wrap-ansi": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true
+ },
+ "ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "requires": {
+ "color-convert": "^2.0.1"
+ }
+ },
+ "color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "requires": {
+ "color-name": "~1.1.4"
+ }
+ },
+ "color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ }
+ },
+ "strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^5.0.1"
+ }
+ }
+ }
+ },
+ "wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
+ "dev": true
+ },
+ "ws": {
+ "version": "8.2.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz",
+ "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==",
+ "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": "16.2.0",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz",
+ "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==",
+ "dev": true,
+ "requires": {
+ "cliui": "^7.0.2",
+ "escalade": "^3.1.1",
+ "get-caller-file": "^2.0.5",
+ "require-directory": "^2.1.1",
+ "string-width": "^4.2.0",
+ "y18n": "^5.0.5",
+ "yargs-parser": "^20.2.2"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ }
+ },
+ "strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^5.0.1"
+ }
+ },
+ "y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "dev": true
+ }
+ }
+ },
+ "yargs-parser": {
+ "version": "20.2.9",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
+ "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
+ "dev": true
+ },
+ "yargs-unparser": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz",
+ "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==",
+ "dev": true,
+ "requires": {
+ "camelcase": "^6.0.0",
+ "decamelize": "^4.0.0",
+ "flat": "^5.0.2",
+ "is-plain-obj": "^2.1.0"
+ }
+ },
+ "yocto-queue": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
+ "dev": true
+ }
+ }
+}
diff --git a/browser/components/newtab/package.json b/browser/components/newtab/package.json
new file mode 100644
index 0000000000..a849dea14d
--- /dev/null
+++ b/browser/components/newtab/package.json
@@ -0,0 +1,124 @@
+{
+ "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/bundle": "0.17.1",
+ "@fluent/react": "0.15.0",
+ "react": "16.13.1",
+ "react-dom": "16.13.1",
+ "react-redux": "7.2.6",
+ "react-transition-group": "4.4.2",
+ "redux": "4.1.2"
+ },
+ "devDependencies": {
+ "@babel/core": "7.16.0",
+ "@babel/plugin-proposal-class-properties": "7.16.0",
+ "@babel/plugin-proposal-nullish-coalescing-operator": "7.16.0",
+ "@babel/plugin-proposal-optional-chaining": "7.16.0",
+ "@babel/preset-react": "7.16.0",
+ "@jsdevtools/coverage-istanbul-loader": "^3.0.5",
+ "acorn": "8.5.0",
+ "babel-loader": "8.2.3",
+ "babel-plugin-jsm-to-esmodules": "0.6.0",
+ "buffer": "6.0.3",
+ "chai": "4.3.4",
+ "chai-json-schema": "1.5.1",
+ "enzyme": "3.11.0",
+ "enzyme-adapter-react-16": "1.15.6",
+ "joi-browser": "13.4.0",
+ "karma": "6.3.8",
+ "karma-chai": "0.1.0",
+ "karma-coverage-istanbul-reporter": "3.0.3",
+ "karma-firefox-launcher": "2.1.2",
+ "karma-json-reporter": "1.2.1",
+ "karma-mocha": "2.0.1",
+ "karma-mocha-reporter": "2.2.5",
+ "karma-sinon": "1.0.5",
+ "karma-sourcemap-loader": "0.3.8",
+ "karma-webpack": "5.0.0",
+ "loader-utils": "3.2.0",
+ "lodash": "4.17.21",
+ "minimist": "1.2.5",
+ "mocha": "9.1.3",
+ "mock-raf": "1.0.1",
+ "npm-run-all": "4.1.5",
+ "postcss-scss": "4.0.6",
+ "prop-types": "15.7.2",
+ "raw-loader": "4.0.2",
+ "react-test-renderer": "17.0.2",
+ "rimraf": "3.0.2",
+ "sass": "1.43.4",
+ "shelljs": "0.8.4",
+ "sinon": "12.0.1",
+ "stream-browserify": "3.0.0",
+ "util": "0.10.4",
+ "webpack": "5.56.0",
+ "webpack-cli": "4.9.1",
+ "yamscripts": "0.1.0"
+ },
+ "engines": {
+ "firefox": ">=45.0 <=*",
+ "//": "when changing node versions, also edit .nvmrc",
+ "node": "16.19.*",
+ "npm": "8.19.3"
+ },
+ "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"
+ },
+ "scripts": {
+ "bundle": "npm-run-all bundle:*",
+ "bundle:webpack": "webpack-cli --config webpack.system-addon.config.js",
+ "bundle:css": "sass content-src/styles:css --no-source-map",
+ "bundle:welcomeBundle": "webpack-cli --config webpack.aboutwelcome.config.js",
+ "bundle:welcomeCss": "sass content-src/aboutwelcome:aboutwelcome/content --no-source-map",
+ "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:css": "npm run bundle:css -- --source-map --embed-sources --embed-source-map --load-path=content-src -w",
+ "watchmc:welcomeBundle": "npm run bundle:welcomeBundle -- --env development -w",
+ "watchmc:welcomeCss": "npm run bundle:welcomeCss -- --source-map --embed-sources --embed-source-map -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/lcov-report/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 soft browser/locales/en-US/browser/newtab)",
+ "lint:license": "(cd $npm_package_config_mc_root && ./mach lint -l license $npm_package_config_newtab_path)",
+ "lint:stylelint": "(cd $npm_package_config_mc_root && ./mach lint -l stylelint $npm_package_config_newtab_path)",
+ "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",
+ "fix:stylelint": "npm run lint:stylelint -- --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/pings.yaml b/browser/components/newtab/pings.yaml
new file mode 100644
index 0000000000..5c7aa7a77a
--- /dev/null
+++ b/browser/components/newtab/pings.yaml
@@ -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/.
+
+---
+$schema: moz://mozilla.org/schemas/glean/pings/2-0-0
+
+newtab:
+ description: |
+ Newtab-related instrumentation.
+ Can be disabled via the `newtabPingEnabled` variable of the `glean` Nimbus
+ feature, or the `browser.newtabpage.ping.enabled` pref.
+ reasons:
+ newtab_session_end: |
+ The newtab visit ended.
+ Could be by navigation, being closed, etc.
+ component_init: |
+ The newtab component init'd,
+ and the newtab and homepage settings have been categorized.
+ This is mostly to ensure we hear at least once from clients configured to
+ not show a newtab UI.
+ include_client_id: true
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1766887
+ notification_emails:
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - anicholson@mozilla.com
+ - najiang@mozilla.com
+
+messaging-system:
+ description: |
+ This is a ping representing single events triggered by the messaging system
+ and captures some pings from About:Welcome, ASRouter, and other corners.
+ include_client_id: false
+ send_if_empty: false
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
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..b580d4543d
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-debug.html
@@ -0,0 +1,47 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.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: chrome:; style-src 'unsafe-inline';"
+ />
+ <meta name="color-scheme" content="light dark" />
+ <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="toolkit/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..572edbfa45
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-noscripts.html
@@ -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/. -->
+
+<!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: chrome:; style-src 'unsafe-inline';"
+ />
+ <meta name="color-scheme" content="light dark" />
+ <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="toolkit/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..74e336a315
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream.html
@@ -0,0 +1,47 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.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: chrome:; style-src 'unsafe-inline';"
+ />
+ <meta name="color-scheme" content="light dark" />
+ <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="toolkit/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..5f6628d816
--- /dev/null
+++ b/browser/components/newtab/test/.eslintrc.js
@@ -0,0 +1,41 @@
+/* eslint-disable import/no-commonjs */
+// This config doesn't inhert from top-level eslint config Bug 1780031
+
+const xpcshellTestPaths = ["./unit*/**", "./xpcshell/**"];
+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,
+ },
+ overrides: [
+ {
+ // Exempt all files without a 'test' string in their path name since no-insecure-url
+ // is focussing on the test base
+ files: "*",
+ excludedFiles: ["**/test**", "**/test*/**", "Test*/**"],
+ rules: {
+ "@microsoft/sdl/no-insecure-url": "off",
+ },
+ },
+ {
+ // Disable "no-insecure-url" for all xpcshell test
+ files: xpcshellTestPaths.map(path => `${path}`),
+ rules: {
+ // As long "new HttpServer()" does not support https there is no reason to log warnings
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1742061
+ "@microsoft/sdl/no-insecure-url": "off",
+ },
+ },
+ ],
+};
diff --git a/browser/components/newtab/test/InflightAssetsMessageProvider.jsm b/browser/components/newtab/test/InflightAssetsMessageProvider.jsm
new file mode 100644
index 0000000000..b6e1f6aeb8
--- /dev/null
+++ b/browser/components/newtab/test/InflightAssetsMessageProvider.jsm
@@ -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/.
+ */
+
+// This file is generated by:
+// https://github.com/mozilla/messaging-system-inflight-assets/tree/master/scripts/export-all.py
+
+const EXPORTED_SYMBOLS = ["InflightAssetsMessageProvider"];
+
+const InflightAssetsMessageProvider = {
+ getMessages() {
+ return [
+ {
+ id: "MILESTONE_MESSAGE",
+ groups: ["cfr"],
+ content: {
+ anchor_id: "tracking-protection-icon-container",
+ bucket_id: "CFR_MILESTONE_MESSAGE",
+ buttons: {
+ primary: {
+ action: {
+ type: "OPEN_PROTECTION_REPORT",
+ },
+ event: "PROTECTION",
+ label: {
+ string_id: "cfr-doorhanger-milestone-ok-button",
+ },
+ },
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-milestone-close-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ event: "DISMISS",
+ },
+ ],
+ },
+ category: "cfrFeatures",
+ heading_text: {
+ string_id: "cfr-doorhanger-milestone-heading",
+ },
+ layout: "short_message",
+ notification_text: "",
+ skip_address_bar_notifier: true,
+ text: "",
+ },
+ frequency: {
+ lifetime: 7,
+ },
+ targeting:
+ "pageLoad >= 4 && firefoxVersion < 87 && userPrefs.cfrFeatures",
+ template: "milestone_message",
+ trigger: {
+ id: "contentBlocking",
+ params: ["ContentBlockingMilestone"],
+ },
+ },
+ {
+ id: "MILESTONE_MESSAGE_87",
+ groups: ["cfr"],
+ content: {
+ anchor_id: "tracking-protection-icon-container",
+ bucket_id: "CFR_MILESTONE_MESSAGE",
+ buttons: {
+ primary: {
+ action: {
+ type: "OPEN_PROTECTION_REPORT",
+ },
+ event: "PROTECTION",
+ label: {
+ string_id: "cfr-doorhanger-milestone-ok-button",
+ },
+ },
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-milestone-close-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ event: "DISMISS",
+ },
+ ],
+ },
+ category: "cfrFeatures",
+ heading_text: {
+ string_id: "cfr-doorhanger-milestone-heading2",
+ },
+ layout: "short_message",
+ notification_text: "",
+ skip_address_bar_notifier: true,
+ text: "",
+ },
+ frequency: {
+ lifetime: 7,
+ },
+ targeting:
+ "pageLoad >= 4 && firefoxVersion >= 87 && userPrefs.cfrFeatures",
+ template: "milestone_message",
+ trigger: {
+ id: "contentBlocking",
+ params: ["ContentBlockingMilestone"],
+ },
+ },
+ {
+ id: "DOH_ROLLOUT_CONFIRMATION_89",
+ groups: ["cfr"],
+ targeting:
+ "profileAgeCreated < 1572480000000 && ( 'doh-rollout.enabled'|preferenceValue || 'doh-rollout.self-enabled'|preferenceValue || 'doh-rollout.ru.enabled'|preferenceValue || 'doh-rollout.ua.enabled'|preferenceValue ) && !( 'doh-rollout.disable-heuristics'|preferenceValue || 'doh-rollout.skipHeuristicsCheck'|preferenceValue || 'doh-rollout.doorhanger-decision'|preferenceValue ) && firefoxVersion >= 89",
+ template: "infobar",
+ content: {
+ priority: 3,
+ type: "global",
+ text: {
+ string_id: "cfr-doorhanger-doh-body",
+ },
+ buttons: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-doh-primary-button-2",
+ },
+ action: {
+ type: "ACCEPT_DOH",
+ },
+ primary: true,
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-doh-secondary-button",
+ },
+ action: {
+ type: "DISABLE_DOH",
+ },
+ },
+ {
+ label: {
+ string_id: "notification-learnmore-default-label",
+ },
+ supportPage: "dns-over-https",
+ callback: null,
+ action: {
+ type: "CANCEL",
+ },
+ },
+ ],
+ bucket_id: "DOH_ROLLOUT_CONFIRMATION_89",
+ category: "cfrFeatures",
+ },
+ frequency: {
+ lifetime: 3,
+ },
+ trigger: {
+ id: "openURL",
+ patterns: ["*://*/*"],
+ },
+ },
+ {
+ id: "INFOBAR_DEFAULT_AND_PIN_87",
+ groups: ["cfr"],
+ content: {
+ category: "cfrFeatures",
+ bucket_id: "INFOBAR_DEFAULT_AND_PIN_87",
+ text: {
+ string_id: "default-browser-notification-message",
+ },
+ type: "global",
+ buttons: [
+ {
+ label: {
+ string_id: "default-browser-notification-button",
+ },
+ action: {
+ type: "PIN_AND_DEFAULT",
+ },
+ primary: true,
+ accessKey: "P",
+ },
+ ],
+ },
+ trigger: {
+ id: "defaultBrowserCheck",
+ },
+ template: "infobar",
+ frequency: {
+ lifetime: 2,
+ custom: [
+ {
+ period: 3024000000,
+ cap: 1,
+ },
+ ],
+ },
+ targeting:
+ "((firefoxVersion >= 87 && firefoxVersion < 89) || (firefoxVersion >= 89 && source == 'startup')) && !isDefaultBrowser && !'browser.shell.checkDefaultBrowser'|preferenceValue && isMajorUpgrade != true && platformName != 'linux' && ((currentDate|date - profileAgeCreated) / 604800000) >= 5 && !activeNotifications && 'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features'|preferenceValue && ((currentDate|date - profileAgeCreated) / 604800000) < 15",
+ },
+ {
+ id: "CFR_FULL_VIDEO_SUPPORT_EN",
+ groups: ["cfr"],
+ targeting:
+ "firefoxVersion < 88 && firefoxVersion != 78 && localeLanguageCode in ['en', 'fr', 'de', 'ru', 'zh', 'es', 'it', 'pl']",
+ 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-video-support-body",
+ },
+ buttons: {
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-cancel-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ ],
+ primary: {
+ label: {
+ string_id: "cfr-doorhanger-video-support-primary-button",
+ },
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://support.mozilla.org/kb/update-firefox-latest-release",
+ where: "tabshifted",
+ },
+ },
+ },
+ },
+ bucket_id: "CFR_FULL_VIDEO_SUPPORT_EN",
+ heading_text: {
+ string_id: "cfr-doorhanger-video-support-header",
+ },
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ notification_text: "Message from Firefox",
+ category: "cfrFeatures",
+ },
+ frequency: {
+ lifetime: 3,
+ },
+ trigger: {
+ id: "openURL",
+ patterns: ["https://*/Amazon-Video/*", "https://*/Prime-Video/*"],
+ params: [
+ "www.hulu.com",
+ "hulu.com",
+ "www.netflix.com",
+ "netflix.com",
+ "www.disneyplus.com",
+ "disneyplus.com",
+ "www.hbomax.com",
+ "hbomax.com",
+ "www.sho.com",
+ "sho.com",
+ "www.directv.com",
+ "directv.com",
+ "www.starzplay.com",
+ "starzplay.com",
+ "www.sling.com",
+ "sling.com",
+ "www.facebook.com",
+ "facebook.com",
+ ],
+ },
+ },
+ {
+ id: "WNP_MOMENTS_12",
+ groups: ["moments-pages"],
+ content: {
+ action: {
+ data: {
+ expire: 1640908800000,
+ url: "https://www.mozilla.org/firefox/welcome/12",
+ },
+ id: "moments-wnp",
+ },
+ bucket_id: "WNP_MOMENTS_12",
+ },
+ targeting:
+ 'localeLanguageCode == "en" && region in ["DE", "AT", "BE", "CA", "FR", "IE", "IT", "MY", "NL", "NZ", "SG", "CH", "US", "GB", "ES"] && (addonsInfo.addons|keys intersect ["@testpilot-containers"])|length == 1 && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features\'|preferenceValue && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons\'|preferenceValue',
+ template: "update_action",
+ trigger: {
+ id: "momentsUpdate",
+ },
+ },
+ {
+ id: "WNP_MOMENTS_13",
+ groups: ["moments-pages"],
+ content: {
+ action: {
+ data: {
+ expire: 1640908800000,
+ url: "https://www.mozilla.org/firefox/welcome/13",
+ },
+ id: "moments-wnp",
+ },
+ bucket_id: "WNP_MOMENTS_13",
+ },
+ targeting:
+ '(localeLanguageCode in ["en", "de", "fr", "nl", "it", "ms"] || locale == "es-ES") && region in ["DE", "AT", "BE", "CA", "FR", "IE", "IT", "MY", "NL", "NZ", "SG", "CH", "US", "GB", "ES"] && (addonsInfo.addons|keys intersect ["@testpilot-containers"])|length == 0 && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features\'|preferenceValue && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons\'|preferenceValue',
+ template: "update_action",
+ trigger: {
+ id: "momentsUpdate",
+ },
+ },
+ {
+ id: "WNP_MOMENTS_14",
+ groups: ["moments-pages"],
+ content: {
+ action: {
+ data: {
+ expire: 1668470400000,
+ url: "https://www.mozilla.org/firefox/welcome/14",
+ },
+ id: "moments-wnp",
+ },
+ bucket_id: "WNP_MOMENTS_14",
+ },
+ targeting:
+ 'localeLanguageCode in ["en", "de", "fr"] && region in ["AT", "BE", "CA", "CH", "DE", "ES", "FI", "FR", "GB", "IE", "IT", "MY", "NL", "NZ", "SE", "SG", "US"] && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features\'|preferenceValue && \'browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons\'|preferenceValue',
+ template: "update_action",
+ trigger: {
+ id: "momentsUpdate",
+ },
+ },
+ ];
+ },
+};
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..febe76d92e
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser.ini
@@ -0,0 +1,39 @@
+[DEFAULT]
+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
+ dom.ipc.processPrelaunch.delayMs=0
+# Bug 1694957 is why we need dom.ipc.processPrelaunch.delayMs=0
+
+[browser_basic_endtoend.js]
+[browser_bump_version.js]
+[browser_disabled.js]
+[browser_experiments_api_control.js]
+[browser_locale_change.js]
+[browser_no_cache.js]
+[browser_no_cache_on_SessionStartup_restore.js]
+[browser_no_startup_actions.js]
+[browser_overwrite_cache.js]
+[browser_process_crash.js]
+skip-if =
+ !crashreporter
+ os == "mac" && fission # Bug 1659427; medium frequency intermittent on osx: test timed out
+[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..bd42dd4af9
--- /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 withFullyLoadedAboutHome(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..726b9aa973
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_bump_version.js
@@ -0,0 +1,35 @@
+/* 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 withFullyLoadedAboutHome(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");
+ // We don't need to shutdown write or ensure the cache wins the race,
+ // since we expect the cache to be blown away because the version number
+ // has been bumped.
+ await simulateRestart(browser, {
+ withAutoShutdownWrite: false,
+ ensureCacheWinsRace: false,
+ });
+ 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..faa79b219c
--- /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 withFullyLoadedAboutHome(async browser => {
+ await simulateRestart(browser);
+ });
+});
+
+/**
+ * Tests the case where the cache is disabled via the pref.
+ */
+add_task(async function test_cache_disabled() {
+ await withFullyLoadedAboutHome(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 withFullyLoadedAboutHome(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 withFullyLoadedAboutHome(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 withFullyLoadedAboutHome(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_experiments_api_control.js b/browser/components/newtab/test/browser/abouthomecache/browser_experiments_api_control.js
new file mode 100644
index 0000000000..a94f1fe055
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_experiments_api_control.js
@@ -0,0 +1,63 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ExperimentFakes } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+
+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 withFullyLoadedAboutHome(async browser => {
+ await simulateRestart(browser);
+ });
+});
+
+/**
+ * Tests that the ExperimentsAPI mechanism can be used to remotely
+ * enable and disable the about:home startup cache.
+ */
+add_task(async function test_experiments_api_control() {
+ // First, the disabled case.
+ await withFullyLoadedAboutHome(async browser => {
+ let doEnrollmentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "abouthomecache",
+ value: { enabled: false },
+ });
+
+ Assert.ok(
+ !NimbusFeatures.abouthomecache.getVariable("enabled"),
+ "NimbusFeatures should tell us that the about:home startup cache " +
+ "is disabled"
+ );
+
+ await simulateRestart(browser);
+
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DISABLED
+ );
+
+ await doEnrollmentCleanup();
+ });
+
+ // Now the enabled case.
+ await withFullyLoadedAboutHome(async browser => {
+ let doEnrollmentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "abouthomecache",
+ value: { enabled: true },
+ });
+
+ Assert.ok(
+ NimbusFeatures.abouthomecache.getVariable("enabled"),
+ "NimbusFeatures should tell us that the about:home startup cache " +
+ "is enabled"
+ );
+
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+ await doEnrollmentCleanup();
+ });
+});
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..e9e3c619ec
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js
@@ -0,0 +1,30 @@
+/* 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 withFullyLoadedAboutHome(async browser => {
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ Services.obs.notifyObservers(null, "intl:app-locales-changed");
+ await AboutHomeStartupCache.ensureCacheEntry();
+
+ // We're testing that switching locales blows away the cache, so we
+ // bypass the automatic writing of the cache on shutdown, and we
+ // also don't need to wait for the cache to be available.
+ await simulateRestart(browser, {
+ withAutoShutdownWrite: false,
+ ensureCacheWinsRace: 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..fdb51f8712
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js
@@ -0,0 +1,27 @@
+/* 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 withFullyLoadedAboutHome(async browser => {
+ await clearCache();
+ // We're testing the no-cache case, so we bypass the automatic writing
+ // of the cache on shutdown, and we also don't need to wait for the
+ // cache to be available.
+ await simulateRestart(browser, {
+ withAutoShutdownWrite: false,
+ ensureCacheWinsRace: false,
+ });
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DOES_NOT_EXIST
+ );
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_no_cache_on_SessionStartup_restore.js b/browser/components/newtab/test/browser/abouthomecache/browser_no_cache_on_SessionStartup_restore.js
new file mode 100644
index 0000000000..a312b2b44f
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_no_cache_on_SessionStartup_restore.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that if somehow about:newtab loads before about:home does, that we
+ * don't use the cache. This is because about:newtab doesn't use the cache,
+ * and so it'll inevitably be newer than what's in the about:home cache,
+ * which will put the about:home cache out of date the next time about:home
+ * eventually loads.
+ */
+add_task(async function test_no_cache_on_SessionStartup_restore() {
+ await withFullyLoadedAboutHome(async browser => {
+ await simulateRestart(browser, { skipAboutHomeLoad: true });
+
+ // We remove the preloaded browser to ensure that loading the next
+ // about:newtab occurs now, and not at preloading time.
+ NewTabPagePreloading.removePreloadedBrowser(window);
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab"
+ );
+
+ let newWin = await BrowserTestUtils.openNewBrowserWindow();
+
+ // The cache is disqualified because about:newtab was loaded first.
+ // So now it's too late to use the cache.
+ await ensureDynamicAboutHome(
+ newWin.gBrowser.selectedBrowser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.LATE
+ );
+
+ await BrowserTestUtils.closeWindow(newWin);
+ await BrowserTestUtils.removeTab(tab);
+ });
+});
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..255b4c9d21
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js
@@ -0,0 +1,83 @@
+/* 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 withFullyLoadedAboutHome(async browser => {
+ // Make sure we have a cached document. We simulate a restart to ensure
+ // that we start with a cache... that we can then clear without a problem,
+ // before writing a new cache. This ensures that no matter what, we're in a
+ // state where we have a fresh cache, regardless of what's happened in earlier
+ // tests.
+ await simulateRestart(browser);
+ await clearCache();
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ // Set up a 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..22df98794f
--- /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 withFullyLoadedAboutHome(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, { withAutoShutdownWrite: false });
+
+ 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..2a26bc553d
--- /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 withFullyLoadedAboutHome(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 withFullyLoadedAboutHome(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 withFullyLoadedAboutHome(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..75f8875f26
--- /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 withFullyLoadedAboutHome(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, { withAutoShutdownWrite: false });
+
+ // 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..4dc7ba2c89
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_sanitize.js
@@ -0,0 +1,54 @@
+/* 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 withFullyLoadedAboutHome(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}`));
+ }
+ },
+ });
+ });
+
+ // For the purposes of the test, we don't want the write-on-shutdown
+ // behaviour here (because we just want to test that the cache doesn't
+ // exist on startup if the history data was cleared). We also therefore
+ // don't need to ensure that the cache wins the race.
+ await simulateRestart(browser, {
+ withAutoShutdownWrite: false,
+ ensureCacheWinsRace: 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..52be79338e
--- /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 withFullyLoadedAboutHome(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..a3c8c1434b
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/head.js
@@ -0,0 +1,360 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+let { AboutHomeStartupCache } = ChromeUtils.importESModule(
+ "resource:///modules/BrowserGlue.sys.mjs"
+);
+
+// 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)
+ );
+}
+
+/**
+ * Utility function that loads about:home in the current window in a new tab, and waits
+ * for the Discovery Stream cards to finish loading before running the taskFn function.
+ * Once taskFn exits, the about:home tab will be closed.
+ *
+ * @param {function} taskFn
+ * A function that will be run after about:home has finished loading. This can be
+ * an async function.
+ * @return {Promise}
+ * @resolves {undefined}
+ */
+// eslint-disable-next-line no-unused-vars
+function withFullyLoadedAboutHome(taskFn) {
+ return BrowserTestUtils.withNewTab("about:home", async browser => {
+ await SpecialPowers.spawn(browser, [], async () => {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelectorAll(
+ "[data-section-id='topstories'] .ds-card-link"
+ ).length,
+ "Waiting for Discovery Stream to be rendered."
+ );
+ });
+
+ await taskFn(browser);
+ });
+}
+
+/**
+ * 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.
+ *
+ * skipAboutHomeLoad (boolean, optional):
+ * If true, doesn't automatically load about:home after the simulated
+ * restart. 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 = true,
+ ensureCacheWinsRace = true,
+ expectTimeout = false,
+ skipAboutHomeLoad = 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();
+ });
+ });
+ }
+ }
+
+ if (!skipAboutHomeLoad) {
+ info("Waiting for about:home to load");
+ let loaded = BrowserTestUtils.browserLoaded(browser, false, "about:home");
+ BrowserTestUtils.loadURIString(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/annotation_first.html b/browser/components/newtab/test/browser/annotation_first.html
new file mode 100644
index 0000000000..e40ed1db6c
--- /dev/null
+++ b/browser/components/newtab/test/browser/annotation_first.html
@@ -0,0 +1,2 @@
+first
+<a href="annotation_second.html">goto second</a>
diff --git a/browser/components/newtab/test/browser/annotation_second.html b/browser/components/newtab/test/browser/annotation_second.html
new file mode 100644
index 0000000000..8d8bbab6bd
--- /dev/null
+++ b/browser/components/newtab/test/browser/annotation_second.html
@@ -0,0 +1,2 @@
+second
+<a href="https://www.example.com/browser/browser/components/newtab/test/browser/annotation_third.html">goto third</a>
diff --git a/browser/components/newtab/test/browser/annotation_third.html b/browser/components/newtab/test/browser/annotation_third.html
new file mode 100644
index 0000000000..b63f85fe1f
--- /dev/null
+++ b/browser/components/newtab/test/browser/annotation_third.html
@@ -0,0 +1,2 @@
+thrid
+<a href="https://example.org/">goto outside</a>
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..9979b4f877
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser.ini
@@ -0,0 +1,112 @@
+[DEFAULT]
+support-files =
+ blue_page.html
+ red_page.html
+ annotation_first.html
+ annotation_second.html
+ annotation_third.html
+ head.js
+ redirect_to.sjs
+ snippet.json
+ snippet_below_search_test.json
+ snippet_simple_test.json
+ topstories.json
+ ds_layout.json
+ file_pdf.PDF
+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
+ intl.multilingual.aboutWelcome.languageMismatchEnabled=false
+
+[browser_aboutwelcome_attribution.js]
+skip-if =
+ os == "linux" # Test setup only implemented for OSX and Windows
+ os == "mac" && bits == 64 # See bug 1784121
+ os == "win" && msix # These tests rely on the ability to write postSigningData, which we can't do in MSIX builds. https://bugzilla.mozilla.org/show_bug.cgi?id=1805911
+[browser_aboutwelcome_configurable_ui.js]
+skip-if =
+ os == "linux" && bits == 64 && debug # Bug 1784548
+[browser_aboutwelcome_fxa_signin_flow.js]
+[browser_aboutwelcome_glean.js]
+[browser_aboutwelcome_import.js]
+[browser_aboutwelcome_mobile_downloads.js]
+[browser_aboutwelcome_multistage_default.js]
+[browser_aboutwelcome_multistage_experimentAPI.js]
+[browser_aboutwelcome_multistage_languageSwitcher.js]
+skip-if =
+ os == 'linux' && bits == 64 # Bug 1757875
+[browser_aboutwelcome_multistage_mr.js]
+skip-if = os == 'linux' && bits == 64 && debug #Bug 1812050
+[browser_aboutwelcome_multistage_video.js]
+[browser_aboutwelcome_observer.js]
+https_first_disabled = true
+[browser_aboutwelcome_rtamo.js]
+skip-if =
+ os == "linux" # Test setup only implemented for OSX and Windows
+ os == "mac" && bits == 64 # See bug 1784121
+ os == "win" && msix # These tests rely on the ability to write postSigningData, which we can't do in MSIX builds. https://bugzilla.mozilla.org/show_bug.cgi?id=1805911
+[browser_aboutwelcome_screen_targeting.js]
+[browser_aboutwelcome_upgrade_multistage_mr.js]
+[browser_as_load_location.js]
+[browser_as_render.js]
+[browser_asrouter_bug1761522.js]
+[browser_asrouter_bug1800087.js]
+[browser_asrouter_cfr.js]
+https_first_disabled = true
+[browser_asrouter_experimentsAPILoader.js]
+[browser_asrouter_group_frequency.js]
+https_first_disabled = true
+[browser_asrouter_group_userprefs.js]
+skip-if =
+ os == 'linux' && bits == 64 && !debug # Bug 1643036
+[browser_asrouter_infobar.js]
+[browser_asrouter_momentspagehub.js]
+tags = remote-settings
+[browser_asrouter_snippets.js]
+https_first_disabled = true
+[browser_asrouter_snippets_dismiss.js]
+support-files=
+ ../../../../base/content/aboutRobots-icon.png
+[browser_asrouter_targeting.js]
+[browser_asrouter_toast_notification.js]
+[browser_asrouter_toolbarbadge.js]
+tags = remote-settings
+[browser_context_menu_item.js]
+[browser_customize_menu_content.js]
+skip-if = (os == "linux" && tsan) #Bug 1687896
+https_first_disabled = true
+[browser_customize_menu_render.js]
+[browser_discovery_card.js]
+[browser_discovery_render.js]
+[browser_discovery_styles.js]
+[browser_enabled_newtabpage.js]
+[browser_feature_callout_in_chrome.js]
+[browser_getScreenshots.js]
+[browser_highlights_section.js]
+[browser_multistage_spotlight.js]
+[browser_multistage_spotlight_telemetry.js]
+skip-if = verify # bug 1834620 - order of events not stable
+[browser_newtab_header.js]
+[browser_newtab_last_LinkMenu.js]
+[browser_newtab_overrides.js]
+[browser_newtab_ping.js]
+skip-if =
+ os == "win" && os_version == "6.1" # Skip on Azure - frequent failure
+[browser_newtab_towindow.js]
+[browser_newtab_trigger.js]
+[browser_open_tab_focus.js]
+skip-if = (os == "linux") # Test setup only implemented for OSX and Windows
+[browser_remote_l10n.js]
+[browser_topsites_annotation.js]
+skip-if=
+ os == "linux" && bits == 64 && debug # Bug 1785005
+[browser_topsites_contextMenu_options.js]
+[browser_topsites_section.js]
+[browser_trigger_listeners.js]
+https_first_disabled = true
+[browser_trigger_messagesLoaded.js]
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..ae33a383ba
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js
@@ -0,0 +1,214 @@
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { AttributionCode } = ChromeUtils.importESModule(
+ "resource:///modules/AttributionCode.sys.mjs"
+);
+const { AddonRepository } = ChromeUtils.importESModule(
+ "resource://gre/modules/addons/AddonRepository.sys.mjs"
+);
+
+const TEST_ATTRIBUTION_DATA = {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ // with the sinon override, the id doesn't matter
+ content: "rta:whatever",
+};
+
+const TEST_ADDON_INFO = [
+ {
+ name: "Test Add-on",
+ sourceURI: { scheme: "https", spec: "https://test.xpi" },
+ icons: { 32: "test.png", 64: "test.png" },
+ type: "extension",
+ },
+];
+
+const TEST_UA_ATTRIBUTION_DATA = {
+ ua: "chrome",
+};
+
+const TEST_PROTON_CONTENT = [
+ {
+ id: "AW_STEP1",
+ content: {
+ title: "Step 1",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ title: "Step 2",
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-import-primary-button-label",
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ },
+ has_noodles: true,
+ },
+ },
+];
+
+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",
+ "h2[data-l10n-id='mr1-return-to-amo-addon-title']",
+ "div.rtamo-icon",
+ "button.primary",
+ "button.secondary",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+});
+
+async function openMultiStageWithUserAgentAttribution() {
+ const sandbox = sinon.createSandbox();
+ await ASRouter.forceAttribution(TEST_UA_ATTRIBUTION_DATA);
+ const TEST_PROTON_JSON = JSON.stringify(TEST_PROTON_CONTENT);
+
+ await setAboutWelcomePref(true);
+ await pushPrefs(["browser.aboutwelcome.screens", TEST_PROTON_JSON]);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(async () => {
+ BrowserTestUtils.removeTab(tab);
+ await ASRouter.forceAttribution("");
+ sandbox.restore();
+ });
+ return tab.linkedBrowser;
+}
+
+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();
+ }
+ );
+}
+
+add_task(async function test_ua_attribution() {
+ let browser = await openMultiStageWithUserAgentAttribution();
+
+ await test_screen_content(
+ browser,
+ "multistage step 1 with ua attribution",
+ // Expected selectors:
+ ["div.onboardingContainer", "main.AW_STEP1", "button.primary"],
+ // Unexpected selectors:
+ ["main.AW_STEP2"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ await test_screen_content(
+ browser,
+ "multistage step 2 with ua attribution",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP2",
+ "button.primary[data-l10n-args*='Google Chrome']",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP1"]
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_configurable_ui.js b/browser/components/newtab/test/browser/browser_aboutwelcome_configurable_ui.js
new file mode 100644
index 0000000000..5376c8bf60
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_configurable_ui.js
@@ -0,0 +1,668 @@
+"use strict";
+
+const { ExperimentFakes } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+
+const { AboutWelcomeTelemetry } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm"
+);
+
+const BASE_SCREEN_CONTENT = {
+ title: "Step 1",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+};
+
+const makeTestContent = (id, contentAdditions) => {
+ return {
+ id,
+ content: Object.assign({}, BASE_SCREEN_CONTENT, contentAdditions),
+ };
+};
+
+async function openAboutWelcome(json) {
+ if (json) {
+ await setAboutWelcomeMultiStage(json);
+ }
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+async function testAboutWelcomeLogoFor(logo = {}) {
+ info(`Testing logo: ${JSON.stringify(logo)}`);
+
+ let screens = [makeTestContent("TEST_LOGO_SELECTION_STEP", { logo })];
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: { enabled: true, screens },
+ });
+
+ let browser = await openAboutWelcome(JSON.stringify(screens));
+
+ let expected = [
+ `.brand-logo[src="${
+ logo.imageURL ?? "chrome://branding/content/about-logo.svg"
+ }"][alt="${logo.alt ?? ""}"]${logo.height ? `[style*="height"]` : ""}${
+ logo.alt ? "" : `[role="presentation"]`
+ }`,
+ ];
+ let unexpected = [];
+ if (!logo.height) {
+ unexpected.push(`.brand-logo[style*="height"]`);
+ }
+ if (logo.alt) {
+ unexpected.push(`.brand-logo[role="presentation"]`);
+ }
+ (logo.darkModeImageURL ? expected : unexpected).push(
+ `.logo-container source[media="(prefers-color-scheme: dark)"]${
+ logo.darkModeImageURL ? `[srcset="${logo.darkModeImageURL}"]` : ""
+ }`
+ );
+ (logo.reducedMotionImageURL ? expected : unexpected).push(
+ `.logo-container source[media="(prefers-reduced-motion: reduce)"]${
+ logo.reducedMotionImageURL
+ ? `[srcset="${logo.reducedMotionImageURL}"]`
+ : ""
+ }`
+ );
+ (logo.darkModeReducedMotionImageURL ? expected : unexpected).push(
+ `.logo-container source[media="(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)"]${
+ logo.darkModeReducedMotionImageURL
+ ? `[srcset="${logo.darkModeReducedMotionImageURL}"]`
+ : ""
+ }`
+ );
+ await test_screen_content(
+ browser,
+ "renders screen with passed logo",
+ expected,
+ unexpected
+ );
+
+ await doExperimentCleanup();
+ browser.closeBrowser();
+}
+
+/**
+ * Test rendering a screen in about welcome with decorative noodles
+ */
+add_task(async function test_aboutwelcome_with_noodles() {
+ const TEST_NOODLE_CONTENT = makeTestContent("TEST_NOODLE_STEP", {
+ has_noodles: true,
+ });
+ const TEST_NOODLE_JSON = JSON.stringify([TEST_NOODLE_CONTENT]);
+ let browser = await openAboutWelcome(TEST_NOODLE_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with noodles",
+ // Expected selectors:
+ [
+ "main.TEST_NOODLE_STEP[pos='center']",
+ "div.noodle.purple-C",
+ "div.noodle.orange-L",
+ "div.noodle.outline-L",
+ "div.noodle.yellow-circle",
+ ]
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a customized logo
+ */
+add_task(async function test_aboutwelcome_with_customized_logo() {
+ const TEST_LOGO_URL = "chrome://branding/content/icon64.png";
+ const TEST_LOGO_HEIGHT = "50px";
+ const TEST_LOGO_CONTENT = makeTestContent("TEST_LOGO_STEP", {
+ logo: {
+ height: TEST_LOGO_HEIGHT,
+ imageURL: TEST_LOGO_URL,
+ },
+ });
+ const TEST_LOGO_JSON = JSON.stringify([TEST_LOGO_CONTENT]);
+ let browser = await openAboutWelcome(TEST_LOGO_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with customized logo",
+ // Expected selectors:
+ ["main.TEST_LOGO_STEP[pos='center']", `.brand-logo[src="${TEST_LOGO_URL}"]`]
+ );
+
+ // Ensure logo has custom height
+ await test_element_styles(
+ browser,
+ ".brand-logo",
+ // Expected styles:
+ {
+ // Override default text-link styles
+ height: TEST_LOGO_HEIGHT,
+ }
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with empty logo used for padding
+ */
+add_task(async function test_aboutwelcome_with_empty_logo_spacing() {
+ const TEST_LOGO_HEIGHT = "50px";
+ const TEST_LOGO_CONTENT = makeTestContent("TEST_LOGO_STEP", {
+ logo: {
+ height: TEST_LOGO_HEIGHT,
+ imageURL: "none",
+ },
+ });
+ const TEST_LOGO_JSON = JSON.stringify([TEST_LOGO_CONTENT]);
+ let browser = await openAboutWelcome(TEST_LOGO_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with empty logo element",
+ // Expected selectors:
+ ["main.TEST_LOGO_STEP[pos='center']", ".brand-logo[src='none']"]
+ );
+
+ // Ensure logo has custom height
+ await test_element_styles(
+ browser,
+ ".brand-logo",
+ // Expected styles:
+ {
+ // Override default text-link styles
+ height: TEST_LOGO_HEIGHT,
+ }
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a title with custom styles.
+ */
+add_task(async function test_aboutwelcome_with_title_styles() {
+ const TEST_TITLE_STYLE_CONTENT = makeTestContent("TEST_TITLE_STYLE_STEP", {
+ title: {
+ fontSize: "36px",
+ fontWeight: 276,
+ letterSpacing: 0,
+ raw: "test",
+ },
+ title_style: "fancy shine",
+ });
+
+ const TEST_TITLE_STYLE_JSON = JSON.stringify([TEST_TITLE_STYLE_CONTENT]);
+ let browser = await openAboutWelcome(TEST_TITLE_STYLE_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with customized title style",
+ // Expected selectors:
+ [`div.welcome-text.fancy.shine`]
+ );
+
+ await test_element_styles(
+ browser,
+ "#mainContentHeader",
+ // Expected styles:
+ {
+ "font-weight": "276",
+ "font-size": "36px",
+ animation: "50s linear 0s infinite normal none running shine",
+ "letter-spacing": "normal",
+ }
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with an image for the dialog window's background
+ */
+add_task(async function test_aboutwelcome_with_background() {
+ const BACKGROUND_URL =
+ "chrome://activity-stream/content/data/content/assets/confetti.svg";
+ const TEST_BACKGROUND_CONTENT = makeTestContent("TEST_BACKGROUND_STEP", {
+ background: `url(${BACKGROUND_URL}) no-repeat center/cover`,
+ });
+
+ const TEST_BACKGROUND_JSON = JSON.stringify([TEST_BACKGROUND_CONTENT]);
+ let browser = await openAboutWelcome(TEST_BACKGROUND_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with dialog background image",
+ // Expected selectors:
+ [`div.main-content[style*='${BACKGROUND_URL}'`]
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a dismiss button
+ */
+add_task(async function test_aboutwelcome_dismiss_button() {
+ let browser = await openAboutWelcome(
+ JSON.stringify(
+ // Use 2 screens to test that the message is dismissed, not navigated
+ [1, 2].map(i =>
+ makeTestContent(`TEST_DISMISS_STEP_${i}`, {
+ dismiss_button: { action: { dismiss: true } },
+ })
+ )
+ )
+ );
+
+ // Click dismiss button
+ await onButtonClick(browser, "button.dismiss-button");
+
+ // Wait for about:home to load
+ await BrowserTestUtils.browserLoaded(browser, false, "about:home");
+ is(browser.currentURI.spec, "about:home", "about:home loaded");
+
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with the "split" position
+ */
+add_task(async function test_aboutwelcome_split_position() {
+ const TEST_SPLIT_STEP = makeTestContent("TEST_SPLIT_STEP", {
+ position: "split",
+ hero_text: "hero test",
+ });
+
+ const TEST_SPLIT_JSON = JSON.stringify([TEST_SPLIT_STEP]);
+ let browser = await openAboutWelcome(TEST_SPLIT_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen secondary section containing hero text",
+ // Expected selectors:
+ [`main.screen[pos="split"]`, `.section-secondary`, `.message-text h1`]
+ );
+
+ // Ensure secondary section has split template styling
+ await test_element_styles(
+ browser,
+ "main.screen .section-secondary",
+ // Expected styles:
+ {
+ display: "flex",
+ margin: "auto 0px auto auto",
+ }
+ );
+
+ // Ensure secondary action has button styling
+ await test_element_styles(
+ browser,
+ ".action-buttons .secondary-cta .secondary",
+ // Expected styles:
+ {
+ // Override default text-link styles
+ "background-color": "rgba(21, 20, 26, 0.07)",
+ color: "rgb(21, 20, 26)",
+ }
+ );
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a URL value and default color for backdrop
+ */
+add_task(async function test_aboutwelcome_with_url_backdrop() {
+ const TEST_BACKDROP_URL = `url("chrome://activity-stream/content/data/content/assets/confetti.svg")`;
+ const TEST_BACKDROP_VALUE = `#212121 ${TEST_BACKDROP_URL} center/cover no-repeat fixed`;
+ const TEST_URL_BACKDROP_CONTENT = makeTestContent("TEST_URL_BACKDROP_STEP");
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ backdrop: TEST_BACKDROP_VALUE,
+ screens: [TEST_URL_BACKDROP_CONTENT],
+ },
+ });
+ let browser = await openAboutWelcome();
+
+ await test_screen_content(
+ browser,
+ "renders screen with background image",
+ // Expected selectors:
+ [`div.outer-wrapper.onboardingContainer[style*='${TEST_BACKDROP_URL}']`]
+ );
+ await doExperimentCleanup();
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a color name for backdrop
+ */
+add_task(async function test_aboutwelcome_with_color_backdrop() {
+ const TEST_BACKDROP_COLOR = "transparent";
+ const TEST_BACKDROP_COLOR_CONTENT = makeTestContent(
+ "TEST_COLOR_NAME_BACKDROP_STEP"
+ );
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ backdrop: TEST_BACKDROP_COLOR,
+ screens: [TEST_BACKDROP_COLOR_CONTENT],
+ },
+ });
+ let browser = await openAboutWelcome();
+
+ await test_screen_content(
+ browser,
+ "renders screen with background color",
+ // Expected selectors:
+ [`div.outer-wrapper.onboardingContainer[style*='${TEST_BACKDROP_COLOR}']`]
+ );
+ await doExperimentCleanup();
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a text color override
+ */
+add_task(async function test_aboutwelcome_with_text_color_override() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ // Override the system color scheme to dark
+ ["ui.systemUsesDarkTheme", 1],
+ ],
+ });
+
+ let screens = [];
+ // we need at least two screens to test the step indicator
+ for (let i = 0; i < 2; i++) {
+ screens.push(
+ makeTestContent("TEST_TEXT_COLOR_OVERRIDE_STEP", {
+ text_color: "dark",
+ background: "white",
+ })
+ );
+ }
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ screens,
+ },
+ });
+ let browser = await openAboutWelcome(JSON.stringify(screens));
+
+ await test_screen_content(
+ browser,
+ "renders screen with dark text",
+ // Expected selectors:
+ [`main.screen.dark-text`, `.indicator.current`, `.indicator:not(.current)`],
+ // Unexpected selectors:
+ [`main.screen.light-text`]
+ );
+
+ // Ensure title inherits light text color
+ await test_element_styles(
+ browser,
+ "#mainContentHeader",
+ // Expected styles:
+ {
+ color: "rgb(21, 20, 26)",
+ }
+ );
+
+ // Ensure next step indicator inherits light color
+ await test_element_styles(
+ browser,
+ ".indicator:not(.current)",
+ // Expected styles:
+ {
+ color: "rgb(251, 251, 254)",
+ }
+ );
+
+ await doExperimentCleanup();
+ await SpecialPowers.popPrefEnv();
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with a "progress bar" style step indicator
+ */
+add_task(async function test_aboutwelcome_with_progress_bar() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["ui.systemUsesDarkTheme", 0],
+ ["ui.prefersReducedMotion", 0],
+ ],
+ });
+ let screens = [];
+ // we need at least three screens to test the progress bar styling
+ for (let i = 0; i < 3; i++) {
+ screens.push(
+ makeTestContent(`TEST_MR_PROGRESS_BAR_${i + 1}`, {
+ position: "split",
+ progress_bar: true,
+ primary_button: {
+ label: "next",
+ action: {
+ navigate: true,
+ },
+ },
+ })
+ );
+ }
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ screens,
+ },
+ });
+ let browser = await openAboutWelcome(JSON.stringify(screens));
+
+ await SpecialPowers.spawn(browser, [], async () => {
+ const progressBar = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".progress-bar")
+ );
+ const indicator = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".indicator")
+ );
+ // Progress bar should have a gray background.
+ is(
+ content.window.getComputedStyle(progressBar)["background-color"],
+ "rgba(21, 20, 26, 0.25)",
+ "Correct progress bar background"
+ );
+
+ const indicatorStyles = content.window.getComputedStyle(indicator);
+ for (let [key, val] of Object.entries({
+ // The filled "completed" element should have
+ // `background-color: var(--checkbox-checked-bgcolor);`
+ "background-color": "rgb(0, 97, 224)",
+ // Base progress bar step styles.
+ height: "6px",
+ "margin-inline": "-1px",
+ "padding-block": "0px",
+ })) {
+ is(indicatorStyles[key], val, `Correct indicator ${key} style`);
+ }
+ const indicatorX = indicator.getBoundingClientRect().x;
+ content.document.querySelector("button.primary").click();
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(".indicator")?.getBoundingClientRect()
+ .x > indicatorX,
+ "Indicator should have grown"
+ );
+ });
+
+ await doExperimentCleanup();
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a message with session history updates disabled
+ */
+add_task(async function test_aboutwelcome_history_updates_disabled() {
+ let screens = [];
+ // we need at least two screens to test the history state
+ for (let i = 1; i < 3; i++) {
+ screens.push(makeTestContent(`TEST_PUSH_STATE_STEP_${i}`));
+ }
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ disableHistoryUpdates: true,
+ screens,
+ },
+ });
+ let browser = await openAboutWelcome(JSON.stringify(screens));
+
+ let startHistoryLength = await SpecialPowers.spawn(browser, [], () => {
+ return content.window.history.length;
+ });
+ // Advance to second screen
+ await onButtonClick(browser, "button.primary");
+ let endHistoryLength = await SpecialPowers.spawn(browser, [], async () => {
+ // Ensure next screen has rendered
+ await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".TEST_PUSH_STATE_STEP_2")
+ );
+ return content.window.history.length;
+ });
+
+ ok(
+ startHistoryLength === endHistoryLength,
+ "No entries added to the session's history stack with history updates disabled"
+ );
+
+ await doExperimentCleanup();
+ browser.closeBrowser();
+});
+
+/**
+ * Test rendering a screen with different logos depending on reduced motion and
+ * color scheme preferences
+ */
+add_task(async function test_aboutwelcome_logo_selection() {
+ // Test a screen config that includes every logo parameter
+ await testAboutWelcomeLogoFor({
+ imageURL: "chrome://branding/content/icon16.png",
+ darkModeImageURL: "chrome://branding/content/icon32.png",
+ reducedMotionImageURL: "chrome://branding/content/icon64.png",
+ darkModeReducedMotionImageURL: "chrome://branding/content/icon128.png",
+ alt: "TEST_LOGO_SELECTION_ALT",
+ height: "16px",
+ });
+ // Test a screen config with no animated/static logos
+ await testAboutWelcomeLogoFor({
+ imageURL: "chrome://branding/content/icon16.png",
+ darkModeImageURL: "chrome://branding/content/icon32.png",
+ });
+ // Test a screen config with no dark mode logos
+ await testAboutWelcomeLogoFor({
+ imageURL: "chrome://branding/content/icon16.png",
+ reducedMotionImageURL: "chrome://branding/content/icon64.png",
+ });
+ // Test a screen config that includes only the default logo
+ await testAboutWelcomeLogoFor({
+ imageURL: "chrome://branding/content/icon16.png",
+ });
+ // Test a screen config with no logos
+ await testAboutWelcomeLogoFor();
+});
+
+/**
+ * Test rendering a message that starts on a specific screen
+ */
+add_task(async function test_aboutwelcome_start_screen_configured() {
+ let startScreen = 1;
+ let screens = [];
+ // we need at least two screens to test
+ for (let i = 1; i < 3; i++) {
+ screens.push(makeTestContent(`TEST_START_STEP_${i}`));
+ }
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ enabled: true,
+ startScreen,
+ screens,
+ },
+ });
+
+ let sandbox = sinon.createSandbox();
+ let spy = sandbox.spy(AboutWelcomeTelemetry.prototype, "sendTelemetry");
+
+ let browser = await openAboutWelcome(JSON.stringify(screens));
+
+ let secondScreenShown = await SpecialPowers.spawn(browser, [], async () => {
+ // Ensure screen has rendered
+ await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".TEST_START_STEP_2")
+ );
+ return true;
+ });
+
+ ok(
+ secondScreenShown,
+ `Starts on second screen when configured with startScreen index equal to ${startScreen}`
+ );
+ // Wait for screen elements to render before checking impression pings
+ await test_screen_content(
+ browser,
+ "renders second screen elements",
+ // Expected selectors:
+ [`main.screen`, "div.secondary-cta"]
+ );
+
+ let expectedTelemetry = sinon.match({
+ event: "IMPRESSION",
+ message_id: `MR_WELCOME_DEFAULT_${startScreen}_TEST_START_STEP_${
+ startScreen + 1
+ }_${screens.map(({ id }) => id?.split("_")[1]?.[0]).join("")}`,
+ });
+ if (spy.calledWith(expectedTelemetry)) {
+ ok(
+ true,
+ "Impression events have the correct message id with start screen configured"
+ );
+ } else if (spy.called) {
+ ok(
+ false,
+ `Wrong telemetry sent: ${JSON.stringify(
+ spy.getCalls().map(c => c.args[0]),
+ null,
+ 2
+ )}`
+ );
+ } else {
+ ok(false, "No telemetry sent");
+ }
+
+ await doExperimentCleanup();
+ browser.closeBrowser();
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_fxa_signin_flow.js b/browser/components/newtab/test/browser/browser_aboutwelcome_fxa_signin_flow.js
new file mode 100644
index 0000000000..9de9acb7b3
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_fxa_signin_flow.js
@@ -0,0 +1,303 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { UIState } = ChromeUtils.importESModule(
+ "resource://services-sync/UIState.sys.mjs"
+);
+
+const TEST_ROOT = "https://example.com/";
+
+add_setup(async () => {
+ await SpecialPowers.pushPrefEnv({
+ set: [["identity.fxaccounts.remote.root", TEST_ROOT]],
+ });
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW special action resolves to `true` and
+ * closes the FxA sign-in tab if sign-in is successful.
+ */
+add_task(async function test_fxa_sign_success() {
+ let sandbox = sinon.createSandbox();
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ });
+ });
+ let fxaTab = await fxaTabPromise;
+ let fxaTabClosing = BrowserTestUtils.waitForTabClosing(fxaTab);
+
+ // We'll fake-out the UIState being in the STATUS_SIGNED_IN status
+ // and not test the actual FxA sign-in mechanism.
+ sandbox.stub(UIState, "get").returns({
+ status: UIState.STATUS_SIGNED_IN,
+ syncEnabled: true,
+ email: "email@example.com",
+ });
+
+ Services.obs.notifyObservers(null, UIState.ON_UPDATE);
+
+ await fxaTabClosing;
+ Assert.ok(true, "FxA tab automatically closed.");
+ let result = await resultPromise;
+ Assert.ok(result, "FXA_SIGNIN_FLOW action's result should be true");
+ });
+
+ sandbox.restore();
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action's data.autoClose parameter can
+ * disable the autoclose behavior.
+ */
+add_task(async function test_fxa_sign_success_no_autoclose() {
+ let sandbox = sinon.createSandbox();
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: { autoClose: false },
+ });
+ });
+ let fxaTab = await fxaTabPromise;
+
+ // We'll fake-out the UIState being in the STATUS_SIGNED_IN status
+ // and not test the actual FxA sign-in mechanism.
+ sandbox.stub(UIState, "get").returns({
+ status: UIState.STATUS_SIGNED_IN,
+ syncEnabled: true,
+ email: "email@example.com",
+ });
+
+ Services.obs.notifyObservers(null, UIState.ON_UPDATE);
+
+ let result = await resultPromise;
+ Assert.ok(result, "FXA_SIGNIN_FLOW should have resolved to true");
+ Assert.ok(!fxaTab.closing, "FxA tab was not asked to close.");
+ BrowserTestUtils.removeTab(fxaTab);
+ });
+
+ sandbox.restore();
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action resolves to `false` if the tab
+ * closes before sign-in completes.
+ */
+add_task(async function test_fxa_signin_aborted() {
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ });
+ });
+ let fxaTab = await fxaTabPromise;
+ Assert.ok(!fxaTab.closing, "FxA tab was not asked to close yet.");
+
+ BrowserTestUtils.removeTab(fxaTab);
+ let result = await resultPromise;
+ Assert.ok(!result, "FXA_SIGNIN_FLOW action's result should be false");
+ });
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action can open a separate window, if need
+ * be, and that if that window closes, the flow is considered aborted.
+ */
+add_task(async function test_fxa_signin_window_aborted() {
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaWindowPromise = BrowserTestUtils.waitForNewWindow();
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: {
+ where: "window",
+ },
+ });
+ });
+ let fxaWindow = await fxaWindowPromise;
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close yet.");
+
+ await BrowserTestUtils.closeWindow(fxaWindow);
+ let result = await resultPromise;
+ Assert.ok(!result, "FXA_SIGNIN_FLOW action's result should be false");
+ });
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action can open a separate window, if need
+ * be, and that if sign-in completes, that new window will close automatically.
+ */
+add_task(async function test_fxa_signin_window_success() {
+ let sandbox = sinon.createSandbox();
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaWindowPromise = BrowserTestUtils.waitForNewWindow();
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: {
+ where: "window",
+ },
+ });
+ });
+ let fxaWindow = await fxaWindowPromise;
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close yet.");
+
+ let windowClosed = BrowserTestUtils.windowClosed(fxaWindow);
+
+ // We'll fake-out the UIState being in the STATUS_SIGNED_IN status
+ // and not test the actual FxA sign-in mechanism.
+ sandbox.stub(UIState, "get").returns({
+ status: UIState.STATUS_SIGNED_IN,
+ syncEnabled: true,
+ email: "email@example.com",
+ });
+
+ Services.obs.notifyObservers(null, UIState.ON_UPDATE);
+
+ let result = await resultPromise;
+ Assert.ok(result, "FXA_SIGNIN_FLOW action's result should be true");
+
+ await windowClosed;
+ Assert.ok(fxaWindow.closed, "Sign-in window was automatically closed.");
+ });
+
+ sandbox.restore();
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action can open a separate window, if need
+ * be, and that if a new tab is opened in that window and the sign-in tab
+ * is closed:
+ *
+ * 1. The new window isn't closed
+ * 2. The sign-in is considered aborted.
+ */
+add_task(async function test_fxa_signin_window_multiple_tabs_aborted() {
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaWindowPromise = BrowserTestUtils.waitForNewWindow();
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: {
+ where: "window",
+ },
+ });
+ });
+ let fxaWindow = await fxaWindowPromise;
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close yet.");
+ let fxaTab = fxaWindow.gBrowser.selectedTab;
+ await BrowserTestUtils.openNewForegroundTab(
+ fxaWindow.gBrowser,
+ "about:blank"
+ );
+ BrowserTestUtils.removeTab(fxaTab);
+
+ let result = await resultPromise;
+ Assert.ok(!result, "FXA_SIGNIN_FLOW action's result should be false");
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close.");
+ await BrowserTestUtils.closeWindow(fxaWindow);
+ });
+});
+
+/**
+ * Tests that the FXA_SIGNIN_FLOW action can open a separate window, if need
+ * be, and that if a new tab is opened in that window but then sign-in
+ * completes
+ *
+ * 1. The new window isn't closed, but the sign-in tab is.
+ * 2. The sign-in is considered a success.
+ */
+add_task(async function test_fxa_signin_window_multiple_tabs_success() {
+ let sandbox = sinon.createSandbox();
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaWindowPromise = BrowserTestUtils.waitForNewWindow();
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: {
+ where: "window",
+ },
+ });
+ });
+ let fxaWindow = await fxaWindowPromise;
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close yet.");
+ let fxaTab = fxaWindow.gBrowser.selectedTab;
+
+ // This will open an about:blank tab in the background.
+ await BrowserTestUtils.addTab(fxaWindow.gBrowser);
+ let fxaTabClosed = BrowserTestUtils.waitForTabClosing(fxaTab);
+
+ // We'll fake-out the UIState being in the STATUS_SIGNED_IN status
+ // and not test the actual FxA sign-in mechanism.
+ sandbox.stub(UIState, "get").returns({
+ status: UIState.STATUS_SIGNED_IN,
+ syncEnabled: true,
+ email: "email@example.com",
+ });
+
+ Services.obs.notifyObservers(null, UIState.ON_UPDATE);
+
+ let result = await resultPromise;
+ Assert.ok(result, "FXA_SIGNIN_FLOW action's result should be true");
+ await fxaTabClosed;
+
+ Assert.ok(!fxaWindow.closed, "FxA window was not asked to close.");
+ await BrowserTestUtils.closeWindow(fxaWindow);
+ });
+
+ sandbox.restore();
+});
+
+/**
+ * Tests that we can pass an entrypoint and UTM parameters to the FxA sign-in
+ * page.
+ */
+add_task(async function test_fxa_signin_flow_entrypoint_utm_params() {
+ await BrowserTestUtils.withNewTab("about:welcome", async browser => {
+ let fxaTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
+ let resultPromise = SpecialPowers.spawn(browser, [], async () => {
+ return content.wrappedJSObject.AWSendToParent("SPECIAL_ACTION", {
+ type: "FXA_SIGNIN_FLOW",
+ data: {
+ entrypoint: "test-entrypoint",
+ extraParams: {
+ utm_test1: "utm_test1",
+ utm_test2: "utm_test2",
+ },
+ },
+ });
+ });
+ let fxaTab = await fxaTabPromise;
+
+ let uriParams = new URLSearchParams(fxaTab.linkedBrowser.currentURI.query);
+ Assert.equal(uriParams.get("entrypoint"), "test-entrypoint");
+ Assert.equal(uriParams.get("utm_test1"), "utm_test1");
+ Assert.equal(uriParams.get("utm_test2"), "utm_test2");
+
+ BrowserTestUtils.removeTab(fxaTab);
+ await resultPromise;
+ });
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_glean.js b/browser/components/newtab/test/browser/browser_aboutwelcome_glean.js
new file mode 100644
index 0000000000..2875c19b12
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_glean.js
@@ -0,0 +1,174 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for the Glean version of onboarding telemetry.
+ */
+
+const { AboutWelcomeTelemetry } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm"
+);
+
+const TEST_DEFAULT_CONTENT = [
+ {
+ id: "AW_STEP1",
+
+ content: {
+ position: "split",
+ title: "Step 1",
+ page: "page 1",
+ source: "test",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ secondary_button_top: {
+ label: "link top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: { entrypoint: "test" },
+ },
+ },
+ help_text: {
+ text: "Here's some sample help text",
+ },
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ position: "center",
+ title: "Step 2",
+ page: "page 1",
+ source: "test",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ has_noodles: true,
+ },
+ },
+];
+
+const TEST_DEFAULT_JSON = JSON.stringify(TEST_DEFAULT_CONTENT);
+
+async function openAboutWelcome() {
+ await setAboutWelcomePref(true);
+ await setAboutWelcomeMultiStage(TEST_DEFAULT_JSON);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+add_task(async function test_welcome_telemetry() {
+ const sandbox = sinon.createSandbox();
+ // Be sure to stub out PingCentre so it doesn't hit the network.
+ sandbox
+ .stub(AboutWelcomeTelemetry.prototype, "pingCentre")
+ .value({ sendStructuredIngestionPing: () => {} });
+
+ // Have to turn on AS telemetry for anything to be recorded.
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+ registerCleanupFunction(async () => {
+ await SpecialPowers.popPrefEnv();
+ });
+
+ Services.fog.testResetFOG();
+ // Let's check that there is nothing in the impression event.
+ // This is useful in mochitests because glean inits fairly late in startup.
+ // We want to make sure we are fully initialized during testing so that
+ // when we call testGetValue() we get predictable behavior.
+ Assert.equal(undefined, Glean.messagingSystem.messageId.testGetValue());
+
+ // Setup testBeforeNextSubmit. We do this first, progress onboarding, submit
+ // and then check submission. We put the asserts inside testBeforeNextSubmit
+ // because metric lifetimes are 'ping' and are cleared after submission.
+ // See: https://firefox-source-docs.mozilla.org/toolkit/components/glean/user/instrumentation_tests.html#xpcshell-tests
+ let pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+
+ const message = Glean.messagingSystem.messageId.testGetValue();
+ // Because of the asynchronous nature of receiving messages, we cannot
+ // guarantee that we will get the same message first. Instead we check
+ // that the one we get is a valid example of that type.
+ Assert.ok(
+ message.startsWith("MR_WELCOME_DEFAULT"),
+ "Ping is of an expected type"
+ );
+ Assert.equal(
+ Glean.messagingSystem.unknownKeyCount.testGetValue(),
+ undefined
+ );
+ });
+
+ let browser = await openAboutWelcome();
+ // `openAboutWelcome` isn't synchronous wrt the onboarding flow impressing.
+ await TestUtils.waitForCondition(
+ () => pingSubmitted,
+ "Ping was submitted, callback was called."
+ );
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ // Let's reset and assert some values in the next button click.
+ pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+
+ // Sometimes the impression for MR_WELCOME_DEFAULT_0_AW_STEP1_SS reaches
+ // the parent process before the button click does.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=1834620
+ if (Glean.messagingSystem.event.testGetValue() === "IMPRESSION") {
+ Assert.equal(
+ Glean.messagingSystem.eventPage.testGetValue(),
+ "about:welcome"
+ );
+ const message = Glean.messagingSystem.messageId.testGetValue();
+ Assert.ok(
+ message.startsWith("MR_WELCOME_DEFAULT"),
+ "Ping is of an expected type"
+ );
+ } else {
+ // This is the common and, to my mind, correct case:
+ // the click coming before the next steps' impression.
+ Assert.equal(Glean.messagingSystem.event.testGetValue(), "CLICK_BUTTON");
+ Assert.equal(
+ Glean.messagingSystem.eventSource.testGetValue(),
+ "primary_button"
+ );
+ Assert.equal(
+ Glean.messagingSystem.messageId.testGetValue(),
+ "MR_WELCOME_DEFAULT_0_AW_STEP1"
+ );
+ }
+ Assert.equal(
+ Glean.messagingSystem.unknownKeyCount.testGetValue(),
+ undefined
+ );
+ });
+ await onButtonClick(browser, "button.primary");
+ Assert.ok(pingSubmitted, "Ping was submitted, callback was called.");
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_import.js b/browser/components/newtab/test/browser/browser_aboutwelcome_import.js
new file mode 100644
index 0000000000..76716ec47f
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_import.js
@@ -0,0 +1,106 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+const IMPORT_SCREEN = {
+ id: "AW_IMPORT",
+ content: {
+ primary_button: {
+ label: "import",
+ action: {
+ navigate: true,
+ type: "SHOW_MIGRATION_WIZARD",
+ },
+ },
+ },
+};
+
+const FORCE_LEGACY =
+ Services.prefs.getCharPref(
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "default"
+ ) === "legacy";
+
+add_task(async function test_wait_import_modal() {
+ await setAboutWelcomeMultiStage(
+ JSON.stringify([IMPORT_SCREEN, { id: "AW_NEXT", content: {} }])
+ );
+ const { cleanup, browser } = await openMRAboutWelcome();
+
+ // execution
+ await test_screen_content(
+ browser,
+ "renders IMPORT screen",
+ //Expected selectors
+ ["main.AW_IMPORT", "button[value='primary_button']"],
+
+ //Unexpected selectors:
+ ["main.AW_NEXT"]
+ );
+
+ const wizardPromise = BrowserTestUtils.waitForMigrationWizard(
+ window,
+ FORCE_LEGACY
+ );
+ const prefsTab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:preferences"
+ );
+ await onButtonClick(browser, "button.primary");
+ const wizard = await wizardPromise;
+
+ await test_screen_content(
+ browser,
+ "still shows IMPORT screen",
+ //Expected selectors
+ ["main.AW_IMPORT", "button[value='primary_button']"],
+
+ //Unexpected selectors:
+ ["main.AW_NEXT"]
+ );
+
+ await BrowserTestUtils.closeMigrationWizard(wizard, FORCE_LEGACY);
+
+ await test_screen_content(
+ browser,
+ "moved to NEXT screen",
+ //Expected selectors
+ ["main.AW_NEXT"],
+
+ //Unexpected selectors:
+ []
+ );
+
+ // cleanup
+ await SpecialPowers.popPrefEnv(); // for setAboutWelcomeMultiStage
+ BrowserTestUtils.removeTab(prefsTab);
+ await cleanup();
+});
+
+add_task(async function test_wait_import_spotlight() {
+ const spotlightPromise = TestUtils.topicObserved("subdialog-loaded");
+ ChromeUtils.import(
+ "resource://activity-stream/lib/Spotlight.jsm"
+ ).Spotlight.showSpotlightDialog(gBrowser.selectedBrowser, {
+ content: { modal: "tab", screens: [IMPORT_SCREEN] },
+ });
+ const [win] = await spotlightPromise;
+
+ const wizardPromise = BrowserTestUtils.waitForMigrationWizard(
+ window,
+ FORCE_LEGACY
+ );
+ const prefsTab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:preferences"
+ );
+ win.document
+ .querySelector(".onboardingContainer button[value='primary_button']")
+ .click();
+ const wizard = await wizardPromise;
+
+ await BrowserTestUtils.closeMigrationWizard(wizard, FORCE_LEGACY);
+
+ // cleanup
+ BrowserTestUtils.removeTab(prefsTab);
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_mobile_downloads.js b/browser/components/newtab/test/browser/browser_aboutwelcome_mobile_downloads.js
new file mode 100644
index 0000000000..bb94d575fe
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_mobile_downloads.js
@@ -0,0 +1,112 @@
+"use strict";
+
+const BASE_CONTENT = {
+ id: "MOBILE_DOWNLOADS",
+ content: {
+ tiles: {
+ type: "mobile_downloads",
+ data: {
+ QR_code: {
+ image_url: "chrome://browser/content/assets/focus-qr-code.svg",
+ alt_text: "Test alt",
+ },
+ email: {
+ link_text: {
+ string_id: "spotlight-focus-promo-email-link",
+ },
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ },
+ },
+};
+
+async function openAboutWelcome(json) {
+ if (json) {
+ await setAboutWelcomeMultiStage(json);
+ }
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+const ALT_TEXT = BASE_CONTENT.content.tiles.data.QR_code.alt_text;
+
+/**
+ * Test rendering a screen with a mobile downloads tile
+ * including QR code, email, and marketplace elements
+ */
+add_task(async function test_aboutwelcome_mobile_downloads_all() {
+ const TEST_JSON = JSON.stringify([BASE_CONTENT]);
+ let browser = await openAboutWelcome(TEST_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with all mobile download elements",
+ // Expected selectors:
+ [
+ `img.qr-code-image[alt="${ALT_TEXT}"]`,
+ "ul.mobile-download-buttons",
+ "li.android",
+ "li.ios",
+ "button.email-link",
+ ]
+ );
+});
+
+/**
+ * Test rendering a screen with a mobile downloads tile
+ * including only a QR code and marketplace elements
+ */
+add_task(
+ async function test_aboutwelcome_mobile_downloads_qr_and_marketplace() {
+ const SCREEN_CONTENT = structuredClone(BASE_CONTENT);
+ delete SCREEN_CONTENT.content.tiles.data.email;
+ const TEST_JSON = JSON.stringify([SCREEN_CONTENT]);
+ let browser = await openAboutWelcome(TEST_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with QR code and marketplace badges",
+ // Expected selectors:
+ [
+ `img.qr-code-image[alt="${ALT_TEXT}"]`,
+ "ul.mobile-download-buttons",
+ "li.android",
+ "li.ios",
+ ],
+ // Unexpected selectors:
+ [`button.email-link`]
+ );
+ }
+);
+
+/**
+ * Test rendering a screen with a mobile downloads tile
+ * including only a QR code
+ */
+add_task(async function test_aboutwelcome_mobile_downloads_qr() {
+ let SCREEN_CONTENT = structuredClone(BASE_CONTENT);
+ const QR_CODE_SRC = SCREEN_CONTENT.content.tiles.data.QR_code.image_url;
+
+ delete SCREEN_CONTENT.content.tiles.data.email;
+ delete SCREEN_CONTENT.content.tiles.data.marketplace_buttons;
+ const TEST_JSON = JSON.stringify([SCREEN_CONTENT]);
+ let browser = await openAboutWelcome(TEST_JSON);
+
+ await test_screen_content(
+ browser,
+ "renders screen with QR code",
+ // Expected selectors:
+ [`img.qr-code-image[alt="${ALT_TEXT}"][src="${QR_CODE_SRC}"]`],
+ // Unexpected selectors:
+ ["button.email-link", "li.android", "li.ios"]
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_default.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_default.js
new file mode 100644
index 0000000000..9d578db93d
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_default.js
@@ -0,0 +1,736 @@
+"use strict";
+const { SpecialMessageActions } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs"
+);
+
+const DID_SEE_ABOUT_WELCOME_PREF = "trailhead.firstrun.didSeeAboutWelcome";
+
+const TEST_DEFAULT_CONTENT = [
+ {
+ id: "AW_STEP1",
+ content: {
+ position: "split",
+ title: "Step 1",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ secondary_button_top: {
+ label: "link top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: { entrypoint: "test" },
+ },
+ },
+ help_text: {
+ text: "Here's some sample help text",
+ },
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ position: "center",
+ title: "Step 2",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP3",
+ content: {
+ title: "Step 3",
+ 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: "Import",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: { source: "chrome" },
+ },
+ },
+ },
+ },
+ {
+ id: "AW_STEP4",
+ auto_advance: "primary_button",
+ content: {
+ title: "Step 4",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ },
+ },
+];
+
+const TEST_DEFAULT_JSON = JSON.stringify(TEST_DEFAULT_CONTENT);
+
+async function openAboutWelcome() {
+ await setAboutWelcomePref(true);
+ await setAboutWelcomeMultiStage(TEST_DEFAULT_JSON);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+/**
+ * Test the multistage welcome default UI
+ */
+add_task(async function test_multistage_aboutwelcome_default() {
+ const sandbox = sinon.createSandbox();
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "main.AW_STEP1",
+ "div.onboardingContainer",
+ "div.section-secondary",
+ "span.attrib-text",
+ "div.secondary-cta.top",
+ "div.steps",
+ "div.indicator.current",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "main.dialog-initial",
+ "main.dialog-last",
+ ]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+ let clickCall;
+ 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;
+ }
+ }
+
+ Assert.ok(
+ clickCall.args[1].message_id === "MR_WELCOME_DEFAULT_0_AW_STEP1",
+ "AboutWelcome MR message id joined with screen id"
+ );
+
+ await test_screen_content(
+ browser,
+ "multistage step 2",
+ // Expected selectors:
+ [
+ "main.AW_STEP2",
+ "div.onboardingContainer",
+ "div.section-main",
+ "div.steps",
+ "div.indicator.current",
+ "main.with-noodles",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP3",
+ "div.section-secondary",
+ "main.dialog-last",
+ ]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ // No 3rd screen to go to for win7.
+ if (win7Content) return;
+
+ await test_screen_content(
+ browser,
+ "multistage step 3",
+ // Expected selectors:
+ [
+ "main.AW_STEP3",
+ "div.onboardingContainer",
+ "div.section-main",
+ "div.tiles-theme-container",
+ "div.steps",
+ "div.indicator.current",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP2",
+ "main.AW_STEP1",
+ "div.section-secondary",
+ "main.dialog-initial",
+ "main.with-noodles",
+ "main.dialog-last",
+ ]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ await test_screen_content(
+ browser,
+ "multistage step 4",
+ // Expected selectors:
+ [
+ "main.AW_STEP4.screen-1",
+ "main.AW_STEP4.dialog-last",
+ "div.onboardingContainer",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP2",
+ "main.AW_STEP1",
+ "main.AW_STEP3",
+ "div.steps",
+ "main.dialog-initial",
+ "main.AW_STEP4.screen-0",
+ "main.AW_STEP4.screen-2",
+ "main.AW_STEP4.screen-3",
+ ]
+ );
+});
+
+/**
+ * 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 TestUtils.waitForCondition(() => browser.canGoBack);
+ browser.goBack();
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP1",
+ "div.secondary-cta",
+ "div.secondary-cta.top",
+ "button[value='secondary_button']",
+ "button[value='secondary_button_top']",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3"]
+ );
+
+ await document.getElementById("forward-button").click();
+});
+
+/**
+ * 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();
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button.primary");
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+
+ let clickCall;
+ 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: { mountStart: sinon.match.number },
+ })
+ ) {
+ performanceCall = call;
+ }
+ }
+
+ // 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,
+ "MR_WELCOME_DEFAULT",
+ "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,
+ "MR_WELCOME_DEFAULT_0_AW_STEP1",
+ "MessageId sent in click event telemetry"
+ );
+});
+
+add_task(async function test_AWMultistage_Secondary_Open_URL_Action() {
+ if (win7Content) return;
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.stub(aboutWelcomeActor, "onContentMessage").resolves(null);
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button[value='secondary_button_top']");
+ 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_top",
+ "secondary_top button click source recorded in Telemetry"
+ );
+});
+
+add_task(async function test_AWMultistage_Themes() {
+ // No theme screen to test for win7.
+ if (win7Content) return;
+
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ const sandbox = sinon.createSandbox();
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+ await onButtonClick(browser, "button.primary");
+
+ await test_screen_content(
+ browser,
+ "multistage proton step 2",
+ // Expected selectors:
+ ["main.AW_STEP2"],
+ // Unexpected selectors:
+ ["main.AW_STEP1"]
+ );
+ await onButtonClick(browser, "button.primary");
+
+ 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_can_restore_theme() {
+ const { XPIProvider } = ChromeUtils.import(
+ "resource://gre/modules/addons/XPIProvider.jsm"
+ );
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(() => sandbox.restore());
+
+ const fakeAddons = [];
+ class FakeAddon {
+ constructor({ id = "default-theme@mozilla.org", isActive = false } = {}) {
+ this.id = id;
+ this.isActive = isActive;
+ }
+ enable() {
+ for (let addon of fakeAddons) {
+ addon.isActive = false;
+ }
+ this.isActive = true;
+ }
+ }
+ fakeAddons.push(
+ new FakeAddon({ id: "fake-theme-1@mozilla.org", isActive: true }),
+ new FakeAddon({ id: "fake-theme-2@mozilla.org" })
+ );
+
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ sandbox.stub(XPIProvider, "getAddonsByTypes").resolves(fakeAddons);
+ sandbox
+ .stub(XPIProvider, "getAddonByID")
+ .callsFake(id => fakeAddons.find(addon => addon.id === id));
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+
+ // Test that the active theme ID is stored in LIGHT_WEIGHT_THEMES
+ await aboutWelcomeActor.receiveMessage({
+ name: "AWPage:GET_SELECTED_THEME",
+ });
+ Assert.equal(
+ await aboutWelcomeActor.onContentMessage.lastCall.returnValue,
+ "automatic",
+ `Should return "automatic" for non-built-in theme`
+ );
+
+ await aboutWelcomeActor.receiveMessage({
+ name: "AWPage:SELECT_THEME",
+ data: "AUTOMATIC",
+ });
+ Assert.equal(
+ XPIProvider.getAddonByID.lastCall.args[0],
+ fakeAddons[0].id,
+ `LIGHT_WEIGHT_THEMES.AUTOMATIC should be ${fakeAddons[0].id}`
+ );
+
+ // Enable a different theme...
+ fakeAddons[1].enable();
+ // And test that AWGetSelectedTheme updates the active theme ID
+ await aboutWelcomeActor.receiveMessage({
+ name: "AWPage:GET_SELECTED_THEME",
+ });
+ await aboutWelcomeActor.receiveMessage({
+ name: "AWPage:SELECT_THEME",
+ data: "AUTOMATIC",
+ });
+ Assert.equal(
+ XPIProvider.getAddonByID.lastCall.args[0],
+ fakeAddons[1].id,
+ `LIGHT_WEIGHT_THEMES.AUTOMATIC should be ${fakeAddons[1].id}`
+ );
+});
+
+add_task(async function test_AWMultistage_Import() {
+ // No import screen to test for win7.
+ if (win7Content) return;
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ // Click twice to advance to screen 3
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage proton step 2",
+ // Expected selectors:
+ ["main.AW_STEP2"],
+ // Unexpected selectors:
+ ["main.AW_STEP1"]
+ );
+ await onButtonClick(browser, "button.primary");
+
+ const sandbox = sinon.createSandbox();
+ sandbox.stub(SpecialMessageActions, "handleAction");
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await test_screen_content(
+ browser,
+ "multistage proton step 2",
+ // Expected selectors:
+ ["main.AW_STEP3"],
+ // Unexpected selectors:
+ ["main.AW_STEP2"]
+ );
+
+ await onButtonClick(browser, "button[value='secondary_button']");
+ 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"
+ );
+});
+
+add_task(async function test_updatesPrefOnAWOpen() {
+ Services.prefs.setBoolPref(DID_SEE_ABOUT_WELCOME_PREF, false);
+ await setAboutWelcomePref(true);
+
+ await openAboutWelcome();
+ await TestUtils.waitForCondition(
+ () =>
+ Services.prefs.getBoolPref(DID_SEE_ABOUT_WELCOME_PREF, false) === true,
+ "Updated pref to seen AW"
+ );
+ Services.prefs.clearUserPref(DID_SEE_ABOUT_WELCOME_PREF);
+});
+
+add_setup(async function () {
+ const sandbox = sinon.createSandbox();
+ // This needs to happen before any about:welcome page opens
+ sandbox.stub(FxAccounts.config, "promiseMetricsFlowURI").resolves("");
+ await setAboutWelcomeMultiStage("");
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+add_task(async function test_FxA_metricsFlowURI() {
+ let browser = await openAboutWelcome();
+
+ await ContentTask.spawn(browser, {}, async () => {
+ Assert.ok(
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector("div.onboardingContainer"),
+ "Wait for about:welcome to load"
+ ),
+ "about:welcome loaded"
+ );
+ });
+
+ Assert.ok(FxAccounts.config.promiseMetricsFlowURI.called, "Stub was called");
+ Assert.equal(
+ FxAccounts.config.promiseMetricsFlowURI.firstCall.args[0],
+ "aboutwelcome",
+ "Called by AboutWelcomeParent"
+ );
+
+ SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_send_aboutwelcome_as_page_in_event_telemetry() {
+ const sandbox = sinon.createSandbox();
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+
+ await onButtonClick(browser, "button.primary");
+
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+
+ 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("", { event: "CLICK_BUTTON" })) {
+ eventCall = call;
+ }
+ }
+
+ Assert.equal(
+ eventCall.args[1].event,
+ "CLICK_BUTTON",
+ "Event telemetry sent on primary button press"
+ );
+ Assert.equal(
+ eventCall.args[1].event_context.page,
+ "about:welcome",
+ "Event context page set to 'about:welcome' in event telemetry"
+ );
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_experimentAPI.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_experimentAPI.js
new file mode 100644
index 0000000000..fea1ca961a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_experimentAPI.js
@@ -0,0 +1,597 @@
+"use strict";
+
+const { ExperimentAPI } = ChromeUtils.importESModule(
+ "resource://nimbus/ExperimentAPI.sys.mjs"
+);
+const { ExperimentFakes } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+const { TelemetryTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/TelemetryTestUtils.sys.mjs"
+);
+
+const TEST_PROTON_CONTENT = [
+ {
+ id: "AW_STEP1",
+ content: {
+ title: "Step 1",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ secondary_button_top: {
+ label: "link top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: { entrypoint: "test" },
+ },
+ },
+ help_text: {
+ text: "Here's some sample help text",
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ title: "Step 2",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP3",
+ content: {
+ title: "Step 3",
+ 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: "Import",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: { source: "chrome" },
+ },
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP4",
+ content: {
+ title: "Step 4",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ has_noodles: true,
+ },
+ },
+];
+
+/**
+ * Test the zero onboarding using ExperimentAPI
+ */
+add_task(async function test_multistage_zeroOnboarding_experimentAPI() {
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: { enabled: false },
+ });
+
+ 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"]
+ );
+
+ await doExperimentCleanup();
+});
+
+/**
+ * Test the multistage welcome UI with test content theme as first screen
+ */
+add_task(async function test_multistage_aboutwelcome_experimentAPI() {
+ const TEST_CONTENT = [
+ {
+ id: "AW_STEP1",
+ content: {
+ 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",
+ },
+ secondary_button_top: {
+ label: "link top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: { entrypoint: "test" },
+ },
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ zap: true,
+ title: "Step 2 test",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ },
+ has_noodles: true,
+ },
+ },
+ {
+ id: "AW_STEP3",
+ content: {
+ logo: {},
+ title: "Step 3",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "Import",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: { source: "chrome" },
+ },
+ },
+ has_noodles: true,
+ },
+ },
+ ];
+ const sandbox = sinon.createSandbox();
+ NimbusFeatures.aboutwelcome._didSendExposureEvent = false;
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ enabled: true,
+ value: {
+ id: "my-mochitest-experiment",
+ screens: TEST_CONTENT,
+ },
+ });
+
+ sandbox.spy(ExperimentAPI, "recordExposureEvent");
+
+ Services.telemetry.clearScalars();
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ const browser = tab.linkedBrowser;
+
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ sandbox.restore();
+ });
+
+ // Test first (theme) screen for non-win7.
+ if (!win7Content) {
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP1",
+ "div.secondary-cta",
+ "div.secondary-cta.top",
+ "button[value='secondary_button']",
+ "button[value='secondary_button_top']",
+ "label.theme",
+ "input[type='radio']",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3", "div.tiles-container.info"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+ let clickCall;
+ 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;
+ }
+ }
+
+ Assert.equal(
+ clickCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "send telemetry event"
+ );
+
+ Assert.equal(
+ clickCall.args[1].message_id,
+ "MY-MOCHITEST-EXPERIMENT_0_AW_STEP1",
+ "Telemetry should join id defined in feature value with screen"
+ );
+ }
+
+ await test_screen_content(
+ browser,
+ "multistage step 2",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP2",
+ "button[value='secondary_button']",
+ ],
+ // 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",
+ "img.brand-logo",
+ "div.welcome-text",
+ ],
+ // 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"]
+ );
+
+ Assert.equal(
+ ExperimentAPI.recordExposureEvent.callCount,
+ 1,
+ "Called only once for exposure event"
+ );
+
+ const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
+ TelemetryTestUtils.assertKeyedScalar(
+ scalars,
+ "telemetry.event_counts",
+ "normandy#expose#nimbus_experiment",
+ 1
+ );
+
+ await doExperimentCleanup();
+});
+
+/**
+ * Test the multistage proton welcome UI using ExperimentAPI with transitions
+ */
+add_task(async function test_multistage_aboutwelcome_transitions() {
+ const sandbox = sinon.createSandbox();
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ id: "my-mochitest-experiment",
+ enabled: true,
+ screens: TEST_PROTON_CONTENT,
+ transitions: true,
+ },
+ });
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ const browser = tab.linkedBrowser;
+
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ sandbox.restore();
+ });
+
+ await test_screen_content(
+ browser,
+ "multistage proton step 1",
+ // Expected selectors:
+ ["div.proton.transition- .screen"],
+ // Unexpected selectors:
+ ["div.proton.transition-out"]
+ );
+
+ // Double click should still only transition once.
+ await onButtonClick(browser, "button.primary");
+ await onButtonClick(browser, "button.primary");
+
+ await test_screen_content(
+ browser,
+ "multistage proton step 1 transition to 2",
+ // Expected selectors:
+ ["div.proton.transition-out .screen", "div.proton.transition- .screen-1"]
+ );
+
+ await doExperimentCleanup();
+});
+
+/**
+ * Test the multistage proton welcome UI using ExperimentAPI without transitions
+ */
+add_task(async function test_multistage_aboutwelcome_transitions_off() {
+ const sandbox = sinon.createSandbox();
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ id: "my-mochitest-experiment",
+ enabled: true,
+ screens: TEST_PROTON_CONTENT,
+ transitions: false,
+ },
+ });
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ const browser = tab.linkedBrowser;
+
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ sandbox.restore();
+ });
+
+ await test_screen_content(
+ browser,
+ "multistage proton step 1",
+ // Expected selectors:
+ ["div.proton.transition- .screen"],
+ // Unexpected selectors:
+ ["div.proton.transition-out"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage proton step 1 no transition to 2",
+ // Expected selectors:
+ [],
+ // Unexpected selectors:
+ ["div.proton.transition-out .screen-0"]
+ );
+
+ await doExperimentCleanup();
+});
+
+/* Test multistage custom backdrop
+ */
+add_task(async function test_multistage_aboutwelcome_backdrop() {
+ const sandbox = sinon.createSandbox();
+ const TEST_BACKDROP = "blue";
+
+ const TEST_CONTENT = [
+ {
+ id: "TEST_SCREEN",
+ content: {
+ position: "split",
+ logo: {},
+ title: "test",
+ },
+ },
+ ];
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+ await pushPrefs(["browser.aboutwelcome.backdrop", TEST_BACKDROP]);
+
+ const doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ id: "my-mochitest-experiment",
+ screens: TEST_CONTENT,
+ },
+ });
+
+ const tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ const browser = tab.linkedBrowser;
+
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ sandbox.restore();
+ });
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [`div.outer-wrapper.onboardingContainer[style*='${TEST_BACKDROP}']`]
+ );
+
+ await doExperimentCleanup();
+});
+
+add_task(async function test_multistage_aboutwelcome_utm_term() {
+ const sandbox = sinon.createSandbox();
+
+ const TEST_CONTENT = [
+ {
+ id: "TEST_SCREEN",
+ content: {
+ position: "split",
+ logo: {},
+ title: "test",
+ secondary_button_top: {
+ label: "test",
+ style: "link",
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://www.mozilla.org/",
+ },
+ },
+ },
+ },
+ },
+ ];
+ await setAboutWelcomePref(true);
+ await ExperimentAPI.ready();
+
+ const doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: {
+ id: "my-mochitest-experiment",
+ screens: TEST_CONTENT,
+ UTMTerm: "test",
+ },
+ });
+
+ const tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ const browser = tab.linkedBrowser;
+ const aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ sandbox.stub(aboutWelcomeActor, "onContentMessage");
+
+ await onButtonClick(browser, "button[value='secondary_button_top']");
+
+ let actionCall;
+
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ 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;
+ }
+ }
+
+ Assert.equal(
+ actionCall.args[1].data.args,
+ "https://www.mozilla.org/?utm_source=activity-stream&utm_campaign=firstrun&utm_medium=referral&utm_term=test-screen",
+ "UTMTerm set in mobile"
+ );
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ BrowserTestUtils.removeTab(tab);
+ });
+
+ await doExperimentCleanup();
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_languageSwitcher.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_languageSwitcher.js
new file mode 100644
index 0000000000..55fab7ff00
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_languageSwitcher.js
@@ -0,0 +1,705 @@
+"use strict";
+
+const { getAddonAndLocalAPIsMocker } = ChromeUtils.importESModule(
+ "resource://testing-common/LangPackMatcherTestUtils.sys.mjs"
+);
+
+const { AWScreenUtils } = ChromeUtils.import(
+ "resource://activity-stream/lib/AWScreenUtils.jsm"
+);
+
+const sandbox = sinon.createSandbox();
+const mockAddonAndLocaleAPIs = getAddonAndLocalAPIsMocker(this, sandbox);
+add_task(function initSandbox() {
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+/**
+ * Spy specifically on the button click telemetry.
+ *
+ * The returned function flushes the spy of all of the matching button click events, and
+ * returns the events.
+ * @returns {() => TelemetryEvents[]}
+ */
+async function spyOnTelemetryButtonClicks(browser) {
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ return () => {
+ const result = aboutWelcomeActor.onContentMessage
+ .getCalls()
+ .filter(
+ call =>
+ call.args[0] === "AWPage:TELEMETRY_EVENT" &&
+ call.args[1]?.event === "CLICK_BUTTON"
+ )
+ // The second argument is the telemetry event.
+ .map(call => call.args[1]);
+
+ aboutWelcomeActor.onContentMessage.resetHistory();
+ return result;
+ };
+}
+
+async function openAboutWelcome() {
+ await pushPrefs(
+ // Speed up the tests by disabling transitions.
+ ["browser.aboutwelcome.transitions", false],
+ ["intl.multilingual.aboutWelcome.languageMismatchEnabled", true]
+ );
+ await setAboutWelcomePref(true);
+
+ // Stub out the doesAppNeedPin to false so the about:welcome pages do not attempt
+ // to pin the app.
+ const { ShellService } = ChromeUtils.importESModule(
+ "resource:///modules/ShellService.sys.mjs"
+ );
+ sandbox.stub(ShellService, "doesAppNeedPin").returns(false);
+
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ info("Opening about:welcome");
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ registerCleanupFunction(async () => {
+ BrowserTestUtils.removeTab(tab);
+ });
+
+ return {
+ browser: tab.linkedBrowser,
+ flushClickTelemetry: await spyOnTelemetryButtonClicks(tab.linkedBrowser),
+ };
+}
+
+async function clickVisibleButton(browser, selector) {
+ // eslint-disable-next-line no-shadow
+ await ContentTask.spawn(browser, { selector }, async ({ selector }) => {
+ function getVisibleElement() {
+ for (const el of content.document.querySelectorAll(selector)) {
+ if (el.offsetParent !== null) {
+ return el;
+ }
+ }
+ return null;
+ }
+
+ await ContentTaskUtils.waitForCondition(
+ getVisibleElement,
+ selector,
+ 200, // interval
+ 100 // maxTries
+ );
+ getVisibleElement().click();
+ });
+}
+
+/**
+ * Test that selectors are present and visible.
+ */
+async function testScreenContent(
+ browser,
+ name,
+ expectedSelectors = [],
+ unexpectedSelectors = []
+) {
+ await ContentTask.spawn(
+ browser,
+ { expectedSelectors, name, unexpectedSelectors },
+ async ({
+ expectedSelectors: expected,
+ name: experimentName,
+ unexpectedSelectors: unexpected,
+ }) => {
+ function selectorIsVisible(selector) {
+ const els = content.document.querySelectorAll(selector);
+ // The offsetParent will be null if element is hidden through "display: none;"
+ return [...els].some(el => el.offsetParent !== null);
+ }
+
+ for (let selector of expected) {
+ await ContentTaskUtils.waitForCondition(
+ () => selectorIsVisible(selector),
+ `Should render ${selector} in ${experimentName}`
+ );
+ }
+ for (let selector of unexpected) {
+ ok(
+ !selectorIsVisible(selector),
+ `Should not render ${selector} in ${experimentName}`
+ );
+ }
+ }
+ );
+}
+
+/**
+ * Report telemetry mismatches nicely.
+ */
+function eventsMatch(
+ actualEvents,
+ expectedEvents,
+ message = "Telemetry events match"
+) {
+ if (actualEvents.length !== expectedEvents.length) {
+ console.error("Events do not match");
+ console.error("Actual: ", JSON.stringify(actualEvents, null, 2));
+ console.error("Expected: ", JSON.stringify(expectedEvents, null, 2));
+ }
+ for (let i = 0; i < actualEvents.length; i++) {
+ const actualEvent = JSON.stringify(actualEvents[i], null, 2);
+ const expectedEvent = JSON.stringify(expectedEvents[i], null, 2);
+ if (actualEvent !== expectedEvent) {
+ console.error("Events do not match");
+ dump(`Actual: ${actualEvent}`);
+ dump("\n");
+ dump(`Expected: ${expectedEvent}`);
+ dump("\n");
+ }
+ ok(actualEvent === expectedEvent, message);
+ }
+}
+
+const liveLanguageSwitchSelectors = [
+ ".screen.AW_LANGUAGE_MISMATCH",
+ `[data-l10n-id*="onboarding-live-language"]`,
+ `[data-l10n-id="mr2022-onboarding-live-language-text"]`,
+];
+
+/**
+ * Accept the about:welcome offer to change the Firefox language when
+ * there is a mismatch between the operating system language and the Firefox
+ * language.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_accept() {
+ sandbox.restore();
+ const { resolveLangPacks, resolveInstaller, mockable } =
+ mockAddonAndLocaleAPIs({
+ systemLocale: "es-ES",
+ appLocale: "en-US",
+ });
+
+ const { browser, flushClickTelemetry } = await openAboutWelcome();
+ await testScreenContent(
+ browser,
+ "First Screen primary CTA loaded",
+ // Expected selectors:
+ [`button.primary[value="primary_button"]`],
+ // Unexpected selectors:
+ []
+ );
+
+ info("Clicking the primary button to start the onboarding process.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ await testScreenContent(
+ browser,
+ "Live language switching (waiting for languages)",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `[data-l10n-id="mr2022-onboarding-live-language-text"]`,
+ `button[disabled] [data-l10n-id="onboarding-live-language-waiting-button"]`,
+ `[data-l10n-id="mr2022-onboarding-secondary-skip-button-label"]`,
+ ],
+ // Unexpected selectors:
+ []
+ );
+
+ // Ignore the telemetry of the initial welcome screen.
+ flushClickTelemetry();
+
+ resolveLangPacks(["es-MX", "es-ES", "fr-FR"]);
+
+ await testScreenContent(
+ browser,
+ "Live language switching, asking for a language",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `button.primary[value="primary_button"]`,
+ `button.primary[value="decline"]`,
+ ],
+ // Unexpected selectors:
+ [
+ `button[disabled] [data-l10n-id="mr2022-onboarding-live-language-waiting-button"]`,
+ `[data-l10n-id="mr2022-onboarding-secondary-skip-button-label"]`,
+ ]
+ );
+
+ info("Clicking the primary button to view language switching page.");
+
+ await clickVisibleButton(browser, "button.primary");
+
+ await testScreenContent(
+ browser,
+ "Live language switching, waiting for langpack to download",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `[data-l10n-id="onboarding-live-language-button-label-downloading"]`,
+ `[data-l10n-id="onboarding-live-language-secondary-cancel-download"]`,
+ ],
+ // Unexpected selectors:
+ [
+ `button[disabled] [data-l10n-id="onboarding-live-language-waiting-button"]`,
+ ]
+ );
+
+ eventsMatch(flushClickTelemetry(), [
+ {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: "download_langpack",
+ page: "about:welcome",
+ },
+ message_id: "MR_WELCOME_DEFAULT_1_AW_LANGUAGE_MISMATCH",
+ },
+ ]);
+
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+
+ await resolveInstaller();
+
+ await testScreenContent(
+ browser,
+ "Language changed",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ liveLanguageSwitchSelectors
+ );
+
+ info("The app locale was changed to the OS locale.");
+ sinon.assert.calledWith(mockable.setRequestedAppLocales, ["es-ES", "en-US"]);
+
+ eventsMatch(flushClickTelemetry(), [
+ {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: "download_complete",
+ page: "about:welcome",
+ },
+ message_id: "MR_WELCOME_DEFAULT_1_AW_LANGUAGE_MISMATCH",
+ },
+ ]);
+});
+
+/**
+ * Test declining the about:welcome offer to change the Firefox language when
+ * there is a mismatch between the operating system language and the Firefox
+ * language.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_decline() {
+ sandbox.restore();
+ const { resolveLangPacks, resolveInstaller, mockable } =
+ mockAddonAndLocaleAPIs({
+ systemLocale: "es-ES",
+ appLocale: "en-US",
+ });
+
+ const { browser, flushClickTelemetry } = await openAboutWelcome();
+ await testScreenContent(
+ browser,
+ "First Screen primary CTA loaded",
+ // Expected selectors:
+ [`button.primary[value="primary_button"]`],
+ // Unexpected selectors:
+ []
+ );
+
+ info("Clicking the primary button to view language switching page.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ await testScreenContent(
+ browser,
+ "Live language switching (waiting for languages)",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `[data-l10n-id="mr2022-onboarding-live-language-text"]`,
+ `button[disabled] [data-l10n-id="onboarding-live-language-waiting-button"]`,
+ `[data-l10n-id="mr2022-onboarding-secondary-skip-button-label"]`,
+ ],
+ // Unexpected selectors:
+ []
+ );
+
+ // Ignore the telemetry of the initial welcome screen.
+ flushClickTelemetry();
+
+ resolveLangPacks(["es-MX", "es-ES", "fr-FR"]);
+ resolveInstaller();
+
+ await testScreenContent(
+ browser,
+ "Live language switching, asking for a language",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `button.primary[value="primary_button"]`,
+ `button.primary[value="decline"]`,
+ ],
+ // Unexpected selectors:
+ [
+ `button[disabled] [data-l10n-id="onboarding-live-language-waiting-button"]`,
+ `[data-l10n-id="mr2022-onboarding-secondary-skip-button-label"]`,
+ ]
+ );
+
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+
+ info("Clicking the secondary button to skip installing the langpack.");
+ await clickVisibleButton(browser, `button.primary[value="decline"]`);
+
+ await testScreenContent(
+ browser,
+ "Language selection declined",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ liveLanguageSwitchSelectors
+ );
+
+ info("The requested locale should be set to the original en-US");
+ sinon.assert.calledWith(mockable.setRequestedAppLocales, ["en-US"]);
+
+ eventsMatch(flushClickTelemetry(), [
+ {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: "decline",
+ page: "about:welcome",
+ },
+ message_id: "MR_WELCOME_DEFAULT_1_AW_LANGUAGE_MISMATCH",
+ },
+ ]);
+});
+
+/**
+ * Ensure the langpack can be installed before the user gets to the language screen.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_asyncCalls() {
+ sandbox.restore();
+ const { resolveLangPacks, resolveInstaller, mockable } =
+ mockAddonAndLocaleAPIs({
+ systemLocale: "es-ES",
+ appLocale: "en-US",
+ });
+
+ await openAboutWelcome();
+
+ info("Waiting for getAvailableLangpacks to be called.");
+ await TestUtils.waitForCondition(
+ () => mockable.getAvailableLangpacks.called,
+ "getAvailableLangpacks called once"
+ );
+ ok(mockable.installLangPack.notCalled);
+
+ resolveLangPacks(["es-MX", "es-ES", "fr-FR"]);
+
+ await TestUtils.waitForCondition(
+ () => mockable.installLangPack.called,
+ "installLangPack was called once"
+ );
+ ok(mockable.getAvailableLangpacks.called);
+
+ resolveInstaller();
+});
+
+/**
+ * Test that the "en-US" langpack is installed, if it's already available as the last
+ * fallback locale.
+ */
+add_task(async function test_aboutwelcome_fallback_locale() {
+ sandbox.restore();
+ const { resolveLangPacks, resolveInstaller, mockable } =
+ mockAddonAndLocaleAPIs({
+ systemLocale: "en-US",
+ appLocale: "it",
+ });
+
+ await openAboutWelcome();
+
+ info("Waiting for getAvailableLangpacks to be called.");
+ await TestUtils.waitForCondition(
+ () => mockable.getAvailableLangpacks.called,
+ "getAvailableLangpacks called once"
+ );
+ ok(mockable.installLangPack.notCalled);
+
+ resolveLangPacks(["en-US"]);
+
+ await TestUtils.waitForCondition(
+ () => mockable.installLangPack.called,
+ "installLangPack was called once"
+ );
+ ok(mockable.getAvailableLangpacks.called);
+
+ resolveInstaller();
+});
+
+/**
+ * Test when AMO does not have a matching language.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_noMatch() {
+ sandbox.restore();
+ const { resolveLangPacks, mockable } = mockAddonAndLocaleAPIs({
+ systemLocale: "tlh", // Klingon
+ appLocale: "en-US",
+ });
+
+ const { browser } = await openAboutWelcome();
+
+ info("Clicking the primary button to start installing the langpack.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ // Klingon is not supported.
+ resolveLangPacks(["es-MX", "es-ES", "fr-FR"]);
+
+ await testScreenContent(
+ browser,
+ "Language selection skipped",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ [
+ `[data-l10n-id*="onboarding-live-language"]`,
+ `[data-l10n-id="onboarding-live-language-header"]`,
+ ]
+ );
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+});
+
+/**
+ * Test when bidi live reloading is not supported.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_bidiNotSupported() {
+ sandbox.restore();
+ await pushPrefs(["intl.multilingual.liveReloadBidirectional", false]);
+
+ const { mockable } = mockAddonAndLocaleAPIs({
+ systemLocale: "ar-EG", // Arabic (Egypt)
+ appLocale: "en-US",
+ });
+
+ const { browser } = await openAboutWelcome();
+
+ info("Clicking the primary button to start installing the langpack.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ await testScreenContent(
+ browser,
+ "Language selection skipped for bidi",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ [
+ `[data-l10n-id*="onboarding-live-language"]`,
+ `[data-l10n-id="onboarding-live-language-header"]`,
+ ]
+ );
+
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+});
+
+/**
+ * Test when bidi live reloading is not supported and no langpacks.
+ */
+add_task(
+ async function test_aboutwelcome_languageSwitcher_bidiNotSupported_noLangPacks() {
+ sandbox.restore();
+ await pushPrefs(["intl.multilingual.liveReloadBidirectional", false]);
+
+ const { resolveLangPacks, mockable } = mockAddonAndLocaleAPIs({
+ systemLocale: "ar-EG", // Arabic (Egypt)
+ appLocale: "en-US",
+ });
+ resolveLangPacks([]);
+
+ const { browser } = await openAboutWelcome();
+
+ info("Clicking the primary button to start installing the langpack.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ await testScreenContent(
+ browser,
+ "Language selection skipped for bidi",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ [
+ `[data-l10n-id*="onboarding-live-language"]`,
+ `[data-l10n-id="onboarding-live-language-header"]`,
+ ]
+ );
+
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+ }
+);
+
+/**
+ * Test when bidi live reloading is supported.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_bidiNotSupported() {
+ sandbox.restore();
+ await pushPrefs(["intl.multilingual.liveReloadBidirectional", true]);
+
+ const { resolveLangPacks, mockable } = mockAddonAndLocaleAPIs({
+ systemLocale: "ar-EG", // Arabic (Egypt)
+ appLocale: "en-US",
+ });
+
+ const { browser } = await openAboutWelcome();
+
+ info("Clicking the primary button to start installing the langpack.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ resolveLangPacks(["ar-EG", "es-ES", "fr-FR"]);
+
+ await testScreenContent(
+ browser,
+ "Live language switching with bidi supported",
+ // Expected selectors:
+ [...liveLanguageSwitchSelectors],
+ // Unexpected selectors:
+ []
+ );
+
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+});
+
+/**
+ * Test hitting the cancel button when waiting on a langpack.
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_cancelWaiting() {
+ sandbox.restore();
+ const { resolveLangPacks, resolveInstaller, mockable } =
+ mockAddonAndLocaleAPIs({
+ systemLocale: "es-ES",
+ appLocale: "en-US",
+ });
+
+ const { browser, flushClickTelemetry } = await openAboutWelcome();
+
+ info("Clicking the primary button to start the onboarding process.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+ resolveLangPacks(["es-MX", "es-ES", "fr-FR"]);
+
+ await testScreenContent(
+ browser,
+ "Live language switching, asking for a language",
+ // Expected selectors:
+ liveLanguageSwitchSelectors,
+ // Unexpected selectors:
+ []
+ );
+
+ info("Clicking the primary button to view language switching page.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ await testScreenContent(
+ browser,
+ "Live language switching, waiting for langpack to download",
+ // Expected selectors:
+ [
+ ...liveLanguageSwitchSelectors,
+ `[data-l10n-id="onboarding-live-language-button-label-downloading"]`,
+ `[data-l10n-id="onboarding-live-language-secondary-cancel-download"]`,
+ ],
+ // Unexpected selectors:
+ [
+ `button[disabled] [data-l10n-id="onboarding-live-language-waiting-button"]`,
+ ]
+ );
+
+ // Ignore all the telemetry up to this point.
+ flushClickTelemetry();
+
+ info("Cancel the request for the language");
+ await clickVisibleButton(browser, "button.secondary");
+
+ await testScreenContent(
+ browser,
+ "Language selection declined waiting",
+ // Expected selectors:
+ [`.screen.AW_IMPORT_SETTINGS`],
+ // Unexpected selectors:
+ liveLanguageSwitchSelectors
+ );
+
+ eventsMatch(flushClickTelemetry(), [
+ {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: "cancel_waiting",
+ page: "about:welcome",
+ },
+ message_id: "MR_WELCOME_DEFAULT_1_AW_LANGUAGE_MISMATCH",
+ },
+ ]);
+
+ await resolveInstaller();
+
+ is(flushClickTelemetry().length, 0);
+ sinon.assert.notCalled(mockable.setRequestedAppLocales);
+});
+
+/**
+ * Test MR About Welcome language mismatch screen
+ */
+add_task(async function test_aboutwelcome_languageSwitcher_MR() {
+ sandbox.restore();
+
+ const { resolveLangPacks, resolveInstaller } = mockAddonAndLocaleAPIs({
+ systemLocale: "es-ES",
+ appLocale: "en-US",
+ });
+
+ const { browser } = await openAboutWelcome(true);
+
+ info("Clicking the primary button to view language switching screen.");
+ await clickVisibleButton(browser, `button.primary[value="primary_button"]`);
+
+ resolveLangPacks(["es-AR"]);
+ await testScreenContent(
+ browser,
+ "Live language switching, asking for a language",
+ // Expected selectors:
+ [
+ `#mainContentHeader[data-l10n-id="mr2022-onboarding-live-language-text"]`,
+ `[data-l10n-id="mr2022-language-mismatch-subtitle"]`,
+ `.section-secondary [data-l10n-id="mr2022-onboarding-live-language-text"]`,
+ `[data-l10n-id="mr2022-onboarding-live-language-switch-to"]`,
+ `button.primary[value="primary_button"]`,
+ `button.primary[value="decline"]`,
+ ],
+ // Unexpected selectors:
+ [`[data-l10n-id="onboarding-live-language-header"]`]
+ );
+
+ await resolveInstaller();
+ await testScreenContent(
+ browser,
+ "Switched some to langpack (raw) strings after install",
+ // Expected selectors:
+ [`#mainContentHeader[data-l10n-id="mr2022-onboarding-live-language-text"]`],
+ // Unexpected selectors:
+ [
+ `.section-secondary [data-l10n-id="mr2022-onboarding-live-language-text"]`,
+ `[data-l10n-id="mr2022-onboarding-live-language-switch-to"]`,
+ ]
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_mr.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_mr.js
new file mode 100644
index 0000000000..145d157e1a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_mr.js
@@ -0,0 +1,621 @@
+"use strict";
+
+const { AboutWelcomeParent } = ChromeUtils.import(
+ "resource:///actors/AboutWelcomeParent.jsm"
+);
+
+const { AboutWelcomeTelemetry } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm"
+);
+const { AWScreenUtils } = ChromeUtils.import(
+ "resource://activity-stream/lib/AWScreenUtils.jsm"
+);
+const { InternalTestingProfileMigrator } = ChromeUtils.importESModule(
+ "resource:///modules/InternalTestingProfileMigrator.sys.mjs"
+);
+
+async function clickVisibleButton(browser, selector) {
+ // eslint-disable-next-line no-shadow
+ await ContentTask.spawn(browser, { selector }, async ({ selector }) => {
+ function getVisibleElement() {
+ for (const el of content.document.querySelectorAll(selector)) {
+ if (el.offsetParent !== null) {
+ return el;
+ }
+ }
+ return null;
+ }
+ await ContentTaskUtils.waitForCondition(
+ getVisibleElement,
+ selector,
+ 200, // interval
+ 100 // maxTries
+ );
+ getVisibleElement().click();
+ });
+}
+
+add_setup(async function () {
+ SpecialPowers.pushPrefEnv({
+ set: [
+ ["ui.prefersReducedMotion", 1],
+ ["browser.aboutwelcome.transitions", false],
+ ],
+ });
+});
+
+function initSandbox({ pin = true, isDefault = false } = {}) {
+ const sandbox = sinon.createSandbox();
+ sandbox.stub(AboutWelcomeParent, "doesAppNeedPin").returns(pin);
+ sandbox.stub(AboutWelcomeParent, "isDefaultBrowser").returns(isDefault);
+
+ return sandbox;
+}
+
+/**
+ * Test MR message telemetry
+ */
+add_task(async function test_aboutwelcome_mr_template_telemetry() {
+ const sandbox = initSandbox();
+
+ let { browser, cleanup } = await openMRAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent's Content Message Handler
+ const messageStub = sandbox.spy(aboutWelcomeActor, "onContentMessage");
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+
+ const { callCount } = messageStub;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+ let clickCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = messageStub.getCall(i);
+ info(`Call #${i}: ${call.args[0]} ${JSON.stringify(call.args[1])}`);
+ if (call.calledWithMatch("", { event: "CLICK_BUTTON" })) {
+ clickCall = call;
+ }
+ }
+
+ Assert.ok(
+ clickCall.args[1].message_id.startsWith("MR_WELCOME_DEFAULT"),
+ "Telemetry includes MR message id"
+ );
+
+ await cleanup();
+ sandbox.restore();
+});
+
+/**
+ * Telemetry Impression with Pin as First Screen
+ */
+add_task(async function test_aboutwelcome_pin_screen_impression() {
+ await pushPrefs(["browser.shell.checkDefaultBrowser", true]);
+
+ const sandbox = initSandbox();
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ let impressionSpy = sandbox.spy(
+ AboutWelcomeTelemetry.prototype,
+ "sendTelemetry"
+ );
+
+ let { browser, cleanup } = await openMRAboutWelcome();
+ // Wait for screen elements to render before checking impression pings
+ await test_screen_content(
+ browser,
+ "Onboarding screen elements rendered",
+ // Expected selectors:
+ [
+ `main.screen[pos="split"]`,
+ "div.secondary-cta.top",
+ "button[value='secondary_button_top']",
+ ]
+ );
+
+ const { callCount } = impressionSpy;
+ ok(callCount >= 1, `${callCount} impressionSpy was called`);
+ let impressionCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = impressionSpy.getCall(i);
+ info(`Call #${i}: ${JSON.stringify(call.args[0])}`);
+ if (
+ call.calledWithMatch({ event: "IMPRESSION" }) &&
+ !call.calledWithMatch({ message_id: "MR_WELCOME_DEFAULT" })
+ ) {
+ info(`Screen Impression Call #${i}: ${JSON.stringify(call.args[0])}`);
+ impressionCall = call;
+ }
+ }
+
+ Assert.ok(
+ impressionCall.args[0].message_id.startsWith(
+ "MR_WELCOME_DEFAULT_0_AW_PIN_FIREFOX_P"
+ ),
+ "Impression telemetry includes correct message id"
+ );
+ await cleanup();
+ sandbox.restore();
+ await popPrefs();
+});
+
+/**
+ * Test MR template content - Browser is not Pinned and not set as default
+ */
+add_task(async function test_aboutwelcome_mr_template_content() {
+ await pushPrefs(["browser.shell.checkDefaultBrowser", true]);
+
+ const sandbox = initSandbox();
+
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ let { cleanup, browser } = await openMRAboutWelcome();
+
+ await test_screen_content(
+ browser,
+ "MR template includes screens with split position and a sign in link on the first screen",
+ // Expected selectors:
+ [
+ `main.screen[pos="split"]`,
+ "div.secondary-cta.top",
+ "button[value='secondary_button_top']",
+ ]
+ );
+
+ await test_screen_content(
+ browser,
+ "renders pin screen",
+ //Expected selectors:
+ ["main.AW_PIN_FIREFOX"],
+ //Unexpected selectors:
+ ["main.AW_GRATITUDE"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+
+ //should render set default
+ await test_screen_content(
+ browser,
+ "renders set default screen",
+ //Expected selectors:
+ ["main.AW_SET_DEFAULT"],
+ //Unexpected selectors:
+ ["main.AW_CHOOSE_THEME"]
+ );
+
+ await cleanup();
+ sandbox.restore();
+ await popPrefs();
+});
+
+/**
+ * Test MR template content - Browser has been set as Default, not pinned
+ */
+add_task(async function test_aboutwelcome_mr_template_content_pin() {
+ await pushPrefs(["browser.shell.checkDefaultBrowser", true]);
+
+ const sandbox = initSandbox({ isDefault: true });
+
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ let { browser, cleanup } = await openMRAboutWelcome();
+
+ await test_screen_content(
+ browser,
+ "renders pin screen",
+ //Expected selectors:
+ ["main.AW_PIN_FIREFOX"],
+ //Unexpected selectors:
+ ["main.AW_SET_DEFAULT"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+
+ await test_screen_content(
+ browser,
+ "renders next screen",
+ //Expected selectors:
+ ["main"],
+ //Unexpected selectors:
+ ["main.AW_SET_DEFAULT"]
+ );
+
+ await cleanup();
+ sandbox.restore();
+ await popPrefs();
+});
+
+/**
+ * Test MR template content - Browser is Pinned, not default
+ */
+add_task(async function test_aboutwelcome_mr_template_only_default() {
+ await pushPrefs(["browser.shell.checkDefaultBrowser", true]);
+
+ const sandbox = initSandbox({ pin: false });
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ let { browser, cleanup } = await openMRAboutWelcome();
+ //should render set default
+ await test_screen_content(
+ browser,
+ "renders set default screen",
+ //Expected selectors:
+ ["main.AW_ONLY_DEFAULT"],
+ //Unexpected selectors:
+ ["main.AW_PIN_FIREFOX"]
+ );
+
+ await cleanup();
+ sandbox.restore();
+ await popPrefs();
+});
+/**
+ * Test MR template content - Browser is Pinned and set as default
+ */
+add_task(async function test_aboutwelcome_mr_template_get_started() {
+ await pushPrefs(["browser.shell.checkDefaultBrowser", true]);
+
+ const sandbox = initSandbox({ pin: false, isDefault: true });
+
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .resolves(true)
+ .withArgs(
+ "os.windowsBuildNumber >= 15063 && !isDefaultBrowser && !doesAppNeedPin"
+ )
+ .resolves(false)
+ .withArgs("isDeviceMigration")
+ .resolves(false);
+
+ let { browser, cleanup } = await openMRAboutWelcome();
+
+ //should render set default
+ await test_screen_content(
+ browser,
+ "doesn't render pin and set default screens",
+ //Expected selectors:
+ ["main.AW_GET_STARTED"],
+ //Unexpected selectors:
+ ["main.AW_PIN_FIREFOX", "main.AW_ONLY_DEFAULT"]
+ );
+
+ await cleanup();
+ sandbox.restore();
+ await popPrefs();
+});
+
+add_task(async function test_aboutwelcome_gratitude() {
+ const TEST_CONTENT = [
+ {
+ id: "AW_GRATITUDE",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-228px",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-gratitude.svg') var(--mr-secondary-position) no-repeat, var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-gratitude-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-gratitude-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-gratitude-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ];
+ await setAboutWelcomeMultiStage(JSON.stringify(TEST_CONTENT)); // NB: calls SpecialPowers.pushPrefEnv
+ let { cleanup, browser } = await openMRAboutWelcome();
+
+ // execution
+ await test_screen_content(
+ browser,
+ "doesn't render secondary button on gratitude screen",
+ //Expected selectors
+ ["main.AW_GRATITUDE", "button[value='primary_button']"],
+
+ //Unexpected selectors:
+ ["button[value='secondary_button']"]
+ );
+ await clickVisibleButton(browser, ".action-buttons button.primary");
+
+ // make sure the button navigates to newtab
+ await test_screen_content(
+ browser,
+ "home",
+ //Expected selectors
+ ["body.activity-stream"],
+
+ //Unexpected selectors:
+ ["main.AW_GRATITUDE"]
+ );
+
+ // cleanup
+ await SpecialPowers.popPrefEnv(); // for setAboutWelcomeMultiStage
+ await cleanup();
+});
+
+add_task(async function test_aboutwelcome_embedded_migration() {
+ // Let's make sure at least one migrator is available and enabled - the
+ // InternalTestingProfileMigrator.
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.migrate.internal-testing.enabled", true]],
+ });
+
+ const sandbox = sinon.createSandbox();
+ sandbox
+ .stub(InternalTestingProfileMigrator.prototype, "getResources")
+ .callsFake(() =>
+ Promise.resolve([
+ {
+ type: MigrationUtils.resourceTypes.BOOKMARKS,
+ migrate: () => {},
+ },
+ ])
+ );
+ sandbox.stub(MigrationUtils, "_importQuantities").value({
+ bookmarks: 123,
+ history: 123,
+ logins: 123,
+ });
+ const migrated = new Promise(resolve => {
+ sandbox
+ .stub(InternalTestingProfileMigrator.prototype, "migrate")
+ .callsFake((aResourceTypes, aStartup, aProfile, aProgressCallback) => {
+ aProgressCallback(MigrationUtils.resourceTypes.BOOKMARKS);
+ Services.obs.notifyObservers(null, "Migration:Ended");
+ resolve();
+ });
+ });
+
+ let telemetrySpy = sandbox.spy(
+ AboutWelcomeTelemetry.prototype,
+ "sendTelemetry"
+ );
+
+ const TEST_CONTENT = [
+ {
+ id: "AW_IMPORT_SETTINGS_EMBEDDED",
+ content: {
+ tiles: { type: "migration-wizard" },
+ position: "split",
+ split_narrow_bkg_position: "-42px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-import-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-import.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ migrate_start: {
+ action: {},
+ },
+ migrate_close: {
+ action: { navigate: true },
+ },
+ secondary_button: {
+ label: {
+ string_id: "mr2022-onboarding-secondary-skip-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ },
+ {
+ id: "AW_STEP2",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-228px",
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-gratitude.svg') var(--mr-secondary-position) no-repeat, var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: {
+ string_id: "mr2022-onboarding-gratitude-title",
+ },
+ subtitle: {
+ string_id: "mr2022-onboarding-gratitude-subtitle",
+ },
+ primary_button: {
+ label: {
+ string_id: "mr2022-onboarding-gratitude-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ];
+
+ await setAboutWelcomeMultiStage(JSON.stringify(TEST_CONTENT)); // NB: calls SpecialPowers.pushPrefEnv
+ let { cleanup, browser } = await openMRAboutWelcome();
+
+ // execution
+ await test_screen_content(
+ browser,
+ "Renders a <migration-wizard> custom element",
+ // We expect <migration-wizard> to automatically request the set of migrators
+ // upon binding to the DOM, and to not be in dialog mode.
+ [
+ "main.AW_IMPORT_SETTINGS_EMBEDDED",
+ "migration-wizard[auto-request-state]:not([dialog-mode])",
+ ]
+ );
+
+ // Do a basic test to make sure that the <migration-wizard> is on the right
+ // page and the <panel-list> can open.
+ await SpecialPowers.spawn(
+ browser,
+ [`panel-item[key="${InternalTestingProfileMigrator.key}"]`],
+ async menuitemSelector => {
+ const { MigrationWizardConstants } = ChromeUtils.importESModule(
+ "chrome://browser/content/migration/migration-wizard-constants.mjs"
+ );
+
+ let wizard = content.document.querySelector("migration-wizard");
+ await new Promise(resolve => content.requestAnimationFrame(resolve));
+ let shadow = wizard.openOrClosedShadowRoot;
+ let deck = shadow.querySelector("#wizard-deck");
+
+ // It's unlikely but possible that the deck might not yet be showing the
+ // selection page yet, in which case we wait for that page to appear.
+ if (deck.selectedViewName !== MigrationWizardConstants.PAGES.SELECTION) {
+ await ContentTaskUtils.waitForMutationCondition(
+ deck,
+ { attributeFilter: ["selected-view"] },
+ () => {
+ return (
+ deck.getAttribute("selected-view") ===
+ `page-${MigrationWizardConstants.PAGES.SELECTION}`
+ );
+ }
+ );
+ }
+
+ Assert.ok(true, "Selection page is being shown in the migration wizard.");
+
+ // Now let's make sure that the <panel-list> can appear.
+ let panelList = wizard.querySelector("panel-list");
+ Assert.ok(panelList, "Found the <panel-list>.");
+
+ // The "shown" event from the panel-list is coming from a lower level
+ // of privilege than where we're executing this SpecialPowers.spawn
+ // task. In order to properly listen for it, we have to ask
+ // ContentTaskUtils.waitForEvent to listen for untrusted events.
+ let shown = ContentTaskUtils.waitForEvent(
+ panelList,
+ "shown",
+ false /* capture */,
+ null /* checkFn */,
+ true /* wantsUntrusted */
+ );
+ let selector = shadow.querySelector("#browser-profile-selector");
+
+ // The migration wizard programmatically focuses the selector after
+ // the selection page is shown using an rAF. If we click the button
+ // before that occurs, then the focus can shift after the panel opens
+ // which will cause it to immediately close again. So we wait for the
+ // selection button to gain focus before continuing.
+ if (!selector.matches(":focus")) {
+ await ContentTaskUtils.waitForEvent(selector, "focus");
+ }
+
+ selector.click();
+ await shown;
+
+ let panelRect = panelList.getBoundingClientRect();
+ let selectorRect = selector.getBoundingClientRect();
+
+ // Recalculate the <panel-list> rect top value relative to the top-left
+ // of the selectorRect. We expect the <panel-list> to be tightly anchored
+ // to the bottom of the <button>, so we expect this new value to be close to 0,
+ // to account for subpixel rounding
+ let panelTopLeftRelativeToAnchorTopLeft =
+ panelRect.top - selectorRect.top - selectorRect.height;
+
+ function isfuzzy(actual, expected, epsilon, msg) {
+ if (actual >= expected - epsilon && actual <= expected + epsilon) {
+ ok(true, msg);
+ } else {
+ is(actual, expected, msg);
+ }
+ }
+
+ isfuzzy(
+ panelTopLeftRelativeToAnchorTopLeft,
+ 0,
+ 1,
+ "Panel should be tightly anchored to the bottom of the button shadow node."
+ );
+
+ let panelItem = wizard.querySelector(menuitemSelector);
+ panelItem.click();
+
+ let importButton = shadow.querySelector("#import");
+ importButton.click();
+ }
+ );
+
+ await migrated;
+ Assert.ok(
+ telemetrySpy.calledWithMatch({
+ event: "CLICK_BUTTON",
+ event_context: { source: "primary_button", page: "about:welcome" },
+ message_id: sinon.match.string,
+ }),
+ "Should have sent telemetry for clicking the 'Import' button."
+ );
+
+ await SpecialPowers.spawn(browser, [], async () => {
+ let wizard = content.document.querySelector("migration-wizard");
+ let shadow = wizard.openOrClosedShadowRoot;
+ let continueButton = shadow.querySelector(
+ "div[name='page-progress'] .continue-button"
+ );
+ continueButton.click();
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector("main.AW_STEP2"),
+ "Waiting for step 2 to render"
+ );
+ });
+
+ Assert.ok(
+ telemetrySpy.calledWithMatch({
+ event: "CLICK_BUTTON",
+ event_context: { source: "migrate_close", page: "about:welcome" },
+ message_id: sinon.match.string,
+ }),
+ "Should have sent telemetry for clicking the 'Continue' button."
+ );
+
+ // cleanup
+ await SpecialPowers.popPrefEnv(); // for the InternalTestingProfileMigrator.
+ await SpecialPowers.popPrefEnv(); // for setAboutWelcomeMultiStage
+ await cleanup();
+ sandbox.restore();
+ let migrator = await MigrationUtils.getMigrator(
+ InternalTestingProfileMigrator.key
+ );
+ migrator.flushResourceCache();
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_video.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_video.js
new file mode 100644
index 0000000000..ed331e6752
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage_video.js
@@ -0,0 +1,97 @@
+"use strict";
+
+const { PermissionTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/PermissionTestUtils.sys.mjs"
+);
+
+const videoUrl =
+ "https://www.mozilla.org/tests/dom/media/webaudio/test/noaudio.webm";
+
+function testAutoplayPermission(browser) {
+ let principal = browser.contentPrincipal;
+ is(
+ PermissionTestUtils.testPermission(principal, "autoplay-media"),
+ Services.perms.ALLOW_ACTION,
+ `Autoplay is allowed on ${principal.origin}`
+ );
+}
+
+async function openAWWithVideo({
+ autoPlay = false,
+ video_url = videoUrl,
+ ...rest
+} = {}) {
+ const content = [
+ {
+ id: "VIDEO_ONBOARDING",
+ content: {
+ position: "center",
+ logo: {},
+ title: "Video onboarding",
+ secondary_button: { label: "Skip video", action: { navigate: true } },
+ video_container: {
+ video_url,
+ action: { navigate: true },
+ autoPlay,
+ ...rest,
+ },
+ },
+ },
+ ];
+ await setAboutWelcomeMultiStage(JSON.stringify(content));
+ let { cleanup, browser } = await openMRAboutWelcome();
+ return {
+ browser,
+ content,
+ async cleanup() {
+ await SpecialPowers.popPrefEnv();
+ await cleanup();
+ },
+ };
+}
+
+add_task(async function test_aboutwelcome_video_autoplay() {
+ let { cleanup, browser } = await openAWWithVideo({ autoPlay: true });
+
+ testAutoplayPermission(browser);
+
+ await SpecialPowers.spawn(browser, [videoUrl], async url => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector("main.with-video"),
+ "Waiting for video onboarding screen"
+ );
+ let video = content.document.querySelector(`video[src='${url}'][autoplay]`);
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ video.currentTime > 0 &&
+ !video.paused &&
+ !video.ended &&
+ video.readyState > 2,
+ "Waiting for video to play"
+ );
+ ok(!video.error, "Video should not have an error");
+ });
+
+ await cleanup();
+});
+
+add_task(async function test_aboutwelcome_video_no_autoplay() {
+ let { cleanup, browser } = await openAWWithVideo();
+
+ testAutoplayPermission(browser);
+
+ await SpecialPowers.spawn(browser, [videoUrl], async url => {
+ let video = await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(`video[src='${url}']:not([autoplay])`),
+ "Waiting for video element to render"
+ );
+ await ContentTaskUtils.waitForCondition(
+ () => video.paused && !video.ended && video.readyState > 2,
+ "Waiting for video to be playable but not playing"
+ );
+ ok(!video.error, "Video should not have an error");
+ });
+
+ await cleanup();
+});
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..58d9b43c0e
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_observer.js
@@ -0,0 +1,71 @@
+"use strict";
+
+const { AboutWelcomeParent } = ChromeUtils.import(
+ "resource:///actors/AboutWelcomeParent.jsm"
+);
+
+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.loadURIString(
+ 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..4e8fe223fe
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js
@@ -0,0 +1,298 @@
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { AddonRepository } = ChromeUtils.importESModule(
+ "resource://gre/modules/addons/AddonRepository.sys.mjs"
+);
+const { ExperimentFakes } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+
+const TEST_ADDON_INFO = [
+ {
+ name: "Test Add-on",
+ sourceURI: { scheme: "https", spec: "https://test.xpi" },
+ icons: { 32: "test.png", 64: "test.png" },
+ type: "extension",
+ },
+];
+
+const TEST_ADDON_INFO_THEME = [
+ {
+ name: "Test Add-on",
+ sourceURI: { scheme: "https", spec: "https://test.xpi" },
+ icons: { 32: "test.png", 64: "test.png" },
+ screenshots: [{ url: "test.png" }],
+ type: "theme",
+ },
+];
+
+async function openRTAMOWelcomePage() {
+ // Can't properly stub the child/parent actors so instead
+ // we stub the modules they depend on for the RTAMO flow
+ // to ensure the right thing is rendered.
+ await ASRouter.forceAttribution({
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ // with the sinon override, the id doesn't matter
+ content: "rta:whatever",
+ experiment: "ua-onboarding",
+ variation: "chrome",
+ ua: "Google Chrome 123",
+ dltoken: "00000000-0000-0000-0000-000000000000",
+ });
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ registerCleanupFunction(async () => {
+ BrowserTestUtils.removeTab(tab);
+ // Clear cache call is only possible in a testing environment
+ Services.env.set("XPCSHELL_TEST_PROFILE_DIR", "testing");
+ await ASRouter.forceAttribution({
+ source: "",
+ medium: "",
+ campaign: "",
+ content: "",
+ experiment: "",
+ variation: "",
+ ua: "",
+ dltoken: "",
+ });
+ });
+
+ 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 sandbox = sinon.createSandbox();
+ sandbox.stub(AddonRepository, "getAddonsByIDs").resolves(TEST_ADDON_INFO);
+
+ let browser = await openRTAMOWelcomePage();
+
+ await test_screen_content(
+ browser,
+ "RTAMO UI",
+ // Expected selectors:
+ [
+ `div.onboardingContainer[style*='background: var(--mr-welcome-background-color) var(--mr-welcome-background-gradient)']`,
+ "h2[data-l10n-id='mr1-return-to-amo-addon-title']",
+ `h2[data-l10n-args='{"addon-name":"${TEST_ADDON_INFO[0].name}"}'`,
+ "div.rtamo-icon",
+ "button.primary[data-l10n-id='mr1-return-to-amo-add-extension-label']",
+ "button[data-l10n-id='onboarding-not-now-button-label']",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+
+ await onButtonClick(
+ browser,
+ "button[data-l10n-id='onboarding-not-now-button-label']"
+ );
+ Assert.ok(gURLBar.focused, "Focus should be on awesome bar");
+
+ let windowGlobalParent = browser.browsingContext.currentWindowGlobal;
+ let aboutWelcomeActor = windowGlobalParent.getActor("AboutWelcome");
+ const messageSandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ messageSandbox.stub(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ messageSandbox.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,
+ "CLICK_BUTTON",
+ "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_EXTENSION",
+ "Message Id sent in telemetry for default RTAMO"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_rtamo_over_experiments() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(AddonRepository, "getAddonsByIDs").resolves(TEST_ADDON_INFO);
+
+ let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "aboutwelcome",
+ value: { screens: [], enabled: true },
+ });
+
+ let browser = await openRTAMOWelcomePage();
+
+ // If addon attribution exist, we should see RTAMO even if enrolled
+ // in about:welcome experiment
+ await test_screen_content(
+ browser,
+ "Experiment RTAMO UI",
+ // Expected selectors:
+ ["h2[data-l10n-id='mr1-return-to-amo-addon-title']"],
+ // Unexpected selectors:
+ []
+ );
+
+ await doExperimentCleanup();
+
+ browser = await openRTAMOWelcomePage();
+
+ await test_screen_content(
+ browser,
+ "No Experiment RTAMO UI",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "h2[data-l10n-id='mr1-return-to-amo-addon-title']",
+ "div.rtamo-icon",
+ "button.primary",
+ "button.secondary",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_rtamo_primary_button_theme() {
+ let themeSandbox = sinon.createSandbox();
+ themeSandbox
+ .stub(AddonRepository, "getAddonsByIDs")
+ .resolves(TEST_ADDON_INFO_THEME);
+
+ let browser = await openRTAMOWelcomePage();
+
+ await test_screen_content(
+ browser,
+ "RTAMO UI",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "h2[data-l10n-id='mr1-return-to-amo-addon-title']",
+ "div.rtamo-icon",
+ "button.primary[data-l10n-id='return-to-amo-add-theme-label']",
+ "button[data-l10n-id='onboarding-not-now-button-label']",
+ "img.rtamo-theme-icon",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+
+ themeSandbox.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_screen_targeting.js b/browser/components/newtab/test/browser/browser_aboutwelcome_screen_targeting.js
new file mode 100644
index 0000000000..f321d6a659
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_screen_targeting.js
@@ -0,0 +1,152 @@
+"use strict";
+
+const { ShellService } = ChromeUtils.importESModule(
+ "resource:///modules/ShellService.sys.mjs"
+);
+
+const { TelemetryEnvironment } = ChromeUtils.importESModule(
+ "resource://gre/modules/TelemetryEnvironment.sys.mjs"
+);
+
+const TEST_DEFAULT_CONTENT = [
+ {
+ id: "AW_STEP1",
+ content: {
+ title: "Step 1",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "Secondary",
+ },
+ },
+ },
+ {
+ id: "AW_STEP2",
+ targeting: "false",
+ content: {
+ title: "Step 2",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "Secondary",
+ },
+ },
+ },
+ {
+ id: "AW_STEP3",
+ content: {
+ title: "Step 3",
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "Secondary",
+ },
+ },
+ },
+];
+
+const sandbox = sinon.createSandbox();
+
+add_setup(function initSandbox() {
+ requestLongerTimeout(2);
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+const TEST_DEFAULT_JSON = JSON.stringify(TEST_DEFAULT_CONTENT);
+async function openAboutWelcome() {
+ await setAboutWelcomePref(true);
+ await setAboutWelcomeMultiStage(TEST_DEFAULT_JSON);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+add_task(async function second_screen_filtered_by_targeting() {
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.spy(aboutWelcomeActor, "onContentMessage");
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ ["main.AW_STEP1"],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+
+ await test_screen_content(
+ browser,
+ "multistage step 3",
+ // Expected selectors:
+ ["main.AW_STEP3"],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP1"]
+ );
+
+ sandbox.restore();
+ await popPrefs();
+});
+
+/**
+ * Test MR template easy setup content - Browser is pinned and
+ * not set as default and Windows 10 version 1703
+ */
+add_task(async function test_aboutwelcome_mr_template_easy_setup() {
+ if (!AppConstants.isPlatformAndVersionAtLeast("win", "10")) {
+ return;
+ }
+
+ if (
+ //Windows version 1703
+ TelemetryEnvironment.currentEnvironment.system.os.windowsBuildNumber < 15063
+ ) {
+ return;
+ }
+
+ sandbox.stub(ShellService, "doesAppNeedPin").returns(false);
+ sandbox.stub(ShellService, "isDefaultBrowser").returns(false);
+
+ await clearHistoryAndBookmarks();
+
+ const { browser, cleanup } = await openMRAboutWelcome();
+
+ //should render easy setup
+ await test_screen_content(
+ browser,
+ "doesn't render pin, import and set to default",
+ //Expected selectors:
+ ["main.AW_EASY_SETUP"],
+ //Unexpected selectors:
+ ["main.AW_PIN_FIREFOX", "main.AW_SET_DEFAULT", "main.AW_IMPORT_SETTINGS"]
+ );
+
+ await cleanup();
+ await popPrefs();
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_upgrade_multistage_mr.js b/browser/components/newtab/test/browser/browser_aboutwelcome_upgrade_multistage_mr.js
new file mode 100644
index 0000000000..a7c94b012b
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_upgrade_multistage_mr.js
@@ -0,0 +1,316 @@
+"use strict";
+
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { SpecialMessageActions } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs"
+);
+const { assertFirefoxViewTabSelected, closeFirefoxViewTab } =
+ ChromeUtils.importESModule(
+ "resource://testing-common/FirefoxViewTestUtils.sys.mjs"
+ );
+
+const HOMEPAGE_PREF = "browser.startup.homepage";
+const NEWTAB_PREF = "browser.newtabpage.enabled";
+const PINPBM_DISABLED_PREF = "browser.startup.upgradeDialog.pinPBM.disabled";
+
+// A bunch of the helper functions here are variants of the helper functions in
+// browser_aboutwelcome_multistage_mr.js, because the onboarding
+// experience runs in the parent process rather than elsewhere.
+// If these start to get used in more than just the two files, it may become
+// worth refactoring them to avoid duplicated code, and hoisting them
+// into head.js.
+
+let sandbox;
+
+add_setup(async () => {
+ requestLongerTimeout(2);
+
+ await setAboutWelcomePref(true);
+
+ sandbox = sinon.createSandbox();
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin").resolves(false);
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(false);
+
+ sandbox.stub(SpecialMessageActions, "pinFirefoxToTaskbar").resolves();
+
+ registerCleanupFunction(async () => {
+ await popPrefs();
+ sandbox.restore();
+ });
+});
+
+/**
+ * Get the content by OnboardingMessageProvider.getUpgradeMessage(),
+ * discard any screens whose ids are not in the "screensToTest" array,
+ * and then open an upgrade dialog with just those screens.
+ *
+ * @param {Array} screensToTest
+ * A list of which screen ids to be displayed
+ *
+ * @returns Promise<Window>
+ * Resolves to the window global object for the dialog once it has been
+ * opened
+ */
+async function openMRUpgradeWelcome(screensToTest) {
+ const data = await OnboardingMessageProvider.getUpgradeMessage();
+
+ if (screensToTest) {
+ data.content.screens = data.content.screens.filter(screen =>
+ screensToTest.includes(screen.id)
+ );
+ }
+
+ sandbox.stub(OnboardingMessageProvider, "getUpgradeMessage").resolves(data);
+
+ let dialogOpenPromise = BrowserTestUtils.promiseAlertDialogOpen(
+ null,
+ "chrome://browser/content/spotlight.html",
+ { isSubDialog: true }
+ );
+
+ Cc["@mozilla.org/browser/browserglue;1"]
+ .getService()
+ .wrappedJSObject._showUpgradeDialog();
+
+ let browser = await dialogOpenPromise;
+
+ OnboardingMessageProvider.getUpgradeMessage.restore();
+ return Promise.resolve(browser);
+}
+
+async function clickVisibleButton(browser, selector) {
+ await BrowserTestUtils.waitForCondition(
+ () => browser.document.querySelector(selector),
+ `waiting for selector ${selector}`,
+ 200, // interval
+ 100 // maxTries
+ );
+ browser.document.querySelector(selector).click();
+}
+
+async function test_upgrade_screen_content(
+ browser,
+ expected = [],
+ unexpected = []
+) {
+ for (let selector of expected) {
+ await TestUtils.waitForCondition(
+ () => browser.document.querySelector(selector),
+ `Should render ${selector}`
+ );
+ }
+ for (let selector of unexpected) {
+ Assert.ok(
+ !browser.document.querySelector(selector),
+ `Should not render ${selector}`
+ );
+ }
+}
+
+async function waitForDialogClose(browser) {
+ await BrowserTestUtils.waitForCondition(
+ () => !browser.top?.document.querySelector(".dialogFrame"),
+ "waiting for dialog to close"
+ );
+}
+
+/**
+ * Test homepage/newtab prefs start off as defaults and do not change
+ */
+add_task(async function test_aboutwelcome_upgrade_mr_prefs_off() {
+ let browser = await openMRUpgradeWelcome(["UPGRADE_GET_STARTED"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors:
+ ["main.UPGRADE_GET_STARTED"],
+ //Unexpected selectors:
+ ["main.PIN_FIREFOX"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+ await clickVisibleButton(browser, ".action-buttons button.primary");
+ await waitForDialogClose(browser);
+
+ Assert.ok(
+ !Services.prefs.prefHasUserValue(HOMEPAGE_PREF),
+ "homepage pref should be default"
+ );
+ Assert.ok(
+ !Services.prefs.prefHasUserValue(NEWTAB_PREF),
+ "newtab pref should be default"
+ );
+
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
+
+/*
+ *Test checkbox if needPrivatePin is true
+ */
+add_task(async function test_aboutwelcome_upgrade_mr_private_pin() {
+ OnboardingMessageProvider._doesAppNeedPin.resolves(true);
+ let browser = await openMRUpgradeWelcome(["UPGRADE_PIN_FIREFOX"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors:
+ ["main.UPGRADE_PIN_FIREFOX", "input#action-checkbox"],
+ //Unexpected selectors:
+ ["main.UPGRADE_COLORWAY"]
+ );
+ await clickVisibleButton(browser, ".action-buttons button.primary");
+ await waitForDialogClose(browser);
+
+ const pinStub = SpecialMessageActions.pinFirefoxToTaskbar;
+ Assert.equal(
+ pinStub.callCount,
+ 2,
+ "pinFirefoxToTaskbar should have been called twice"
+ );
+ Assert.ok(
+ // eslint-disable-next-line eqeqeq
+ pinStub.firstCall.lastArg != pinStub.secondCall.lastArg,
+ "pinFirefoxToTaskbar should have been called once for private, once not"
+ );
+
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
+
+/*
+ *Test checkbox shouldn't be shown in get started screen
+ */
+
+add_task(async function test_aboutwelcome_upgrade_mr_private_pin_get_started() {
+ OnboardingMessageProvider._doesAppNeedPin.resolves(false);
+
+ let browser = await openMRUpgradeWelcome(["UPGRADE_GET_STARTED"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ ["main.UPGRADE_GET_STARTED"],
+ //Unexpected selectors:
+ ["input#action-checkbox"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+
+ await waitForDialogClose(browser);
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
+
+/*
+ *Test checkbox shouldn't be shown if needPrivatePin is false
+ */
+add_task(async function test_aboutwelcome_upgrade_mr_private_pin_not_needed() {
+ OnboardingMessageProvider._doesAppNeedPin
+ .resolves(true)
+ .withArgs(true)
+ .resolves(false);
+
+ let browser = await openMRUpgradeWelcome(["UPGRADE_PIN_FIREFOX"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ ["main.UPGRADE_PIN_FIREFOX"],
+ //Unexpected selectors:
+ ["input#action-checkbox"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+ await waitForDialogClose(browser);
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
+
+/*
+ * Make sure we don't get an extraneous checkbox here.
+ */
+add_task(
+ async function test_aboutwelcome_upgrade_mr_pin_not_needed_default_needed() {
+ OnboardingMessageProvider._doesAppNeedPin.resolves(false);
+ OnboardingMessageProvider._doesAppNeedDefault.resolves(false);
+
+ let browser = await openMRUpgradeWelcome(["UPGRADE_GET_STARTED"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ ["main.UPGRADE_GET_STARTED"],
+ //Unexpected selectors:
+ ["input#action-checkbox"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+ await waitForDialogClose(browser);
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+ }
+);
+
+add_task(async function test_aboutwelcome_privacy_segmentation_pref() {
+ async function testPrivacySegmentation(enabled = false) {
+ await pushPrefs(["browser.privacySegmentation.preferences.show", enabled]);
+ let screenIds = ["UPGRADE_DATA_RECOMMENDATION", "UPGRADE_GRATITUDE"];
+ let browser = await openMRUpgradeWelcome(screenIds);
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ [`main.${screenIds[enabled ? 0 : 1]}`],
+ //Unexpected selectors:
+ [`main.${screenIds[enabled ? 1 : 0]}`]
+ );
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+ await popPrefs();
+ }
+
+ for (let enabled of [true, false]) {
+ await testPrivacySegmentation(enabled);
+ }
+});
+
+add_task(async function test_aboutwelcome_upgrade_show_firefox_view() {
+ let browser = await openMRUpgradeWelcome(["UPGRADE_GRATITUDE"]);
+
+ // execution
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ ["main.UPGRADE_GRATITUDE"],
+ //Unexpected selectors:
+ []
+ );
+ await clickVisibleButton(browser, ".action-buttons button.primary");
+
+ // verification
+ await BrowserTestUtils.waitForEvent(gBrowser, "TabSwitchDone");
+ assertFirefoxViewTabSelected(gBrowser.ownerGlobal);
+
+ closeFirefoxViewTab(gBrowser.ownerGlobal);
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
+
+/*
+ *Checkbox shouldn't be shown if pinPBMDisabled pref is true
+ */
+add_task(async function test_aboutwelcome_upgrade_mr_private_pin_not_needed() {
+ OnboardingMessageProvider._doesAppNeedPin.resolves(true);
+ await pushPrefs([PINPBM_DISABLED_PREF, true]);
+
+ const browser = await openMRUpgradeWelcome(["UPGRADE_PIN_FIREFOX"]);
+
+ await test_upgrade_screen_content(
+ browser,
+ //Expected selectors
+ ["main.UPGRADE_PIN_FIREFOX"],
+ //Unexpected selectors:
+ ["input#action-checkbox"]
+ );
+
+ await clickVisibleButton(browser, ".action-buttons button.secondary");
+ await waitForDialogClose(browser);
+ await BrowserTestUtils.removeTab(gBrowser.selectedTab);
+});
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_bug1761522.js b/browser/components/newtab/test/browser/browser_asrouter_bug1761522.js
new file mode 100644
index 0000000000..13f5ac9b9c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_bug1761522.js
@@ -0,0 +1,232 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ASRouter, MessageLoaderUtils } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
+const { RemoteL10n } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/RemoteL10n.sys.mjs"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+
+// This pref is used to override the Remote Settings server URL in tests.
+// See SERVER_URL in services/settings/Utils.jsm for more details.
+const RS_SERVER_PREF = "services.settings.server";
+
+const FLUENT_CONTENT = "asrouter-test-string = Test Test Test\n";
+
+async function serveRemoteSettings() {
+ const server = new HttpServer();
+ server.start(-1);
+
+ const baseURL = `http://localhost:${server.identity.primaryPort}/`;
+ const attachmentUuid = crypto.randomUUID();
+ const attachment = new TextEncoder().encode(FLUENT_CONTENT);
+
+ // Serve an index so RS knows where to fetch images from.
+ server.registerPathHandler("/v1/", (request, response) => {
+ response.write(
+ JSON.stringify({
+ capabilities: {
+ attachments: {
+ base_url: `${baseURL}cdn`,
+ },
+ },
+ })
+ );
+ });
+
+ // Serve the ms-language-packs record for cfr-v1-ja-JP-mac, pointing to an attachment.
+ server.registerPathHandler(
+ "/v1/buckets/main/collections/ms-language-packs/records/cfr-v1-ja-JP-mac",
+ (request, response) => {
+ response.setStatusLine(null, 200, "OK");
+ response.setHeader(
+ "Content-type",
+ "application/json; charset=utf-8",
+ false
+ );
+ response.write(
+ JSON.stringify({
+ permissions: {},
+ data: {
+ attachment: {
+ hash: "f9aead2693c4ff95c2764df72b43fdf5b3490ed06414588843848f991136040b",
+ size: attachment.buffer.byteLength,
+ filename: "asrouter.ftl",
+ location: `main-workspace/ms-language-packs/${attachmentUuid}`,
+ },
+ id: "cfr-v1-ja-JP-mac",
+ last_modified: Date.now(),
+ },
+ })
+ );
+ }
+ );
+
+ // Serve the attachment for ms-language-packs/cfr-va-ja-JP-mac.
+ server.registerPathHandler(
+ `/cdn/main-workspace/ms-language-packs/${attachmentUuid}`,
+ (request, response) => {
+ const stream = Cc[
+ "@mozilla.org/io/arraybuffer-input-stream;1"
+ ].createInstance(Ci.nsIArrayBufferInputStream);
+ stream.setData(attachment.buffer, 0, attachment.buffer.byteLength);
+
+ response.setStatusLine(null, 200, "OK");
+ response.setHeader("Content-type", "application/octet-stream");
+ response.bodyOutputStream.writeFrom(stream, attachment.buffer.byteLength);
+ }
+ );
+
+ // Serve the list of changed collections. cfr must have changed, otherwise we
+ // won't attempt to fetch the cfr records (and then won't fetch
+ // ms-language-packs).
+ server.registerPathHandler(
+ "/v1/buckets/monitor/collections/changes/changeset",
+ (request, response) => {
+ const now = Date.now();
+ response.setStatusLine(null, 200, "OK");
+ response.setHeader(
+ "Content-type",
+ "application/json; charset=utf-8",
+ false
+ );
+ response.write(
+ JSON.stringify({
+ timestamp: now,
+ changes: [
+ {
+ host: `localhost:${server.identity.primaryPort}`,
+ last_modified: now,
+ bucket: "main",
+ collection: "cfr",
+ },
+ ],
+ metadata: {},
+ })
+ );
+ }
+ );
+
+ const message = await PanelTestProvider.getMessages().then(msgs =>
+ msgs.find(msg => msg.id === "PERSONALIZED_CFR_MESSAGE")
+ );
+
+ // Serve the "changed" cfr entries. If there are no changes, then ASRouter
+ // won't re-fetch ms-language-packs.
+ server.registerPathHandler(
+ "/v1/buckets/main/collections/cfr/changeset",
+ (request, response) => {
+ const now = Date.now();
+ response.setStatusLine(null, 200, "OK");
+ response.setHeader(
+ "Content-type",
+ "application/json; charset=utf-8",
+ false
+ );
+ response.write(
+ JSON.stringify({
+ timestamp: now,
+ changes: [message],
+ metadata: {},
+ })
+ );
+ }
+ );
+
+ await SpecialPowers.pushPrefEnv({
+ set: [[RS_SERVER_PREF, `${baseURL}v1`]],
+ });
+
+ return async () => {
+ await new Promise(resolve => server.stop(() => resolve()));
+ await SpecialPowers.popPrefEnv();
+ };
+}
+
+add_task(async function test_asrouter() {
+ const MS_LANGUAGE_PACKS_DIR = PathUtils.join(
+ PathUtils.localProfileDir,
+ "settings",
+ "main",
+ "ms-language-packs"
+ );
+ const sandbox = sinon.createSandbox();
+ const stop = await serveRemoteSettings();
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ JSON.stringify({
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ collection: "cfr",
+ updateCyleInMs: 3600000,
+ }),
+ ],
+ ],
+ });
+ const localeService = Services.locale;
+ RemoteSettings("cfr").verifySignature = false;
+
+ registerCleanupFunction(async () => {
+ RemoteSettings("cfr").verifySignature = true;
+ Services.locale = localeService;
+ await SpecialPowers.popPrefEnv();
+ await stop();
+ sandbox.restore();
+ await IOUtils.remove(MS_LANGUAGE_PACKS_DIR, { recursive: true });
+ RemoteL10n.reloadL10n();
+ });
+
+ // We can't stub Services.locale.appLocaleAsBCP47 directly because its an
+ // XPCOM_Native object.
+ const fakeLocaleService = new Proxy(localeService, {
+ get(obj, prop) {
+ if (prop === "appLocaleAsBCP47") {
+ return "ja-JP-macos";
+ }
+ return obj[prop];
+ },
+ });
+
+ const localeSpy = sandbox.spy(MessageLoaderUtils, "locale", ["get"]);
+ Services.locale = fakeLocaleService;
+
+ const cfrProvider = ASRouter.state.providers.find(p => p.id === "cfr");
+ await ASRouter.loadMessagesFromAllProviders([cfrProvider]);
+
+ Assert.equal(
+ Services.locale.appLocaleAsBCP47,
+ "ja-JP-macos",
+ "Locale service returns ja-JP-macos"
+ );
+ Assert.ok(localeSpy.get.called, "MessageLoaderUtils.locale getter called");
+ Assert.ok(
+ localeSpy.get.alwaysReturned("ja-JP-mac"),
+ "MessageLoaderUtils.locale getter returned expected locale ja-JP-mac"
+ );
+
+ const path = PathUtils.join(
+ MS_LANGUAGE_PACKS_DIR,
+ "browser",
+ "newtab",
+ "asrouter.ftl"
+ );
+ Assert.ok(await IOUtils.exists(path), "asrouter.ftl was downloaded");
+ Assert.equal(
+ await IOUtils.readUTF8(path),
+ FLUENT_CONTENT,
+ "asrouter.ftl content matches expected"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_bug1800087.js b/browser/components/newtab/test/browser/browser_asrouter_bug1800087.js
new file mode 100644
index 0000000000..dd7138d00d
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_bug1800087.js
@@ -0,0 +1,48 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 (Bug 1800937): Remove this whole test along with the migration code
+// after the next watershed release.
+
+const { ASRouterNewTabHook } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/ASRouterNewTabHook.sys.mjs"
+);
+const { ASRouterDefaultConfig } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterDefaultConfig.jsm"
+);
+
+add_setup(() => ASRouterNewTabHook.destroy());
+
+// Test that the old pref format is migrated correctly to the new format.
+// provider.bucket -> provider.collection
+add_task(async function test_newtab_asrouter() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ JSON.stringify({
+ id: "cfr",
+ enabled: true,
+ type: "local",
+ bucket: "cfr", // The pre-migration property name is bucket.
+ updateCyleInMs: 3600000,
+ }),
+ ],
+ ],
+ });
+
+ await ASRouterNewTabHook.createInstance(ASRouterDefaultConfig());
+ const hook = await ASRouterNewTabHook.getInstance();
+ const router = hook._router;
+ if (!router.initialized) {
+ await router.waitForInitialized;
+ }
+
+ // Test that the pref's bucket is migrated to collection.
+ let cfrProvider = router.state.providers.find(p => p.id === "cfr");
+ Assert.equal(cfrProvider.collection, "cfr", "The collection name is correct");
+ Assert.ok(!cfrProvider.bucket, "The bucket name is removed");
+});
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..3c163e2a14
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_cfr.js
@@ -0,0 +1,914 @@
+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.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+
+const createDummyRecommendation = ({
+ action,
+ category,
+ heading_text,
+ layout,
+ skip_address_bar_notifier,
+ show_in_private_browsing,
+ template,
+}) => {
+ let recommendation = {
+ template,
+ groups: ["mochitest-group"],
+ content: {
+ layout: layout || "addon_recommendation",
+ category,
+ anchor_id: "page-action-buttons",
+ skip_address_bar_notifier,
+ show_in_private_browsing,
+ heading_text: heading_text || "Mochitest",
+ info_icon: {
+ label: { attributes: { tooltiptext: "Why am I seeing this" } },
+ sumo_path: "extensionrecommendations",
+ },
+ icon: "chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg",
+ icon_dark_theme:
+ "chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg",
+ learn_more: "extensionrecommendations",
+ addon: {
+ id: "addon-id",
+ title: "Addon name",
+ icon: "chrome://browser/skin/addons/addon-install-downloading.svg",
+ 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 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 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,
+ show_in_private_browsing = 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,
+ show_in_private_browsing,
+ 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_setup(async function () {
+ // 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.loadURIString(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.loadURIString(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.loadURIString(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.loadURIString(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.loadURIString(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_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.loadURIString(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"
+ );
+
+ notification.secondaryButton.click();
+ await hidePanel;
+ await SpecialPowers.popPrefEnv();
+ clearNotifications();
+ }
+);
+
+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.loadURIString(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.loadURIString(browser, "about:blank");
+ await BrowserTestUtils.browserLoaded(browser, false, "about:blank");
+
+ BrowserTestUtils.loadURIString(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.loadURIString(browser, "http://example.com/#foo");
+ await BrowserTestUtils.waitForLocationChange(
+ gBrowser,
+ "http://example.com/#foo"
+ );
+
+ Assert.equal(count, 1, "It should ignore same page navigation");
+
+ BrowserTestUtils.loadURIString(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.loadURIString(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.loadURIString(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.loadURIString(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.loadURIString(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.loadURIString(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_doorhanger_in_private_window() {
+ const win = await BrowserTestUtils.openNewBrowserWindow({ private: true });
+ const sendPingStub = sinon.stub(
+ TelemetryFeed.prototype,
+ "sendStructuredIngestionEvent"
+ );
+
+ const tab = await BrowserTestUtils.openNewForegroundTab(
+ win.gBrowser,
+ "http://example.com/"
+ );
+ const browser = tab.linkedBrowser;
+
+ const response1 = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ !response1,
+ "CFR should not be shown in a private window if show_in_private_browsing is false"
+ );
+
+ const response2 = await trigger_cfr_panel(browser, "example.com", {
+ show_in_private_browsing: true,
+ });
+ Assert.ok(
+ response2,
+ "CFR should be shown in a private window if show_in_private_browsing is true"
+ );
+
+ const shownPromise = BrowserTestUtils.waitForEvent(
+ win.PopupNotifications.panel,
+ "popupshown"
+ );
+ win.document.getElementById("contextual-feature-recommendation").click();
+ await shownPromise;
+
+ const hiddenPromise = BrowserTestUtils.waitForEvent(
+ win.PopupNotifications.panel,
+ "popuphidden"
+ );
+ const button = win.document.getElementById(
+ "contextual-feature-recommendation-notification"
+ )?.button;
+ Assert.ok(button, "CFR doorhanger button found");
+ button.click();
+ await hiddenPromise;
+
+ Assert.greater(sendPingStub.callCount, 0, "Recorded CFR telemetry");
+ const cfrPing = sendPingStub.args.find(args => args[2] === "cfr");
+ Assert.equal(cfrPing[0].source, "CFR", "Got a CFR event");
+ Assert.equal(
+ cfrPing[0].message_id,
+ "n/a",
+ "Omitted message_id consistent with CFR telemetry policy"
+ );
+ Assert.equal(
+ cfrPing[0].client_id,
+ undefined,
+ "Omitted client_id consistent with CFR telemetry policy"
+ );
+
+ sendPingStub.restore();
+ await BrowserTestUtils.closeWindow(win);
+});
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..719c0d3512
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js
@@ -0,0 +1,505 @@
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettingsExperimentLoader } = ChromeUtils.importESModule(
+ "resource://nimbus/lib/RemoteSettingsExperimentLoader.sys.mjs"
+);
+const { ExperimentAPI } = ChromeUtils.importESModule(
+ "resource://nimbus/ExperimentAPI.sys.mjs"
+);
+const { ExperimentFakes, ExperimentTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+const { ExperimentManager } = ChromeUtils.importESModule(
+ "resource://nimbus/lib/ExperimentManager.sys.mjs"
+);
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+const { TelemetryTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/TelemetryTestUtils.sys.mjs"
+);
+
+const MESSAGE_CONTENT = {
+ id: "xman_test_message",
+ groups: [],
+ 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: "about:blank",
+ },
+ 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",
+ layout: "short_message",
+ 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",
+};
+
+const getExperiment = async feature => {
+ let recipe = 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_${feature}_${Date.now()}`,
+ {
+ id: "xman_test_message",
+ bucketConfig: {
+ count: 100,
+ start: 0,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ }
+ );
+ recipe.branches[0].features[0].featureId = feature;
+ recipe.branches[0].features[0].value = MESSAGE_CONTENT;
+ recipe.branches[1].features[0].featureId = feature;
+ recipe.branches[1].features[0].value = MESSAGE_CONTENT;
+ recipe.featureIds = [feature];
+ await ExperimentTestUtils.validateExperiment(recipe);
+ return recipe;
+};
+
+const getCFRExperiment = async () => {
+ return getExperiment("cfr");
+};
+
+const getLegacyCFRExperiment = async () => {
+ let recipe = ExperimentFakes.recipe(`test_xman_cfr_${Date.now()}`, {
+ id: "xman_test_message",
+ bucketConfig: {
+ count: 100,
+ start: 0,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ });
+
+ delete recipe.branches[0].features;
+ delete recipe.branches[1].features;
+ recipe.branches[0].feature = {
+ featureId: "cfr",
+ value: MESSAGE_CONTENT,
+ };
+ recipe.branches[1].feature = {
+ featureId: "cfr",
+ value: MESSAGE_CONTENT,
+ };
+ return recipe;
+};
+
+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(experiment) {
+ // Store the experiment in RS local db to bypass synchronization.
+ await client.db.importChanges({}, Date.now(), [experiment], { clear: true });
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["app.shield.optoutstudies.enabled", true],
+ ["datareporting.healthreport.uploadEnabled", true],
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.messaging-experiments",
+ `{"id":"messaging-experiments","enabled":true,"type":"remote-experiments","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+}
+
+async function cleanup() {
+ await client.db.clear();
+ await SpecialPowers.popPrefEnv();
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+}
+
+/**
+ * Assert that a message is (or optionally is not) present in the ASRouter
+ * messages list, optionally waiting for it to be present/not present.
+ * @param {string} id message id
+ * @param {boolean} [found=true] expect the message to be found
+ * @param {boolean} [wait=true] check for the message until found/not found
+ * @returns {Promise<Message|null>} resolves with the message, if found
+ */
+async function assertMessageInState(id, found = true, wait = true) {
+ if (wait) {
+ await BrowserTestUtils.waitForCondition(
+ () => !!ASRouter.state.messages.find(m => m.id === id) === found,
+ `Message ${id} should ${found ? "" : "not"} be found in ASRouter state`
+ );
+ }
+ const message = ASRouter.state.messages.find(m => m.id === id);
+ Assert.equal(
+ !!message,
+ found,
+ `Message ${id} should ${found ? "" : "not"} be found`
+ );
+ return message || null;
+}
+
+add_task(async function test_loading_experimentsAPI() {
+ const experiment = await getCFRExperiment();
+ await setup(experiment);
+ // 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"
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ await cleanup();
+});
+
+add_task(async function test_loading_fxms_message_1_feature() {
+ const experiment = await getExperiment("fxms-message-1");
+ await setup(experiment);
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "fxms-message-1" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ await cleanup();
+});
+
+add_task(async function test_loading_experimentsAPI_legacy() {
+ const experiment = await getLegacyCFRExperiment();
+ await setup(experiment);
+ // 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"
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ await cleanup();
+});
+
+add_task(async function test_loading_experimentsAPI_rollout() {
+ const rollout = await getCFRExperiment();
+ rollout.isRollout = true;
+ rollout.branches.pop();
+
+ await setup(rollout);
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(() =>
+ ExperimentAPI.getRolloutMetaData({ featureId: "cfr" })
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ await cleanup();
+});
+
+add_task(async function test_exposure_ping() {
+ // Reset this check to allow sending multiple exposure pings in tests
+ NimbusFeatures.cfr._didSendExposureEvent = false;
+ const experiment = await getCFRExperiment();
+ await setup(experiment);
+ Services.telemetry.clearScalars();
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ 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#nimbus_experiment",
+ 1
+ );
+
+ exposureSpy.restore();
+ await cleanup();
+});
+
+add_task(async function test_exposure_ping_legacy() {
+ // Reset this check to allow sending multiple exposure pings in tests
+ NimbusFeatures.cfr._didSendExposureEvent = false;
+ const experiment = await getLegacyCFRExperiment();
+ await setup(experiment);
+ Services.telemetry.clearScalars();
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await assertMessageInState("xman_test_message");
+
+ 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#nimbus_experiment",
+ 1
+ );
+
+ exposureSpy.restore();
+ await cleanup();
+});
+
+add_task(async function test_forceEnrollUpdatesMessages() {
+ const experiment = await getCFRExperiment();
+
+ await setup(experiment);
+ await SpecialPowers.pushPrefEnv({
+ set: [["nimbus.debug", true]],
+ });
+
+ await assertMessageInState("xman_test_message", false, false);
+
+ await RemoteSettingsExperimentLoader.optInToExperiment({
+ slug: experiment.slug,
+ branch: experiment.branches[0].slug,
+ });
+
+ await assertMessageInState("xman_test_message");
+
+ await ExperimentManager.unenroll(`optin-${experiment.slug}`, "cleanup");
+ await SpecialPowers.popPrefEnv();
+ await cleanup();
+});
+
+add_task(async function test_update_on_enrollments_changed() {
+ // Check that the message is not already present
+ await assertMessageInState("xman_test_message", false, false);
+
+ const experiment = await getCFRExperiment();
+ let enrollmentChanged = TestUtils.topicObserved("nimbus:enrollments-updated");
+ await setup(experiment);
+ await RemoteSettingsExperimentLoader.updateRecipes();
+
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+ await enrollmentChanged;
+
+ await assertMessageInState("xman_test_message");
+
+ await cleanup();
+});
+
+add_task(async function test_emptyMessage() {
+ const experiment = ExperimentFakes.recipe(`empty_${Date.now()}`, {
+ id: "empty",
+ branches: [
+ {
+ slug: "a",
+ ratio: 1,
+ features: [
+ {
+ featureId: "cfr",
+ value: {},
+ },
+ ],
+ },
+ ],
+ bucketConfig: {
+ start: 0,
+ count: 100,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ });
+
+ await setup(experiment);
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await ASRouter._updateMessageProviders();
+
+ const experimentsProvider = ASRouter.state.providers.find(
+ p => p.id === "messaging-experiments"
+ );
+
+ // Clear all messages
+ ASRouter.setState(state => ({
+ messages: [],
+ }));
+
+ await ASRouter.loadMessagesFromAllProviders([experimentsProvider]);
+
+ Assert.deepEqual(
+ ASRouter.state.messages,
+ [],
+ "ASRouter should have loaded zero messages"
+ );
+
+ await cleanup();
+});
+
+add_task(async function test_multiMessageTreatment() {
+ const featureId = "cfr";
+ // Add an array of two messages to the first branch
+ const messages = [
+ { ...MESSAGE_CONTENT, id: "multi-message-1" },
+ { ...MESSAGE_CONTENT, id: "multi-message-2" },
+ ];
+ const recipe = ExperimentFakes.recipe(`multi-message_${Date.now()}`, {
+ id: `multi-message`,
+ bucketConfig: {
+ count: 100,
+ start: 0,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ branches: [
+ {
+ slug: "control",
+ ratio: 1,
+ features: [{ featureId, value: { template: "multi", messages } }],
+ },
+ ],
+ });
+ await ExperimentTestUtils.validateExperiment(recipe);
+
+ await setup(recipe);
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ messages
+ .map(m => ASRouter.state.messages.find(n => n.id === m.id))
+ .every(Boolean),
+ "Experiment message found in ASRouter state"
+ );
+ Assert.ok(true, "Experiment message found in ASRouter state");
+
+ 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..5957a5905e
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_group_frequency.js
@@ -0,0 +1,190 @@
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+
+/**
+ * Load and modify a message for the test.
+ */
+add_setup(async function () {
+ 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({}, Date.now(), [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","collection":"cfr","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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 ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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({}, Date.now(), [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","collection":"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.loadURIString(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.loadURIString(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.loadURIString(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..af943b8587
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js
@@ -0,0 +1,160 @@
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+
+/**
+ * Load and modify a message for the test.
+ */
+add_setup(async function () {
+ 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({}, Date.now(), [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","collection":"cfr","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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 ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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({}, Date.now(), [groupConfiguration], {
+ clear: true,
+ });
+
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.message-groups",
+ `{"id":"message-groups","enabled":true,"type":"remote-settings","collection":"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.loadURIString(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.loadURIString(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..dbbc86bb3a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_infobar.js
@@ -0,0 +1,226 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { InfoBar } = ChromeUtils.import(
+ "resource://activity-stream/lib/InfoBar.jsm"
+);
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+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,
+ content: {
+ priority: window.gNotificationBox.PRIORITY_WARNING_HIGH,
+ ...message.content,
+ },
+ },
+ 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);
+ Assert.equal(
+ infobar.notification.priority,
+ window.gNotificationBox.PRIORITY_WARNING_HIGH,
+ "Has the priority level set in the message definition"
+ );
+
+ let primaryBtn = infobar.notification.buttonContainer.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"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => !InfoBar._activeInfobar,
+ "Wait for notification to be dismissed by primary btn click."
+ );
+});
+
+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"
+ );
+
+ let defaultPriority = notificationStack.PRIORITY_SYSTEM;
+ Assert.ok(
+ notificationStack.currentNotification.priority === defaultPriority,
+ "Notification has default priority"
+ );
+ // Dismiss the notification
+ notificationStack.currentNotification.closeButton.click();
+});
+
+add_task(async function dismiss_telemetry() {
+ let message = {
+ ...(await CFRMessageProvider.getMessages()).find(
+ m => m.id === "INFOBAR_ACTION_86"
+ ),
+ };
+ message.content.type = "tab";
+
+ let dispatchStub = sinon.stub();
+ let infobar = InfoBar.showInfoBarMessage(
+ BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ message,
+ dispatchStub
+ );
+
+ // Remove any IMPRESSION pings
+ dispatchStub.reset();
+
+ infobar.notification.closeButton.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () => infobar.notification === null,
+ "Set to null by `removed` event"
+ );
+
+ Assert.equal(dispatchStub.callCount, 1, "Only called once");
+ Assert.equal(
+ dispatchStub.firstCall.args[0].data.event,
+ "DISMISSED",
+ "Called with dismissed"
+ );
+
+ // Remove DISMISSED ping
+ dispatchStub.reset();
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:blank"
+ );
+ infobar = InfoBar.showInfoBarMessage(
+ BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ message,
+ dispatchStub
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => dispatchStub.callCount > 0,
+ "Wait for impression ping"
+ );
+
+ // Remove IMPRESSION ping
+ dispatchStub.reset();
+ BrowserTestUtils.removeTab(tab);
+
+ await BrowserTestUtils.waitForCondition(
+ () => infobar.notification === null,
+ "Set to null by `disconnect` event"
+ );
+
+ // Called by closing the tab and triggering "disconnect"
+ Assert.equal(dispatchStub.callCount, 1, "Only called once");
+ Assert.equal(
+ dispatchStub.firstCall.args[0].data.event,
+ "DISMISSED",
+ "Called with dismissed"
+ );
+});
+
+add_task(async function prevent_multiple_messages() {
+ 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");
+
+ // Try to stack 2 notifications
+ InfoBar.showInfoBarMessage(
+ BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ message,
+ dispatchStub
+ );
+
+ Assert.equal(dispatchStub.callCount, 2, "Impression count did not increase");
+
+ // Dismiss the first notification
+ infobar.notification.closeButton.click();
+ Assert.equal(InfoBar._activeInfobar, null, "Cleared the active notification");
+
+ // Reset impressions count
+ dispatchStub.reset();
+ // Try show the message again
+ infobar = InfoBar.showInfoBarMessage(
+ BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ message,
+ dispatchStub
+ );
+ Assert.ok(InfoBar._activeInfobar, "activeInfobar is set");
+ Assert.equal(dispatchStub.callCount, 2, "Called twice with IMPRESSION");
+ // Dismiss the notification again
+ infobar.notification.closeButton.click();
+ Assert.equal(InfoBar._activeInfobar, null, "Cleared the active notification");
+});
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..44288c1433
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js
@@ -0,0 +1,116 @@
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+const { MomentsPageHub } = ChromeUtils.import(
+ "resource://activity-stream/lib/MomentsPageHub.jsm"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+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","collection":"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(
+ {},
+ Date.now(),
+ [
+ {
+ // 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();
+ await ASRouter.loadMessagesFromAllProviders();
+ // Wait to load the WNPanel messages
+ await BrowserTestUtils.waitForCondition(
+ () => 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 ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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 ASRouter.loadMessagesFromAllProviders();
+ await BrowserTestUtils.waitForCondition(
+ () => 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..50f3f147dc
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_snippets.js
@@ -0,0 +1,190 @@
+"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.loadURIString(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_snippets_dismiss.js b/browser/components/newtab/test/browser/browser_asrouter_snippets_dismiss.js
new file mode 100644
index 0000000000..fb4387eb1d
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_snippets_dismiss.js
@@ -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";
+
+/**
+ * Snippets endpoint has two snippets that share the same campaign id.
+ * We want to make sure that dismissing the snippet on the first about:newtab
+ * will clear the snippet on the next (preloaded) about:newtab.
+ */
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+async function setup() {
+ 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":14400000}',
+ ],
+ ["browser.newtabpage.activity-stream.feeds.snippets", true],
+ // Disable onboarding, this would prevent snippets from showing up
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.onboarding",
+ '{"id":"onboarding","type":"local","localProvider":"OnboardingMessageProvider","enabled":false,"exclude":[]}',
+ ],
+ // Ensure this is true, this is the main behavior we want to test for
+ ["browser.newtab.preload", true],
+ ],
+ });
+}
+
+add_task(async function test_campaign_dismiss() {
+ await setup();
+ let tab1 = await BrowserTestUtils.openNewForegroundTab({
+ gBrowser,
+ opening: "about:home",
+ });
+ await ContentTask.spawn(gBrowser.selectedBrowser, {}, 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"
+ );
+
+ content.document
+ .querySelector("#footer-asrouter-container .blockButton")
+ .click();
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ !content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ),
+ "Should wait for the snippet to block"
+ );
+ });
+
+ ok(
+ ASRouter.state.messageBlockList.length,
+ "Should have the campaign blocked"
+ );
+
+ let tab2 = await BrowserTestUtils.openNewForegroundTab({
+ gBrowser,
+ opening: "about:newtab",
+ // This is important because the newtab is preloaded and doesn't behave
+ // like a regular page load
+ waitForLoad: false,
+ });
+
+ await ContentTask.spawn(gBrowser.selectedBrowser, {}, async () => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".activity-stream"),
+ `Should render Activity Stream`
+ );
+ let snippet = content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ );
+ Assert.equal(
+ snippet,
+ null,
+ "No snippets shown because campaign is blocked"
+ );
+ });
+
+ BrowserTestUtils.removeTab(tab1);
+ BrowserTestUtils.removeTab(tab2);
+ await ASRouter.unblockMessageById(["10533", "10534"]);
+ await SpecialPowers.popPrefEnv();
+});
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..21429f5bd3
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_targeting.js
@@ -0,0 +1,1697 @@
+XPCOMUtils.defineLazyModuleGetters(this, {
+ AboutNewTab: "resource:///modules/AboutNewTab.jsm",
+ ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm",
+ BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
+ HomePage: "resource:///modules/HomePage.jsm",
+ QueryCache: "resource://activity-stream/lib/ASRouterTargeting.jsm",
+});
+ChromeUtils.defineESModuleGetters(this, {
+ AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
+ AddonTestUtils: "resource://testing-common/AddonTestUtils.sys.mjs",
+ AppConstants: "resource://gre/modules/AppConstants.sys.mjs",
+ AttributionCode: "resource:///modules/AttributionCode.sys.mjs",
+ BuiltInThemes: "resource:///modules/BuiltInThemes.sys.mjs",
+ CFRMessageProvider:
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs",
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ExperimentFakes: "resource://testing-common/NimbusTestUtils.sys.mjs",
+ FxAccounts: "resource://gre/modules/FxAccounts.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
+ ProfileAge: "resource://gre/modules/ProfileAge.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+ ShellService: "resource:///modules/ShellService.sys.mjs",
+ TargetingContext: "resource://messaging-system/targeting/Targeting.sys.mjs",
+ TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.sys.mjs",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
+});
+
+function sendFormAutofillMessage(name, data) {
+ let actor =
+ gBrowser.selectedBrowser.browsingContext.currentWindowGlobal.getActor(
+ "FormAutofill"
+ );
+ return actor.receiveMessage({ name, data });
+}
+
+async function removeAutofillRecords() {
+ let addresses = await sendFormAutofillMessage("FormAutofill:GetRecords", {
+ collectionName: "addresses",
+ });
+ if (addresses.length) {
+ let observePromise = TestUtils.topicObserved(
+ "formautofill-storage-changed"
+ );
+ await sendFormAutofillMessage("FormAutofill:RemoveAddresses", {
+ guids: addresses.map(address => address.guid),
+ });
+ await observePromise;
+ }
+ let creditCards = await sendFormAutofillMessage("FormAutofill:GetRecords", {
+ collectionName: "creditCards",
+ });
+ if (creditCards.length) {
+ let observePromise = TestUtils.topicObserved(
+ "formautofill-storage-changed"
+ );
+ await sendFormAutofillMessage("FormAutofill:RemoveCreditCards", {
+ guids: creditCards.map(cc => cc.guid),
+ });
+ await observePromise;
+ }
+}
+
+// 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_isFxASignedIn_false() {
+ await pushPrefs(
+ ["identity.fxaccounts.enabled", true],
+ ["services.sync.username", ""]
+ );
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(async () => sandbox.restore());
+ sandbox.stub(FxAccounts.prototype, "getSignedInUser").resolves(null);
+ is(
+ await ASRouterTargeting.Environment.isFxASignedIn,
+ false,
+ "user should not appear signed in"
+ );
+
+ const message = { id: "foo", targeting: "isFxASignedIn" };
+ isnot(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should not select the message since user is not signed in"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function check_isFxASignedIn_true() {
+ await pushPrefs(
+ ["identity.fxaccounts.enabled", true],
+ ["services.sync.username", ""]
+ );
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(async () => sandbox.restore());
+ sandbox.stub(FxAccounts.prototype, "getSignedInUser").resolves({});
+ is(
+ await ASRouterTargeting.Environment.isFxASignedIn,
+ true,
+ "user should appear signed in"
+ );
+
+ const message = { id: "foo", targeting: "isFxASignedIn" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select the correct message"
+ );
+
+ sandbox.restore();
+});
+
+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 = await 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: {
+ browser_specific_settings: { 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 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`
+ );
+});
+
+add_task(async function check_is_major_upgrade() {
+ let message = {
+ id: "check_is_major_upgrade",
+ targeting: `isMajorUpgrade != undefined && isMajorUpgrade == ${
+ Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler)
+ .majorUpgrade
+ }`,
+ };
+
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages: [message] })).id,
+ message.id,
+ "Should select the message"
+ );
+});
+
+add_task(async function check_userMonthlyActivity() {
+ ok(
+ Array.isArray(await ASRouterTargeting.Environment.userMonthlyActivity),
+ "value is an array"
+ );
+});
+
+add_task(async function check_doesAppNeedPin() {
+ is(
+ typeof (await ASRouterTargeting.Environment.doesAppNeedPin),
+ "boolean",
+ "Should return a boolean"
+ );
+});
+
+add_task(async function check_doesAppNeedPrivatePin() {
+ is(
+ typeof (await ASRouterTargeting.Environment.doesAppNeedPrivatePin),
+ "boolean",
+ "Should return a boolean"
+ );
+});
+
+add_task(async function check_isBackgroundTaskMode() {
+ if (!AppConstants.MOZ_BACKGROUNDTASKS) {
+ // `mochitest-browser` suite `add_task` does not yet support
+ // `properties.skip_if`.
+ ok(true, "Skipping because !AppConstants.MOZ_BACKGROUNDTASKS");
+ return;
+ }
+
+ const bts = Cc["@mozilla.org/backgroundtasks;1"].getService(
+ Ci.nsIBackgroundTasks
+ );
+
+ // Pretend that this is a background task.
+ bts.overrideBackgroundTaskNameForTesting("taskName");
+ is(
+ await ASRouterTargeting.Environment.isBackgroundTaskMode,
+ true,
+ "Is in background task mode"
+ );
+ is(
+ await ASRouterTargeting.Environment.backgroundTaskName,
+ "taskName",
+ "Has expected background task name"
+ );
+
+ // Unset, so that subsequent test functions don't see background task mode.
+ bts.overrideBackgroundTaskNameForTesting(null);
+ is(
+ await ASRouterTargeting.Environment.isBackgroundTaskMode,
+ false,
+ "Is not in background task mode"
+ );
+ is(
+ await ASRouterTargeting.Environment.backgroundTaskName,
+ null,
+ "Has no background task name"
+ );
+});
+
+add_task(async function check_userPrefersReducedMotion() {
+ is(
+ typeof (await ASRouterTargeting.Environment.userPrefersReducedMotion),
+ "boolean",
+ "Should return a boolean"
+ );
+});
+
+add_task(async function test_mr2022Holdback() {
+ await ExperimentAPI.ready();
+
+ ok(
+ !ASRouterTargeting.Environment.inMr2022Holdback,
+ "Should not be in holdback (no experiment)"
+ );
+
+ {
+ const doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "majorRelease2022",
+ value: {
+ onboarding: true,
+ },
+ });
+
+ ok(
+ !ASRouterTargeting.Environment.inMr2022Holdback,
+ "Should not be in holdback (onboarding = true)"
+ );
+
+ await doExperimentCleanup();
+ }
+
+ {
+ const doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "majorRelease2022",
+ value: {
+ onboarding: false,
+ },
+ });
+
+ ok(
+ ASRouterTargeting.Environment.inMr2022Holdback,
+ "Should be in holdback (onboarding = false)"
+ );
+
+ await doExperimentCleanup();
+ }
+});
+
+add_task(async function test_distributionId() {
+ is(
+ ASRouterTargeting.Environment.distributionId,
+ "",
+ "Should return an empty distribution Id"
+ );
+
+ Services.prefs.getDefaultBranch(null).setCharPref("distribution.id", "test");
+
+ is(
+ ASRouterTargeting.Environment.distributionId,
+ "test",
+ "Should return the correct distribution Id"
+ );
+});
+
+add_task(async function test_fxViewButtonAreaType_default() {
+ is(
+ typeof (await ASRouterTargeting.Environment.fxViewButtonAreaType),
+ "string",
+ "Should return a string"
+ );
+
+ is(
+ await ASRouterTargeting.Environment.fxViewButtonAreaType,
+ "toolbar",
+ "Should return name of container if button hasn't been removed"
+ );
+});
+
+add_task(async function test_fxViewButtonAreaType_removed() {
+ CustomizableUI.removeWidgetFromArea("firefox-view-button");
+
+ is(
+ await ASRouterTargeting.Environment.fxViewButtonAreaType,
+ null,
+ "Should return null if button has been removed"
+ );
+ CustomizableUI.reset();
+});
+
+add_task(async function test_creditCardsSaved() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["extensions.formautofill.creditCards.supported", "on"],
+ ["extensions.formautofill.creditCards.enabled", true],
+ ],
+ });
+
+ is(
+ await ASRouterTargeting.Environment.creditCardsSaved,
+ 0,
+ "Should return 0 when no credit cards are saved"
+ );
+
+ let creditcard = {
+ "cc-name": "Test User",
+ "cc-number": "5038146897157463",
+ "cc-exp-month": "11",
+ "cc-exp-year": "20",
+ };
+
+ // Intermittently fails on macOS, likely related to Bug 1714221. So, mock the
+ // autofill actor.
+ if (AppConstants.platform === "macosx") {
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(async () => sandbox.restore());
+ let stub = sandbox
+ .stub(
+ gBrowser.selectedBrowser.browsingContext.currentWindowGlobal.getActor(
+ "FormAutofill"
+ ),
+ "receiveMessage"
+ )
+ .withArgs(
+ sandbox.match({
+ name: "FormAutofill:GetRecords",
+ data: { collectionName: "creditCards" },
+ })
+ )
+ .resolves([creditcard])
+ .callThrough();
+
+ is(
+ await ASRouterTargeting.Environment.creditCardsSaved,
+ 1,
+ "Should return 1 when 1 credit card is saved"
+ );
+ ok(
+ stub.calledWithMatch({ name: "FormAutofill:GetRecords" }),
+ "Targeting called FormAutofill:GetRecords"
+ );
+
+ sandbox.restore();
+ } else {
+ let observePromise = TestUtils.topicObserved(
+ "formautofill-storage-changed"
+ );
+ await sendFormAutofillMessage("FormAutofill:SaveCreditCard", {
+ creditcard,
+ });
+ await observePromise;
+
+ is(
+ await ASRouterTargeting.Environment.creditCardsSaved,
+ 1,
+ "Should return 1 when 1 credit card is saved"
+ );
+ await removeAutofillRecords();
+ }
+
+ await SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_addressesSaved() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["extensions.formautofill.addresses.supported", "on"],
+ ["extensions.formautofill.addresses.enabled", true],
+ ],
+ });
+
+ is(
+ await ASRouterTargeting.Environment.addressesSaved,
+ 0,
+ "Should return 0 when no addresses are saved"
+ );
+
+ let observePromise = TestUtils.topicObserved("formautofill-storage-changed");
+ await sendFormAutofillMessage("FormAutofill:SaveAddress", {
+ address: {
+ "given-name": "John",
+ "additional-name": "R.",
+ "family-name": "Smith",
+ organization: "World Wide Web Consortium",
+ "street-address": "32 Vassar Street\nMIT Room 32-G524",
+ "address-level2": "Cambridge",
+ "address-level1": "MA",
+ "postal-code": "02139",
+ country: "US",
+ tel: "+16172535702",
+ email: "timbl@w3.org",
+ },
+ });
+ await observePromise;
+
+ is(
+ await ASRouterTargeting.Environment.addressesSaved,
+ 1,
+ "Should return 1 when 1 address is saved"
+ );
+
+ await removeAutofillRecords();
+ await SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_migrationInteractions() {
+ await pushPrefs(
+ ["browser.migrate.interactions.bookmarks", false],
+ ["browser.migrate.interactions.history", false],
+ ["browser.migrate.interactions.passwords", false]
+ );
+
+ ok(!(await ASRouterTargeting.Environment.hasMigratedBookmarks));
+ ok(!(await ASRouterTargeting.Environment.hasMigratedHistory));
+ ok(!(await ASRouterTargeting.Environment.hasMigratedPasswords));
+
+ await pushPrefs(
+ ["browser.migrate.interactions.bookmarks", true],
+ ["browser.migrate.interactions.history", false],
+ ["browser.migrate.interactions.passwords", false]
+ );
+
+ ok(await ASRouterTargeting.Environment.hasMigratedBookmarks);
+ ok(!(await ASRouterTargeting.Environment.hasMigratedHistory));
+ ok(!(await ASRouterTargeting.Environment.hasMigratedPasswords));
+
+ await pushPrefs(
+ ["browser.migrate.interactions.bookmarks", true],
+ ["browser.migrate.interactions.history", true],
+ ["browser.migrate.interactions.passwords", false]
+ );
+
+ ok(await ASRouterTargeting.Environment.hasMigratedBookmarks);
+ ok(await ASRouterTargeting.Environment.hasMigratedHistory);
+ ok(!(await ASRouterTargeting.Environment.hasMigratedPasswords));
+
+ await pushPrefs(
+ ["browser.migrate.interactions.bookmarks", true],
+ ["browser.migrate.interactions.history", true],
+ ["browser.migrate.interactions.passwords", true]
+ );
+
+ ok(await ASRouterTargeting.Environment.hasMigratedBookmarks);
+ ok(await ASRouterTargeting.Environment.hasMigratedHistory);
+ ok(await ASRouterTargeting.Environment.hasMigratedPasswords);
+});
+
+add_task(async function check_useEmbeddedMigrationWizard() {
+ await pushPrefs([
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "default",
+ ]);
+
+ ok(!(await ASRouterTargeting.Environment.useEmbeddedMigrationWizard));
+
+ await pushPrefs([
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "autoclose",
+ ]);
+
+ ok(!(await ASRouterTargeting.Environment.useEmbeddedMigrationWizard));
+
+ await pushPrefs([
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "embedded",
+ ]);
+
+ ok(await ASRouterTargeting.Environment.useEmbeddedMigrationWizard);
+
+ await pushPrefs([
+ "browser.migrate.content-modal.about-welcome-behavior",
+ "standalone",
+ ]);
+
+ ok(!(await ASRouterTargeting.Environment.useEmbeddedMigrationWizard));
+});
+
+add_task(async function check_isRTAMO() {
+ is(
+ typeof ASRouterTargeting.Environment.isRTAMO,
+ "boolean",
+ "Should return a boolean"
+ );
+
+ const TEST_CASES = [
+ {
+ title: "no attribution data",
+ attributionData: {},
+ expected: false,
+ },
+ {
+ title: "null attribution data",
+ attributionData: null,
+ expected: false,
+ },
+ {
+ title: "no content",
+ attributionData: {
+ source: "addons.mozilla.org",
+ },
+ expected: false,
+ },
+ {
+ title: "empty content",
+ attributionData: {
+ source: "addons.mozilla.org",
+ content: "",
+ },
+ expected: false,
+ },
+ {
+ title: "null content",
+ attributionData: {
+ source: "addons.mozilla.org",
+ content: null,
+ },
+ expected: false,
+ },
+ {
+ title: "empty source",
+ attributionData: {
+ source: "",
+ },
+ expected: false,
+ },
+ {
+ title: "null source",
+ attributionData: {
+ source: null,
+ },
+ expected: false,
+ },
+ {
+ title: "valid attribution data for RTAMO with content not encoded",
+ attributionData: {
+ source: "addons.mozilla.org",
+ content: "rta:<encoded-addon-id>",
+ },
+ expected: true,
+ },
+ {
+ title: "valid attribution data for RTAMO with content encoded once",
+ attributionData: {
+ source: "addons.mozilla.org",
+ content: "rta%3A<encoded-addon-id>",
+ },
+ expected: true,
+ },
+ {
+ title: "valid attribution data for RTAMO with content encoded twice",
+ attributionData: {
+ source: "addons.mozilla.org",
+ content: "rta%253A<encoded-addon-id>",
+ },
+ expected: true,
+ },
+ {
+ title: "invalid source",
+ attributionData: {
+ source: "www.mozilla.org",
+ content: "rta%3A<encoded-addon-id>",
+ },
+ expected: false,
+ },
+ ];
+
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(async () => {
+ sandbox.restore();
+ });
+
+ const stub = sandbox.stub(AttributionCode, "getCachedAttributionData");
+
+ for (const { title, attributionData, expected } of TEST_CASES) {
+ stub.returns(attributionData);
+
+ is(
+ ASRouterTargeting.Environment.isRTAMO,
+ expected,
+ `${title} - Expected isRTAMO to have the expected value`
+ );
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function check_isDeviceMigration() {
+ is(
+ typeof ASRouterTargeting.Environment.isDeviceMigration,
+ "boolean",
+ "Should return a boolean"
+ );
+
+ const TEST_CASES = [
+ {
+ title: "no attribution data",
+ attributionData: {},
+ expected: false,
+ },
+ {
+ title: "null attribution data",
+ attributionData: null,
+ expected: false,
+ },
+ {
+ title: "no campaign",
+ attributionData: {
+ source: "support.mozilla.org",
+ },
+ expected: false,
+ },
+ {
+ title: "empty campaign",
+ attributionData: {
+ source: "support.mozilla.org",
+ campaign: "",
+ },
+ expected: false,
+ },
+ {
+ title: "null campaign",
+ attributionData: {
+ source: "addons.mozilla.org",
+ campaign: null,
+ },
+ expected: false,
+ },
+ {
+ title: "empty source",
+ attributionData: {
+ source: "",
+ },
+ expected: false,
+ },
+ {
+ title: "null source",
+ attributionData: {
+ source: null,
+ },
+ expected: false,
+ },
+ {
+ title: "other source",
+ attributionData: {
+ source: "www.mozilla.org",
+ campaign: "migration",
+ },
+ expected: true,
+ },
+ {
+ title: "valid attribution data for isDeviceMigration",
+ attributionData: {
+ source: "support.mozilla.org",
+ campaign: "migration",
+ },
+ expected: true,
+ },
+ ];
+
+ const sandbox = sinon.createSandbox();
+ registerCleanupFunction(async () => {
+ sandbox.restore();
+ });
+
+ const stub = sandbox.stub(AttributionCode, "getCachedAttributionData");
+
+ for (const { title, attributionData, expected } of TEST_CASES) {
+ stub.returns(attributionData);
+
+ is(
+ ASRouterTargeting.Environment.isDeviceMigration,
+ expected,
+ `${title} - Expected isDeviceMigration to have the expected value`
+ );
+ }
+
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_toast_notification.js b/browser/components/newtab/test/browser/browser_asrouter_toast_notification.js
new file mode 100644
index 0000000000..18f8594dbe
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_toast_notification.js
@@ -0,0 +1,139 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// At the time of writing, toast notifications (including XUL notifications)
+// don't support action buttons, so there's little to be tested here beyond
+// display.
+
+"use strict";
+
+const { ToastNotification } = ChromeUtils.import(
+ "resource://activity-stream/lib/ToastNotification.jsm"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+
+function getMessage(id) {
+ return PanelTestProvider.getMessages().then(msgs =>
+ msgs.find(m => m.id === id)
+ );
+}
+
+// Ensure we don't fall back to a real implementation.
+const showAlertStub = sinon.stub();
+const AlertsServiceStub = sinon.stub(ToastNotification, "AlertsService").value({
+ showAlert: showAlertStub,
+});
+
+registerCleanupFunction(() => {
+ AlertsServiceStub.restore();
+});
+
+// Test that toast notifications do, in fact, invoke the AlertsService. These
+// tests don't *need* to be `browser` tests, but we may eventually be able to
+// interact with the XUL notification elements, which would require `browser`
+// tests, so we follow suit with the equivalent `Spotlight`, etc, tests and use
+// the `browser` framework.
+add_task(async function test_showAlert() {
+ const l10n = new Localization([
+ "branding/brand.ftl",
+ "browser/newtab/asrouter.ftl",
+ ]);
+ let expectedTitle = await l10n.formatValue(
+ "cfr-doorhanger-bookmark-fxa-header"
+ );
+
+ showAlertStub.reset();
+
+ let dispatchStub = sinon.stub();
+
+ let message = await getMessage("TEST_TOAST_NOTIFICATION1");
+ await ToastNotification.showToastNotification(message, dispatchStub);
+
+ // Test display.
+ Assert.equal(
+ showAlertStub.callCount,
+ 1,
+ "AlertsService.showAlert is invoked"
+ );
+
+ let [alert] = showAlertStub.firstCall.args;
+ Assert.equal(alert.title, expectedTitle, "Should match");
+ Assert.equal(alert.text, "Body", "Should match");
+ Assert.equal(alert.name, "test_toast_notification", "Should match");
+});
+
+// Test that the `title` of each `action` of a toast notification is localized.
+add_task(async function test_actionLocalization() {
+ const l10n = new Localization([
+ "branding/brand.ftl",
+ "browser/newtab/asrouter.ftl",
+ ]);
+ let expectedTitle = await l10n.formatValue(
+ "mr2022-background-update-toast-title"
+ );
+ let expectedText = await l10n.formatValue(
+ "mr2022-background-update-toast-text"
+ );
+ let expectedPrimary = await l10n.formatValue(
+ "mr2022-background-update-toast-primary-button-label"
+ );
+ let expectedSecondary = await l10n.formatValue(
+ "mr2022-background-update-toast-secondary-button-label"
+ );
+
+ showAlertStub.reset();
+
+ let dispatchStub = sinon.stub();
+
+ let message = await getMessage("MR2022_BACKGROUND_UPDATE_TOAST_NOTIFICATION");
+ await ToastNotification.showToastNotification(message, dispatchStub);
+
+ // Test display.
+ Assert.equal(
+ showAlertStub.callCount,
+ 1,
+ "AlertsService.showAlert is invoked"
+ );
+
+ let [alert] = showAlertStub.firstCall.args;
+ Assert.equal(alert.title, expectedTitle, "Should match title");
+ Assert.equal(alert.text, expectedText, "Should match text");
+ Assert.equal(alert.name, "mr2022_background_update", "Should match");
+ Assert.equal(alert.actions[0].title, expectedPrimary, "Should match primary");
+ Assert.equal(
+ alert.actions[1].title,
+ expectedSecondary,
+ "Should match secondary"
+ );
+});
+
+// Test that toast notifications report sensible telemetry.
+add_task(async function test_telemetry() {
+ let dispatchStub = sinon.stub();
+
+ let message = await getMessage("TEST_TOAST_NOTIFICATION1");
+ await ToastNotification.showToastNotification(message, dispatchStub);
+
+ Assert.equal(
+ dispatchStub.callCount,
+ 2,
+ "1 IMPRESSION and 1 TOAST_NOTIFICATION_TELEMETRY"
+ );
+ Assert.equal(
+ dispatchStub.firstCall.args[0].type,
+ "TOAST_NOTIFICATION_TELEMETRY",
+ "Should match"
+ );
+ Assert.equal(
+ dispatchStub.firstCall.args[0].data.event,
+ "IMPRESSION",
+ "Should match"
+ );
+ Assert.equal(
+ dispatchStub.secondCall.args[0].type,
+ "IMPRESSION",
+ "Should match"
+ );
+});
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..f0089a2364
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js
@@ -0,0 +1,149 @@
+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(() => {
+ // Clicking on the Firefox Accounts button while in the signed out
+ // state opens a new tab for signing in.
+ // We'll clean those up here for now.
+ gBrowser.removeAllTabsBut(gBrowser.tabs[0]);
+ // Stop the load in the last tab that remains.
+ gBrowser.stop();
+ 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_context_menu_item.js b/browser/components/newtab/test/browser/browser_context_menu_item.js
new file mode 100644
index 0000000000..6a4883ab93
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_context_menu_item.js
@@ -0,0 +1,18 @@
+"use strict";
+
+// Test that we do not set icons in individual tile and card context menus on
+// newtab page.
+test_newtab({
+ 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");
+ },
+});
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..861814793a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_content.js
@@ -0,0 +1,222 @@
+"use strict";
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ ["browser.newtabpage.activity-stream.feeds.topsites", false],
+ ["browser.newtabpage.activity-stream.feeds.section.topstories", false],
+ ["browser.newtabpage.activity-stream.feeds.section.highlights", 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 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"
+ );
+ },
+ async after() {
+ 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"
+ );
+ },
+});
+
+test_newtab({
+ 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"
+ );
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.activeElement.classList.contains("close-button"),
+ "Close button should be focused when menu becomes visible"
+ );
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".personalize-button")
+ ).visibility === "hidden",
+ "Personalize button should become hidden"
+ );
+
+ // 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"
+ );
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.activeElement.classList.contains("personalize-button"),
+ "Personalize button should be focused when menu closes"
+ );
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".personalize-button")
+ ).visibility === "visible",
+ "Personalize button should become visible"
+ );
+
+ // 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"
+ );
+ },
+});
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..0ed761c181
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_render.js
@@ -0,0 +1,27 @@
+"use strict";
+
+// Test that the customization menu is rendered.
+test_newtab({
+ 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"
+ );
+ },
+});
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..8762160cb1
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_enabled_newtabpage.js
@@ -0,0 +1,33 @@
+function getSpec(uri) {
+ const { spec } = NetUtil.newChannel({
+ loadUsingSystemPrincipal: true,
+ uri,
+ }).URI;
+
+ info(`got ${spec} for ${uri}`);
+ return spec;
+}
+
+add_task(async function test_newtab_enabled() {
+ ok(
+ !getSpec("about:newtab").endsWith("/blanktab.html"),
+ "did not get blank for default about:newtab"
+ );
+ ok(
+ !getSpec("about:home").endsWith("/blanktab.html"),
+ "did not get blank for default about:home"
+ );
+
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.enabled", false]],
+ });
+
+ ok(
+ getSpec("about:newtab").endsWith("/blanktab.html"),
+ "got special blank page when newtab is not enabled"
+ );
+ ok(
+ !getSpec("about:home").endsWith("/blanktab.html"),
+ "got special blank page for about:home"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_feature_callout_in_chrome.js b/browser/components/newtab/test/browser/browser_feature_callout_in_chrome.js
new file mode 100644
index 0000000000..5eff75e31e
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_feature_callout_in_chrome.js
@@ -0,0 +1,487 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+const calloutId = "multi-stage-message-root";
+const calloutSelector = `#${calloutId}.featureCallout`;
+const primaryButtonSelector = `#${calloutId} .primary`;
+const PDF_TEST_URL =
+ "https://example.com/browser/browser/components/newtab/test/browser/file_pdf.PDF";
+
+const waitForCalloutScreen = async (doc, screenId) => {
+ await BrowserTestUtils.waitForCondition(() => {
+ return doc.querySelector(`${calloutSelector}:not(.hidden) .${screenId}`);
+ });
+};
+
+const waitForRemoved = async doc => {
+ await BrowserTestUtils.waitForCondition(() => {
+ return !doc.querySelector(calloutSelector);
+ });
+};
+
+async function openURLInWindow(window, url) {
+ const { selectedBrowser } = window.gBrowser;
+ BrowserTestUtils.loadURIString(selectedBrowser, url);
+ await BrowserTestUtils.browserLoaded(selectedBrowser, false, url);
+}
+
+async function openURLInNewTab(window, url) {
+ return BrowserTestUtils.openNewForegroundTab(window.gBrowser, url);
+}
+
+const pdfMatch = sinon.match(val => {
+ return val?.id === "featureCalloutCheck" && val?.context?.source === "chrome";
+});
+
+const validateCalloutCustomPosition = (element, positionOverride, doc) => {
+ const browserBox = doc.querySelector("hbox#browser");
+ for (let position in positionOverride) {
+ if (Object.prototype.hasOwnProperty.call(positionOverride, position)) {
+ // The substring here is to remove the `px` at the end of our position override strings
+ const relativePos = positionOverride[position].substring(
+ 0,
+ positionOverride[position].length - 2
+ );
+ const elPos = element.getBoundingClientRect()[position];
+ const browserPos = browserBox.getBoundingClientRect()[position];
+
+ if (position in ["top", "left"]) {
+ if (elPos !== browserPos + relativePos) {
+ return false;
+ }
+ } else if (position in ["right", "bottom"]) {
+ if (elPos !== browserPos - relativePos) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+};
+
+const validateCalloutRTLPosition = (element, positionOverride) => {
+ for (let position in positionOverride) {
+ if (Object.prototype.hasOwnProperty.call(positionOverride, position)) {
+ const pixelPosition = positionOverride[position];
+ if (position === "left") {
+ const actualLeft = Number(
+ pixelPosition.substring(0, pixelPosition.length - 2)
+ );
+ if (element.getBoundingClientRect().right !== actualLeft) {
+ return false;
+ }
+ } else if (position === "right") {
+ const expectedLeft = Number(
+ pixelPosition.substring(0, pixelPosition.length - 2)
+ );
+ if (element.getBoundingClientRect().left !== expectedLeft) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+};
+
+const testMessage = {
+ message: {
+ id: "TEST_MESSAGE",
+ template: "feature_callout",
+ content: {
+ id: "TEST_MESSAGE",
+ template: "multistage",
+ backdrop: "transparent",
+ transitions: false,
+ screens: [
+ {
+ id: "TEST_MESSAGE_1",
+ parent_selector: "#urlbar-container",
+ content: {
+ position: "callout",
+ arrow_position: "top-end",
+ title: {
+ raw: "Test title",
+ },
+ subtitle: {
+ raw: "Test subtitle",
+ },
+ primary_button: {
+ label: {
+ raw: "Done",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+ },
+ priority: 1,
+ targeting: "true",
+ trigger: { id: "featureCalloutCheck" },
+ },
+};
+
+const testMessageCalloutSelector = testMessage.message.content.screens[0].id;
+
+add_setup(async function () {
+ requestLongerTimeout(2);
+});
+
+add_task(async function feature_callout_renders_in_browser_chrome_for_pdf() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ await openURLInWindow(win, PDF_TEST_URL);
+ const doc = win.document;
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ const container = doc.querySelector(calloutSelector);
+ ok(
+ container,
+ "Feature Callout is rendered in the browser chrome with a new window when a message is available"
+ );
+
+ // click primary button to close
+ doc.querySelector(primaryButtonSelector).click();
+ await waitForRemoved(doc);
+ ok(
+ true,
+ "Feature callout removed from browser chrome after clicking button configured to navigate"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+});
+
+add_task(
+ async function feature_callout_renders_and_hides_in_chrome_when_switching_tabs() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+
+ const doc = win.document;
+ const tab1 = await BrowserTestUtils.openNewForegroundTab(
+ win.gBrowser,
+ PDF_TEST_URL
+ );
+ tab1.focus();
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ ok(
+ doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout rendered when opening a new tab with PDF url"
+ );
+
+ const tab2 = await openURLInNewTab(win, "about:preferences");
+ tab2.focus();
+ await BrowserTestUtils.waitForCondition(() => {
+ return !doc.body.querySelector(
+ "#multi-stage-message-root.featureCallout"
+ );
+ });
+
+ ok(
+ !doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout removed when tab without PDF URL is navigated to"
+ );
+
+ const tab3 = await openURLInNewTab(win, PDF_TEST_URL);
+ tab3.focus();
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ ok(
+ doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout still renders when opening a new tab with PDF url after being initially rendered on another tab"
+ );
+
+ tab1.focus();
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ ok(
+ doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout rendered on original tab after switching tabs multiple times"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function feature_callout_disappears_when_navigating_to_non_pdf_url_in_same_tab() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+
+ const doc = win.document;
+ const tab1 = await BrowserTestUtils.openNewForegroundTab(
+ win.gBrowser,
+ PDF_TEST_URL
+ );
+ tab1.focus();
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ ok(
+ doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout rendered when opening a new tab with PDF url"
+ );
+
+ BrowserTestUtils.loadURIString(win.gBrowser, "about:preferences");
+ await BrowserTestUtils.waitForLocationChange(
+ win.gBrowser,
+ "about:preferences"
+ );
+ await waitForRemoved(doc);
+
+ ok(
+ !doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout not rendered on original tab after navigating to non pdf URL"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function feature_callout_disappears_when_closing_foreground_pdf_tab() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+
+ const doc = win.document;
+ const tab1 = await BrowserTestUtils.openNewForegroundTab(
+ win.gBrowser,
+ PDF_TEST_URL
+ );
+ tab1.focus();
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ ok(
+ doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout rendered when opening a new tab with PDF url"
+ );
+
+ BrowserTestUtils.removeTab(tab1);
+ await waitForRemoved(doc);
+
+ ok(
+ !doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout disappears after closing foreground tab"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function feature_callout_does_not_appear_when_opening_background_pdf_tab() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ const doc = win.document;
+
+ const tab1 = await BrowserTestUtils.addTab(win.gBrowser, PDF_TEST_URL);
+ ok(
+ !doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout not rendered when opening a background tab with PDF url"
+ );
+
+ BrowserTestUtils.removeTab(tab1);
+
+ ok(
+ !doc.querySelector(`.${testMessageCalloutSelector}`),
+ "Feature callout still not rendered after closing background tab with PDF url"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function feature_callout_is_positioned_relative_to_browser_window() {
+ // Deep copying our test message so we can alter it without disrupting future tests
+ const pdfTestMessage = JSON.parse(JSON.stringify(testMessage));
+ const pdfTestMessageCalloutSelector =
+ pdfTestMessage.message.content.screens[0].id;
+
+ pdfTestMessage.message.content.screens[0].parent_selector = "hbox#browser";
+ pdfTestMessage.message.content.screens[0].content.callout_position_override =
+ {
+ top: "45px",
+ right: "25px",
+ };
+
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(pdfTestMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ await openURLInWindow(win, PDF_TEST_URL);
+ const doc = win.document;
+ await waitForCalloutScreen(doc, pdfTestMessageCalloutSelector);
+
+ // Verify that callout renders in appropriate position (without infobar element)
+ const callout = doc.querySelector(`.${pdfTestMessageCalloutSelector}`);
+ ok(callout, "Callout is rendered when navigating to PDF file");
+ ok(
+ validateCalloutCustomPosition(
+ callout,
+ pdfTestMessage.message.content.screens[0].content
+ .callout_position_override,
+ doc
+ ),
+ "Callout custom position is as expected"
+ );
+
+ // Add height to the top of the browser to simulate an infobar or other element
+ const navigatorToolBox = doc.querySelector("#navigator-toolbox-background");
+ navigatorToolBox.style.height = "150px";
+ // We test in a new tab because the callout does not adjust itself
+ // when size of the navigator-toolbox-background box changes.
+ const tab = await openURLInNewTab(win, "https://example.com/some2.pdf");
+ // Verify that callout renders in appropriate position (with infobar element displayed)
+ ok(
+ validateCalloutCustomPosition(
+ callout,
+ pdfTestMessage.message.content.screens[0].content
+ .callout_position_override,
+ doc
+ ),
+ "Callout custom position is as expected while navigator toolbox height is extended"
+ );
+ BrowserTestUtils.removeTab(tab);
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function custom_position_callout_is_horizontally_reversed_in_rtl_layouts() {
+ // Deep copying our test message so we can alter it without disrupting future tests
+ const pdfTestMessage = JSON.parse(JSON.stringify(testMessage));
+ const pdfTestMessageCalloutSelector =
+ pdfTestMessage.message.content.screens[0].id;
+
+ pdfTestMessage.message.content.screens[0].parent_selector = "hbox#browser";
+ pdfTestMessage.message.content.screens[0].content.callout_position_override =
+ {
+ top: "45px",
+ right: "25px",
+ };
+
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(pdfTestMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ win.document.dir = "rtl";
+ ok(
+ win.document.documentElement.getAttribute("dir") === "rtl",
+ "browser window is in RTL"
+ );
+
+ await openURLInWindow(win, PDF_TEST_URL);
+ const doc = win.document;
+ await waitForCalloutScreen(doc, pdfTestMessageCalloutSelector);
+
+ const callout = doc.querySelector(`.${pdfTestMessageCalloutSelector}`);
+ ok(callout, "Callout is rendered when navigating to PDF file");
+ ok(
+ validateCalloutRTLPosition(
+ callout,
+ pdfTestMessage.message.content.screens[0].content
+ .callout_position_override
+ ),
+ "Callout custom position is rendered appropriately in RTL mode"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
+
+add_task(async function feature_callout_dismissed_on_escape() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ await openURLInWindow(win, PDF_TEST_URL);
+ const doc = win.document;
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ const container = doc.querySelector(calloutSelector);
+ ok(
+ container,
+ "Feature Callout is rendered in the browser chrome with a new window when a message is available"
+ );
+
+ // Ensure the browser is focused
+ win.gBrowser.selectedBrowser.focus();
+
+ // Press Escape to close
+ EventUtils.synthesizeKey("KEY_Escape", {}, win);
+ await waitForRemoved(doc);
+ ok(true, "Feature callout dismissed after pressing Escape");
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+});
+
+add_task(
+ async function feature_callout_not_dismissed_on_escape_with_interactive_elm_focused() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
+ sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
+ sendTriggerStub.callThrough();
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ await openURLInWindow(win, PDF_TEST_URL);
+ const doc = win.document;
+ await waitForCalloutScreen(doc, testMessageCalloutSelector);
+ const container = doc.querySelector(calloutSelector);
+ ok(
+ container,
+ "Feature Callout is rendered in the browser chrome with a new window when a message is available"
+ );
+
+ // Ensure an interactive element is focused
+ win.gURLBar.focus();
+
+ // Press Escape to close
+ EventUtils.synthesizeKey("KEY_Escape", {}, win);
+ await TestUtils.waitForTick();
+ // Wait 500ms for transition to complete
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ await new Promise(resolve => setTimeout(resolve, 500));
+ ok(
+ doc.querySelector(calloutSelector),
+ "Feature callout is not dismissed after pressing Escape because an interactive element is focused"
+ );
+
+ await BrowserTestUtils.closeWindow(win);
+ sandbox.restore();
+ }
+);
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..d73e4eb361
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_highlights_section.js
@@ -0,0 +1,96 @@
+"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() {
+ 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"
+ );
+ removeBookmarkBtn.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelectorAll(
+ "[data-section-id='highlights'] .card-outer:not(.placeholder)"
+ ),
+ "no more bookmark cards should be visible"
+ );
+ }
+);
diff --git a/browser/components/newtab/test/browser/browser_multistage_spotlight.js b/browser/components/newtab/test/browser/browser_multistage_spotlight.js
new file mode 100644
index 0000000000..bbaf64a9e3
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_multistage_spotlight.js
@@ -0,0 +1,58 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { Spotlight } = ChromeUtils.import(
+ "resource://activity-stream/lib/Spotlight.jsm"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+const { BrowserWindowTracker } = ChromeUtils.import(
+ "resource:///modules/BrowserWindowTracker.jsm"
+);
+const { SpecialMessageActions } = ChromeUtils.importESModule(
+ "resource://messaging-system/lib/SpecialMessageActions.sys.mjs"
+);
+
+async function waitForClick(selector, win) {
+ await TestUtils.waitForCondition(() => win.document.querySelector(selector));
+ win.document.querySelector(selector).click();
+}
+
+async function showDialog(dialogOptions) {
+ Spotlight.showSpotlightDialog(
+ dialogOptions.browser,
+ dialogOptions.message,
+ dialogOptions.dispatchStub
+ );
+ const [win] = await TestUtils.topicObserved("subdialog-loaded");
+ return win;
+}
+
+add_task(async function test_specialAction() {
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "MULTISTAGE_SPOTLIGHT_MESSAGE"
+ );
+ let dispatchStub = sinon.stub();
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let specialActionStub = sinon.stub(SpecialMessageActions, "handleAction");
+
+ let win = await showDialog({ message, browser, dispatchStub });
+ await waitForClick("button.primary", win);
+ win.close();
+
+ Assert.equal(
+ specialActionStub.callCount,
+ 1,
+ "Should be called by primary action"
+ );
+ Assert.deepEqual(
+ specialActionStub.firstCall.args[0],
+ message.content.screens[0].content.primary_button.action,
+ "Should be called with button action"
+ );
+
+ specialActionStub.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js b/browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js
new file mode 100644
index 0000000000..c9c4baad83
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js
@@ -0,0 +1,145 @@
+"use strict";
+
+const { Spotlight } = ChromeUtils.import(
+ "resource://activity-stream/lib/Spotlight.jsm"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+const { BrowserWindowTracker } = ChromeUtils.import(
+ "resource:///modules/BrowserWindowTracker.jsm"
+);
+
+const { AboutWelcomeTelemetry } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm"
+);
+
+async function waitForClick(selector, win) {
+ await TestUtils.waitForCondition(() => win.document.querySelector(selector));
+ win.document.querySelector(selector).click();
+}
+
+function waitForDialog(callback = win => win.close()) {
+ return BrowserTestUtils.promiseAlertDialog(
+ null,
+ "chrome://browser/content/spotlight.html",
+ { callback, isSubDialog: true }
+ );
+}
+
+function showAndWaitForDialog(dialogOptions, callback) {
+ const promise = waitForDialog(callback);
+ Spotlight.showSpotlightDialog(
+ dialogOptions.browser,
+ dialogOptions.message,
+ dialogOptions.dispatchStub
+ );
+ return promise;
+}
+
+add_task(async function send_spotlight_as_page_in_telemetry() {
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "MULTISTAGE_SPOTLIGHT_MESSAGE"
+ );
+ let dispatchStub = sinon.stub();
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let sandbox = sinon.createSandbox();
+
+ await showAndWaitForDialog({ message, browser, dispatchStub }, async win => {
+ let stub = sandbox.stub(win, "AWSendEventTelemetry");
+ await waitForClick("button.secondary", win);
+ Assert.equal(
+ stub.lastCall.args[0].event_context.page,
+ "spotlight",
+ "The value of event context page should be set to 'spotlight' in event telemetry"
+ );
+ win.close();
+ });
+
+ sandbox.restore();
+});
+
+add_task(async function send_dismiss_event_telemetry() {
+ // Have to turn on AS telemetry for anything to be recorded.
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+ registerCleanupFunction(async () => {
+ await SpecialPowers.popPrefEnv();
+ });
+
+ const messageId = "MULTISTAGE_SPOTLIGHT_MESSAGE";
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === messageId
+ );
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let sandbox = sinon.createSandbox();
+ sandbox
+ .stub(AboutWelcomeTelemetry.prototype, "pingCentre")
+ .value({ sendStructuredIngestionPing: () => {} });
+ let spy = sandbox.spy(AboutWelcomeTelemetry.prototype, "sendTelemetry");
+ // send without a dispatch function so that default is used
+ let pingSubmitted = false;
+ await showAndWaitForDialog({ message, browser }, async win => {
+ await waitForClick("button.dismiss-button", win);
+ await win.close();
+ // To catch the `DISMISS` and not any of the earlier events
+ // triggering "messaging-system" pings, we must position this synchronously
+ // _after_ the window closes but before `showAndWaitForDialog`'s callback
+ // completes.
+ // Too early and we'll catch an earlier event like `CLICK`.
+ // Too late and we'll not catch any event at all.
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+
+ Assert.equal(
+ messageId,
+ Glean.messagingSystem.messageId.testGetValue(),
+ "Glean was given the correct message_id"
+ );
+ Assert.equal(
+ "DISMISS",
+ Glean.messagingSystem.event.testGetValue(),
+ "Glean was given the correct event"
+ );
+ });
+ });
+
+ Assert.equal(
+ spy.lastCall.args[0].message_id,
+ messageId,
+ "A dismiss event is called with the correct message id"
+ );
+
+ Assert.equal(
+ spy.lastCall.args[0].event,
+ "DISMISS",
+ "A dismiss event is called with a top level event field with value 'DISMISS'"
+ );
+
+ Assert.ok(pingSubmitted, "The Glean ping was submitted.");
+
+ sandbox.restore();
+});
+
+add_task(
+ async function do_not_send_impression_telemetry_from_default_dispatch() {
+ // Don't send impression telemetry from the Spotlight default dispatch function
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "MULTISTAGE_SPOTLIGHT_MESSAGE"
+ );
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let sandbox = sinon.createSandbox();
+ let stub = sandbox.stub(AboutWelcomeTelemetry.prototype, "sendTelemetry");
+ // send without a dispatch function so that default is used
+ await showAndWaitForDialog({ message, browser });
+
+ Assert.equal(
+ stub.calledOn(),
+ false,
+ "No extra impression event was sent for multistage Spotlight"
+ );
+
+ sandbox.restore();
+ }
+);
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..adfecbe71f
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_header.js
@@ -0,0 +1,76 @@
+"use strict";
+
+// Tests 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({
+ 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 topSitesSection = content.document.querySelector(".top-sites");
+ let titleContainer = topSitesSection.querySelector(
+ ".section-title-container"
+ );
+ ok(
+ titleContainer && titleContainer.style.visibility === "hidden",
+ "Top sites header should not be visible"
+ );
+
+ 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"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js b/browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js
new file mode 100644
index 0000000000..2c58c9a48c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js
@@ -0,0 +1,151 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function setupPrefs() {
+ await setDefaultTopSites();
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "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: false,
+ layout_endpoint:
+ "https://example.com/browser/browser/components/newtab/test/browser/ds_layout.json",
+ }),
+ ],
+ [
+ "browser.newtabpage.activity-stream.discoverystream.endpoints",
+ "https://example.com",
+ ],
+ ],
+ });
+}
+
+async function resetPrefs() {
+ // We set 5 prefs in setupPrefs, so we should reset 5 prefs.
+ // 1 popPrefEnv from pushPrefEnv
+ // and 4 popPrefEnv happen internally in setDefaultTopSites.
+ await SpecialPowers.popPrefEnv();
+ await SpecialPowers.popPrefEnv();
+ await SpecialPowers.popPrefEnv();
+ await SpecialPowers.popPrefEnv();
+ await SpecialPowers.popPrefEnv();
+}
+
+let initialHeight;
+let initialWidth;
+function setSize(width, height) {
+ initialHeight = window.innerHeight;
+ initialWidth = window.innerWidth;
+ let resizePromise = BrowserTestUtils.waitForEvent(window, "resize", false);
+ window.resizeTo(width, height);
+ return resizePromise;
+}
+
+function resetSize() {
+ let resizePromise = BrowserTestUtils.waitForEvent(window, "resize", false);
+ window.resizeTo(initialWidth, initialHeight);
+ return resizePromise;
+}
+
+add_task(async function test_newtab_last_LinkMenu() {
+ await setupPrefs();
+
+ // Open about:newtab without using the default load listener
+ 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 BrowserTestUtils.waitForCondition(
+ () =>
+ SpecialPowers.spawn(
+ browser,
+ [],
+ () => content.document.getElementById("root").children.length
+ ),
+ "Should render activity stream content"
+ );
+
+ // Set the window to a small enough size to trigger menus that might overflow.
+ await setSize(600, 450);
+
+ // Test context menu position for topsites.
+ await SpecialPowers.spawn(browser, [], async () => {
+ // Topsites might not be ready, so wait for the button.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ ".top-site-outer:nth-child(2n) .context-menu-button"
+ ),
+ "Wait for the Pocket card and button"
+ );
+ const topsiteOuter = content.document.querySelector(
+ ".top-site-outer:nth-child(2n)"
+ );
+ const topsiteContextMenuButton = topsiteOuter.querySelector(
+ ".context-menu-button"
+ );
+
+ topsiteContextMenuButton.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => topsiteOuter.classList.contains("active"),
+ "Wait for the menu to be active"
+ );
+
+ is(
+ content.window.scrollMaxX,
+ 0,
+ "there should be no horizontal scroll bar"
+ );
+ });
+
+ // Test context menu position for topstories.
+ await SpecialPowers.spawn(browser, [], async () => {
+ // Pocket section might take a bit more time to load,
+ // so wait for the button to be ready.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ ".ds-card:nth-child(1n) .context-menu-button"
+ ),
+ "Wait for the Pocket card and button"
+ );
+
+ const dsCard = content.document.querySelector(".ds-card:nth-child(1n)");
+ const dsCarContextMenuButton = dsCard.querySelector(".context-menu-button");
+
+ dsCarContextMenuButton.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => dsCard.classList.contains("active"),
+ "Wait for the menu to be active"
+ );
+
+ is(
+ content.window.scrollMaxX,
+ 0,
+ "there should be no horizontal scroll bar"
+ );
+ });
+
+ // Resetting the window size to what it was.
+ await resetSize();
+ // Resetting prefs we set for this test.
+ await resetPrefs();
+ BrowserTestUtils.removeTab(tab);
+});
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..ce7d82881f
--- /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_newtab_ping.js b/browser/components/newtab/test/browser/browser_newtab_ping.js
new file mode 100644
index 0000000000..42ff22a57d
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_ping.js
@@ -0,0 +1,216 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { AboutNewTab } = ChromeUtils.import(
+ "resource:///modules/AboutNewTab.jsm"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+const { ExperimentFakes } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+
+let sendTriggerMessageSpy;
+
+add_setup(function () {
+ let sandbox = sinon.createSandbox();
+ sendTriggerMessageSpy = sandbox.spy(ASRouter, "sendTriggerMessage");
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+add_task(async function test_newtab_tab_close_sends_ping() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+
+ Services.fog.testResetFOG();
+ sendTriggerMessageSpy.resetHistory();
+ let TelemetryFeed =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ TelemetryFeed.init(); // INIT action doesn't happen by default.
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ false // waitForLoad; about:newtab is cached so this would never resolve
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => sendTriggerMessageSpy.called,
+ "After about:newtab finishes loading"
+ );
+ sendTriggerMessageSpy.resetHistory();
+
+ await BrowserTestUtils.waitForCondition(
+ () => !!Glean.newtab.opened.testGetValue("newtab"),
+ "We expect the newtab open to be recorded"
+ );
+ let record = Glean.newtab.opened.testGetValue("newtab");
+ Assert.equal(record.length, 1, "Should only be one open");
+ const sessionId = record[0].extra.newtab_visit_id;
+ Assert.ok(!!sessionId, "newtab_visit_id must be present");
+
+ let pingSubmitted = false;
+ GleanPings.newtab.testBeforeNextSubmit(reason => {
+ pingSubmitted = true;
+ Assert.equal(reason, "newtab_session_end");
+ record = Glean.newtab.closed.testGetValue("newtab");
+ Assert.equal(record.length, 1, "Should only have one close");
+ Assert.equal(
+ record[0].extra.newtab_visit_id,
+ sessionId,
+ "Should've closed the session we opened"
+ );
+ Assert.ok(Glean.newtabSearch.enabled.testGetValue());
+ Assert.ok(Glean.topsites.enabled.testGetValue());
+ Assert.ok(Glean.topsites.sponsoredEnabled.testGetValue());
+ Assert.ok(Glean.pocket.enabled.testGetValue());
+ Assert.ok(Glean.pocket.sponsoredStoriesEnabled.testGetValue());
+ Assert.equal(false, Glean.pocket.isSignedIn.testGetValue());
+ });
+
+ BrowserTestUtils.removeTab(tab);
+ await BrowserTestUtils.waitForCondition(
+ () => pingSubmitted,
+ "We expect the ping to have submitted."
+ );
+ await SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_newtab_tab_nav_sends_ping() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+
+ Services.fog.testResetFOG();
+ sendTriggerMessageSpy.resetHistory();
+ let TelemetryFeed =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ TelemetryFeed.init(); // INIT action doesn't happen by default.
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ false // waitForLoad; about:newtab is cached so this would never resolve
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => sendTriggerMessageSpy.called,
+ "After about:newtab finishes loading"
+ );
+ sendTriggerMessageSpy.resetHistory();
+
+ await BrowserTestUtils.waitForCondition(
+ () => !!Glean.newtab.opened.testGetValue("newtab"),
+ "We expect the newtab open to be recorded"
+ );
+ let record = Glean.newtab.opened.testGetValue("newtab");
+ Assert.equal(record.length, 1, "Should only be one open");
+ const sessionId = record[0].extra.newtab_visit_id;
+ Assert.ok(!!sessionId, "newtab_visit_id must be present");
+
+ let pingSubmitted = false;
+ GleanPings.newtab.testBeforeNextSubmit(reason => {
+ pingSubmitted = true;
+ Assert.equal(reason, "newtab_session_end");
+ record = Glean.newtab.closed.testGetValue("newtab");
+ Assert.equal(record.length, 1, "Should only have one close");
+ Assert.equal(
+ record[0].extra.newtab_visit_id,
+ sessionId,
+ "Should've closed the session we opened"
+ );
+ Assert.ok(Glean.newtabSearch.enabled.testGetValue());
+ Assert.ok(Glean.topsites.enabled.testGetValue());
+ Assert.ok(Glean.topsites.sponsoredEnabled.testGetValue());
+ Assert.ok(Glean.pocket.enabled.testGetValue());
+ Assert.ok(Glean.pocket.sponsoredStoriesEnabled.testGetValue());
+ Assert.equal(false, Glean.pocket.isSignedIn.testGetValue());
+ });
+
+ BrowserTestUtils.loadURIString(tab.linkedBrowser, "about:mozilla");
+ await BrowserTestUtils.waitForCondition(
+ () => pingSubmitted,
+ "We expect the ping to have submitted."
+ );
+
+ BrowserTestUtils.removeTab(tab);
+ await SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_newtab_doesnt_send_nimbus() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+
+ let doEnrollmentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
+ featureId: "glean",
+ value: { newtabPingEnabled: false },
+ });
+ Services.fog.testResetFOG();
+ let TelemetryFeed =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ TelemetryFeed.init(); // INIT action doesn't happen by default.
+ sendTriggerMessageSpy.resetHistory();
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ false // waitForLoad; about:newtab is cached so this would never resolve
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => sendTriggerMessageSpy.called,
+ "After about:newtab finishes loading"
+ );
+ sendTriggerMessageSpy.resetHistory();
+
+ await BrowserTestUtils.waitForCondition(
+ () => !!Glean.newtab.opened.testGetValue("newtab"),
+ "We expect the newtab open to be recorded"
+ );
+ let record = Glean.newtab.opened.testGetValue("newtab");
+ Assert.equal(record.length, 1, "Should only be one open");
+ const sessionId = record[0].extra.newtab_visit_id;
+ Assert.ok(!!sessionId, "newtab_visit_id must be present");
+
+ GleanPings.newtab.testBeforeNextSubmit(() => {
+ Assert.ok(false, "Must not submit ping!");
+ });
+ BrowserTestUtils.loadURIString(tab.linkedBrowser, "about:mozilla");
+ BrowserTestUtils.removeTab(tab);
+ await BrowserTestUtils.waitForCondition(() => {
+ let { sessions } =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ return !Array.from(sessions.entries()).filter(
+ ([k, v]) => v.session_id === sessionId
+ ).length;
+ }, "Waiting for sessions to clean up.");
+ // Session ended without a ping being sent. Success!
+ await doEnrollmentCleanup();
+ await SpecialPowers.popPrefEnv();
+});
+
+add_task(async function test_newtab_categorization_sends_ping() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.activity-stream.telemetry", true]],
+ });
+
+ Services.fog.testResetFOG();
+ sendTriggerMessageSpy.resetHistory();
+ let TelemetryFeed =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ let pingSent = false;
+ GleanPings.newtab.testBeforeNextSubmit(reason => {
+ pingSent = true;
+ Assert.equal(reason, "component_init");
+ });
+ await TelemetryFeed.sendPageTakeoverData();
+ Assert.ok(pingSent, "ping was sent");
+
+ await SpecialPowers.popPrefEnv();
+});
diff --git a/browser/components/newtab/test/browser/browser_newtab_towindow.js b/browser/components/newtab/test/browser/browser_newtab_towindow.js
new file mode 100644
index 0000000000..d0a49e63f0
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_towindow.js
@@ -0,0 +1,45 @@
+// This test simulates opening the newtab page and moving it to a new window.
+// Links in the page should still work.
+add_task(async function test_newtab_to_window() {
+ await setTestTopSites();
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ false
+ );
+
+ let swappedPromise = BrowserTestUtils.waitForEvent(
+ tab.linkedBrowser,
+ "SwapDocShells"
+ );
+ let newWindow = gBrowser.replaceTabWithWindow(tab);
+ await swappedPromise;
+
+ is(
+ newWindow.gBrowser.selectedBrowser.currentURI.spec,
+ "about:newtab",
+ "about:newtab moved to window"
+ );
+
+ let tabPromise = BrowserTestUtils.waitForNewTab(
+ newWindow.gBrowser,
+ "https://example.com/",
+ true
+ );
+
+ await BrowserTestUtils.synthesizeMouse(
+ `.top-sites a`,
+ 2,
+ 2,
+ { accelKey: true },
+ newWindow.gBrowser.selectedBrowser
+ );
+
+ await tabPromise;
+
+ is(newWindow.gBrowser.tabs.length, 2, "second page is opened");
+
+ BrowserTestUtils.removeTab(newWindow.gBrowser.selectedTab);
+ await BrowserTestUtils.closeWindow(newWindow);
+});
diff --git a/browser/components/newtab/test/browser/browser_newtab_trigger.js b/browser/components/newtab/test/browser/browser_newtab_trigger.js
new file mode 100644
index 0000000000..dbc1b71e21
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_trigger.js
@@ -0,0 +1,50 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+let sendTriggerMessageSpy;
+let triggerMatch;
+
+add_setup(function () {
+ let sandbox = sinon.createSandbox();
+ sendTriggerMessageSpy = sandbox.spy(ASRouter, "sendTriggerMessage");
+ triggerMatch = sandbox.match({ id: "defaultBrowserCheck" });
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+async function testPageTrigger(url, waitForLoad, expectedTrigger) {
+ sendTriggerMessageSpy.resetHistory();
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ url,
+ waitForLoad
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => sendTriggerMessageSpy.calledWith(expectedTrigger),
+ `After ${url} finishes loading`
+ );
+ Assert.ok(
+ sendTriggerMessageSpy.calledWith(expectedTrigger),
+ `Found the expected ${expectedTrigger.id} trigger`
+ );
+
+ BrowserTestUtils.removeTab(tab);
+ sendTriggerMessageSpy.resetHistory();
+}
+
+add_task(function test_newtab_trigger() {
+ return testPageTrigger("about:newtab", false, triggerMatch);
+});
+
+add_task(function test_abouthome_trigger() {
+ return testPageTrigger("about:home", true, triggerMatch);
+});
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_remote_l10n.js b/browser/components/newtab/test/browser/browser_remote_l10n.js
new file mode 100644
index 0000000000..967236a721
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_remote_l10n.js
@@ -0,0 +1,56 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { RemoteL10n } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/RemoteL10n.sys.mjs"
+);
+
+const ID = "remote_l10n_test_string";
+const VALUE = "RemoteL10n string";
+const CONTENT = `${ID} = ${VALUE}`;
+
+add_setup(async () => {
+ const l10nRegistryInstance = L10nRegistry.getInstance();
+ const localProfileDir = Services.dirsvc.get("ProfD", Ci.nsIFile).path;
+ const dirPath = PathUtils.join(
+ localProfileDir,
+ ...["settings", "main", "ms-language-packs", "browser", "newtab"]
+ );
+ const filePath = PathUtils.join(dirPath, "asrouter.ftl");
+
+ await IOUtils.makeDirectory(dirPath, {
+ ignoreExisting: true,
+ from: localProfileDir,
+ });
+ await IOUtils.writeUTF8(filePath, CONTENT, {
+ tmpPath: `${filePath}.tmp`,
+ });
+
+ // Remove any cached l10n resources, "cfr" is the cache key
+ // used for strings from the remote `asrouter.ftl` see RemoteL10n.sys.mjs
+ RemoteL10n.reloadL10n();
+ if (l10nRegistryInstance.hasSource("cfr")) {
+ l10nRegistryInstance.removeSources(["cfr"]);
+ }
+});
+
+add_task(async function test_TODO() {
+ let [{ value }] = await RemoteL10n.l10n.formatMessages([{ id: ID }]);
+
+ Assert.equal(value, VALUE, "Got back the string we wrote to disk");
+});
+
+// Test that the formatting helper works. This helper is lower-level than the
+// DOM localization apparatus, and as such doesn't require the weight of the
+// `browser` test framework, but it's nice to co-locate related tests.
+add_task(async function test_formatLocalizableText() {
+ let value = await RemoteL10n.formatLocalizableText({ string_id: ID });
+
+ Assert.equal(value, VALUE, "Got back the string we wrote to disk");
+
+ value = await RemoteL10n.formatLocalizableText("unchanged");
+
+ Assert.equal(value, "unchanged", "Got back the string provided");
+});
diff --git a/browser/components/newtab/test/browser/browser_topsites_annotation.js b/browser/components/newtab/test/browser/browser_topsites_annotation.js
new file mode 100644
index 0000000000..7e48868fca
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_annotation.js
@@ -0,0 +1,980 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test whether a visit information is annotated correctly when clicking a tile.
+
+if (AppConstants.platform === "macosx") {
+ requestLongerTimeout(4);
+} else {
+ requestLongerTimeout(2);
+}
+
+ChromeUtils.defineESModuleGetters(this, {
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
+ TelemetryTestUtils: "resource://testing-common/TelemetryTestUtils.sys.mjs",
+ UrlbarTestUtils: "resource://testing-common/UrlbarTestUtils.sys.mjs",
+});
+
+const OPEN_TYPE = {
+ CURRENT_BY_CLICK: 0,
+ NEWTAB_BY_CLICK: 1,
+ NEWTAB_BY_MIDDLECLICK: 2,
+ NEWTAB_BY_CONTEXTMENU: 3,
+ NEWWINDOW_BY_CONTEXTMENU: 4,
+ NEWWINDOW_BY_CONTEXTMENU_OF_TILE: 5,
+};
+
+const FRECENCY = {
+ TYPED: 2000,
+ VISITED: 100,
+ SPONSORED: -1,
+ BOOKMARKED: 2075,
+ MIDDLECLICK_TYPED: 100,
+ MIDDLECLICK_BOOKMARKED: 175,
+ NEWWINDOW_TYPED: 100,
+ NEWWINDOW_BOOKMARKED: 175,
+};
+
+const {
+ VISIT_SOURCE_ORGANIC,
+ VISIT_SOURCE_SPONSORED,
+ VISIT_SOURCE_BOOKMARKED,
+} = PlacesUtils.history;
+
+/**
+ * To be used before checking database contents when they depend on a visit
+ * being added to History.
+ * @param {string} href the page to await notifications for.
+ */
+async function waitForVisitNotification(href) {
+ await PlacesTestUtils.waitForNotification("page-visited", events =>
+ events.some(e => e.url === href)
+ );
+}
+
+async function assertDatabase({ targetURL, expected }) {
+ const frecency = await PlacesTestUtils.getDatabaseValue(
+ "moz_places",
+ "frecency",
+ { url: targetURL }
+ );
+ Assert.equal(frecency, expected.frecency, "Frecency is correct");
+
+ const placesId = await PlacesTestUtils.getDatabaseValue("moz_places", "id", {
+ url: targetURL,
+ });
+ const expectedTriggeringPlaceId = expected.triggerURL
+ ? await PlacesTestUtils.getDatabaseValue("moz_places", "id", {
+ url: expected.triggerURL,
+ })
+ : null;
+ const db = await PlacesUtils.promiseDBConnection();
+ const rows = await db.execute(
+ "SELECT source, triggeringPlaceId FROM moz_historyvisits WHERE place_id = :place_id AND source = :source",
+ {
+ place_id: placesId,
+ source: expected.source,
+ }
+ );
+ Assert.equal(rows.length, 1);
+ Assert.equal(
+ rows[0].getResultByName("triggeringPlaceId"),
+ expectedTriggeringPlaceId,
+ `The triggeringPlaceId in database is correct for ${targetURL}`
+ );
+}
+
+async function waitForLocationChanged(destinationURL) {
+ // If nodeIconChanged of browserPlacesViews.js is called after the target node
+ // is lost during test, "No DOM node set for aPlacesNode" error occur. To avoid
+ // this failure, wait for the onLocationChange event that triggers
+ // nodeIconChanged to occur.
+ return new Promise(resolve => {
+ gBrowser.addTabsProgressListener({
+ async onLocationChange(aBrowser, aWebProgress, aRequest, aLocation) {
+ if (aLocation.spec === destinationURL) {
+ gBrowser.removeTabsProgressListener(this);
+ // Wait for an empty Promise to ensure to proceed our test after
+ // finishing the processing of other onLocatoinChanged events.
+ await Promise.resolve();
+ resolve();
+ }
+ },
+ });
+ });
+}
+
+async function openAndTest({
+ linkSelector,
+ linkURL,
+ redirectTo = null,
+ openType = OPEN_TYPE.CURRENT_BY_CLICK,
+ expected,
+}) {
+ const destinationURL = redirectTo || linkURL;
+
+ // Wait for content is ready.
+ await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [linkSelector, linkURL],
+ async (selector, link) => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(selector).href === link
+ );
+ }
+ );
+
+ info("Open specific link by type and wait for loading.");
+ let promiseVisited = waitForVisitNotification(destinationURL);
+ if (openType === OPEN_TYPE.CURRENT_BY_CLICK) {
+ const onLoad = BrowserTestUtils.browserLoaded(
+ gBrowser.selectedBrowser,
+ false,
+ destinationURL
+ );
+ const onLocationChanged = waitForLocationChanged(destinationURL);
+
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ linkSelector,
+ {},
+ gBrowser.selectedBrowser
+ );
+
+ await onLoad;
+ await onLocationChanged;
+ } else if (openType === OPEN_TYPE.NEWTAB_BY_CLICK) {
+ const onLoad = BrowserTestUtils.waitForNewTab(
+ gBrowser,
+ destinationURL,
+ true
+ );
+ const onLocationChanged = waitForLocationChanged(destinationURL);
+
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ linkSelector,
+ { ctrlKey: true, metaKey: true },
+ gBrowser.selectedBrowser
+ );
+
+ const tab = await onLoad;
+ await onLocationChanged;
+ BrowserTestUtils.removeTab(tab);
+ } else if (openType === OPEN_TYPE.NEWTAB_BY_MIDDLECLICK) {
+ const onLoad = BrowserTestUtils.waitForNewTab(
+ gBrowser,
+ destinationURL,
+ true
+ );
+ const onLocationChanged = waitForLocationChanged(destinationURL);
+
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ linkSelector,
+ { button: 1 },
+ gBrowser.selectedBrowser
+ );
+
+ const tab = await onLoad;
+ await onLocationChanged;
+ BrowserTestUtils.removeTab(tab);
+ } else if (openType === OPEN_TYPE.NEWTAB_BY_CONTEXTMENU) {
+ const onLoad = BrowserTestUtils.waitForNewTab(
+ gBrowser,
+ destinationURL,
+ true
+ );
+ const onLocationChanged = waitForLocationChanged(destinationURL);
+
+ const onPopup = BrowserTestUtils.waitForEvent(document, "popupshown");
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ linkSelector,
+ { type: "contextmenu" },
+ gBrowser.selectedBrowser
+ );
+ await onPopup;
+ const contextMenu = document.getElementById("contentAreaContextMenu");
+ const openLinkMenuItem = contextMenu.querySelector(
+ "#context-openlinkintab"
+ );
+ contextMenu.activateItem(openLinkMenuItem);
+
+ const tab = await onLoad;
+ await onLocationChanged;
+ BrowserTestUtils.removeTab(tab);
+ } else if (openType === OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU) {
+ const onLoad = BrowserTestUtils.waitForNewWindow({ url: destinationURL });
+
+ const onPopup = BrowserTestUtils.waitForEvent(document, "popupshown");
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ linkSelector,
+ { type: "contextmenu" },
+ gBrowser.selectedBrowser
+ );
+ await onPopup;
+ const contextMenu = document.getElementById("contentAreaContextMenu");
+ const openLinkMenuItem = contextMenu.querySelector("#context-openlink");
+ contextMenu.activateItem(openLinkMenuItem);
+
+ const win = await onLoad;
+ await BrowserTestUtils.closeWindow(win);
+ } else if (openType === OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU_OF_TILE) {
+ const onLoad = BrowserTestUtils.waitForNewWindow({ url: destinationURL });
+
+ await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [linkSelector],
+ async selector => {
+ const link = content.document.querySelector(selector);
+ const list = link.closest("li");
+ const contextMenu = list.querySelector(".context-menu-button");
+ contextMenu.click();
+ const target = list.querySelector(
+ "[data-l10n-id=newtab-menu-open-new-window]"
+ );
+ target.click();
+ }
+ );
+
+ const win = await onLoad;
+ await BrowserTestUtils.closeWindow(win);
+ }
+ await promiseVisited;
+
+ info("Check database for the destination.");
+ await assertDatabase({ targetURL: destinationURL, expected });
+}
+
+async function pin(link) {
+ // Setup test tile.
+ NewTabUtils.pinnedLinks.pin(link, 0);
+ await toggleTopsitesPref();
+ await BrowserTestUtils.waitForCondition(() => {
+ const sites = AboutNewTab.getTopSites();
+ return (
+ sites?.[0]?.url === link.url &&
+ sites[0].sponsored_tile_id === link.sponsored_tile_id
+ );
+ }, "Waiting for top sites to be updated");
+}
+
+function unpin(link) {
+ NewTabUtils.pinnedLinks.unpin(link);
+}
+
+add_setup(async function () {
+ await clearHistoryAndBookmarks();
+ registerCleanupFunction(async () => {
+ await clearHistoryAndBookmarks();
+ });
+});
+
+add_task(async function basic() {
+ const SPONSORED_LINK = {
+ label: "test_label",
+ url: "https://example.com/",
+ sponsored_position: 1,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "https://impression.example.com/",
+ sponsored_click_url: "https://click.example.com/",
+ };
+ const NORMAL_LINK = {
+ label: "test_label",
+ url: "https://example.com/",
+ };
+ const BOOKMARKS = [
+ {
+ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
+ url: Services.io.newURI("https://example.com/"),
+ title: "test bookmark",
+ },
+ ];
+
+ const testData = [
+ {
+ description: "Sponsored tile",
+ link: SPONSORED_LINK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Sponsored tile in new tab by click with key",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Sponsored tile in new tab by middle click",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Sponsored tile in new tab by context menu",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Sponsored tile in new window by context menu",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Sponsored tile in new window by context menu of tile",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU_OF_TILE,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ },
+ {
+ description: "Bookmarked result",
+ link: NORMAL_LINK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description: "Bookmarked result in new tab by click with key",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description: "Bookmarked result in new tab by middle click",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.MIDDLECLICK_BOOKMARKED,
+ },
+ },
+ {
+ description: "Bookmarked result in new tab by context menu",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CONTEXTMENU,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.MIDDLECLICK_BOOKMARKED,
+ },
+ },
+ {
+ description: "Bookmarked result in new window by context menu",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.NEWWINDOW_BOOKMARKED,
+ },
+ },
+ {
+ description: "Bookmarked result in new window by context menu of tile",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU_OF_TILE,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_BOOKMARKED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description: "Sponsored and bookmarked result",
+ link: SPONSORED_LINK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description:
+ "Sponsored and bookmarked result in new tab by click with key",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description: "Sponsored and bookmarked result in new tab by middle click",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.MIDDLECLICK_BOOKMARKED,
+ },
+ },
+ {
+ description: "Sponsored and bookmarked result in new tab by context menu",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CONTEXTMENU,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.MIDDLECLICK_BOOKMARKED,
+ },
+ },
+ {
+ description:
+ "Sponsored and bookmarked result in new window by context menu",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.NEWWINDOW_BOOKMARKED,
+ },
+ },
+ {
+ description:
+ "Sponsored and bookmarked result in new window by context menu of tile",
+ link: SPONSORED_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU_OF_TILE,
+ bookmarks: BOOKMARKS,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.BOOKMARKED,
+ },
+ },
+ {
+ description: "Organic tile",
+ link: NORMAL_LINK,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.TYPED,
+ },
+ },
+ {
+ description: "Organic tile in new tab by click with key",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.TYPED,
+ },
+ },
+ {
+ description: "Organic tile in new tab by middle click",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.MIDDLECLICK_TYPED,
+ },
+ },
+ {
+ description: "Organic tile in new tab by context menu",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWTAB_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.MIDDLECLICK_TYPED,
+ },
+ },
+ {
+ description: "Organic tile in new window by context menu",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.NEWWINDOW_TYPED,
+ },
+ },
+ {
+ description: "Organic tile in new window by context menu of tile",
+ link: NORMAL_LINK,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU_OF_TILE,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.TYPED,
+ },
+ },
+ ];
+
+ for (const { description, link, openType, bookmarks, expected } of testData) {
+ info(description);
+
+ await BrowserTestUtils.withNewTab("about:home", async () => {
+ // Setup test tile.
+ await pin(link);
+
+ for (const bookmark of bookmarks || []) {
+ await PlacesUtils.bookmarks.insert(bookmark);
+ }
+
+ await openAndTest({
+ linkSelector: ".top-site-button",
+ linkURL: link.url,
+ openType,
+ expected,
+ });
+
+ await clearHistoryAndBookmarks();
+
+ unpin(link);
+ });
+ }
+});
+
+add_task(async function redirection() {
+ await BrowserTestUtils.withNewTab("about:home", async () => {
+ const redirectTo = "https://example.com/";
+ const link = {
+ label: "test_label",
+ url: "https://example.com/browser/browser/components/newtab/test/browser/redirect_to.sjs?/",
+ sponsored_position: 1,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "https://impression.example.com/",
+ sponsored_click_url: "https://click.example.com/",
+ };
+
+ // Setup test tile.
+ await pin(link);
+
+ // Test with new tab.
+ await openAndTest({
+ linkSelector: ".top-site-button",
+ linkURL: link.url,
+ redirectTo,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+
+ // Check for URL causes the redirection.
+ await assertDatabase({
+ targetURL: link.url,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+ await clearHistoryAndBookmarks();
+
+ // Test with same tab.
+ await openAndTest({
+ linkSelector: ".top-site-button",
+ linkURL: link.url,
+ redirectTo,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+
+ // Check for URL causes the redirection.
+ await assertDatabase({
+ targetURL: link.url,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+ await clearHistoryAndBookmarks();
+ unpin(link);
+ });
+});
+
+add_task(async function inherit() {
+ const host = "https://example.com/";
+ const sameBaseDomainHost = "https://www.example.com/";
+ const path = "browser/browser/components/newtab/test/browser/";
+ const firstURL = `${host}${path}annotation_first.html`;
+ const secondURL = `${host}${path}annotation_second.html`;
+ const thirdURL = `${sameBaseDomainHost}${path}annotation_third.html`;
+ const outsideURL = "https://example.org/";
+
+ await BrowserTestUtils.withNewTab("about:home", async () => {
+ const link = {
+ label: "first",
+ url: firstURL,
+ sponsored_position: 1,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "https://impression.example.com/",
+ sponsored_click_url: "https://click.example.com/",
+ };
+
+ // Setup test tile.
+ await pin(link);
+
+ info("Open the tile to show first page in same tab");
+ await openAndTest({
+ linkSelector: ".top-site-button",
+ linkURL: link.url,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+
+ info("Open link on first page to show second page in new window");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on first page to show second page in new tab by click with key"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on first page to show second page in new tab by middle click"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info("Open link on first page to show second page in same tab");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+
+ info("Open link on first page to show second page in new window");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: thirdURL,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on second page to show third page in new tab by context menu"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: thirdURL,
+ openType: OPEN_TYPE.NEWTAB_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on second page to show third page in new tab by middle click"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: thirdURL,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info("Open link on second page to show third page in same tab");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: thirdURL,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+
+ info("Open link on third page to show outside domain page in same tab");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: outsideURL,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.VISITED,
+ },
+ });
+
+ info("Visit URL that has the same domain as sponsored link from URL bar");
+ const onLoad = BrowserTestUtils.browserLoaded(
+ gBrowser.selectedBrowser,
+ false,
+ host
+ );
+ await UrlbarTestUtils.promiseAutocompleteResultPopup({
+ window,
+ value: host,
+ waitForFocus: SimpleTest.waitForFocus,
+ });
+ let promiseVisited = waitForVisitNotification(host);
+ EventUtils.synthesizeKey("KEY_Enter");
+ await onLoad;
+ await promiseVisited;
+
+ await assertDatabase({
+ targetURL: host,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ triggerURL: link.url,
+ },
+ });
+
+ unpin(link);
+ await clearHistoryAndBookmarks();
+ });
+});
+
+add_task(async function timeout() {
+ const base =
+ "https://example.com/browser/browser/components/newtab/test/browser";
+ const firstURL = `${base}/annotation_first.html`;
+ const secondURL = `${base}/annotation_second.html`;
+
+ await BrowserTestUtils.withNewTab("about:home", async () => {
+ const link = {
+ label: "test",
+ url: firstURL,
+ sponsored_position: 1,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "https://impression.example.com/",
+ sponsored_click_url: "https://click.example.com/",
+ };
+
+ // Setup a test tile.
+ await pin(link);
+
+ info("Open the tile");
+ await openAndTest({
+ linkSelector: ".top-site-button",
+ linkURL: link.url,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+
+ info("Set timeout second");
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.places.sponsoredSession.timeoutSecs", 1]],
+ });
+
+ info("Wait 1 sec");
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ await new Promise(r => setTimeout(r, 1000));
+
+ info("Open link on first page to show second page in new window");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWWINDOW_BY_CONTEXTMENU,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.VISITED,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on first page to show second page in new tab by click with key"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWTAB_BY_CLICK,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.VISITED,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info(
+ "Open link on first page to show second page in new tab by middle click"
+ );
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ openType: OPEN_TYPE.NEWTAB_BY_MIDDLECLICK,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.VISITED,
+ },
+ });
+ await PlacesTestUtils.clearHistoryVisits();
+
+ info("Open link on first page to show second page");
+ await openAndTest({
+ linkSelector: "a",
+ linkURL: secondURL,
+ expected: {
+ source: VISIT_SOURCE_ORGANIC,
+ frecency: FRECENCY.VISITED,
+ },
+ });
+
+ unpin(link);
+ await clearHistoryAndBookmarks();
+ });
+});
+
+add_task(async function fixup() {
+ await BrowserTestUtils.withNewTab("about:home", async () => {
+ const destinationURL = "https://example.com/?a";
+ const link = {
+ label: "test",
+ url: "https://example.com?a",
+ sponsored_position: 1,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "https://impression.example.com/",
+ sponsored_click_url: "https://click.example.com/",
+ };
+
+ info("Setup pin");
+ await pin(link);
+
+ info("Click sponsored tile");
+ let promiseVisited = waitForVisitNotification(destinationURL);
+ const onLoad = BrowserTestUtils.browserLoaded(
+ gBrowser.selectedBrowser,
+ false,
+ destinationURL
+ );
+ const onLocationChanged = waitForLocationChanged(destinationURL);
+ await BrowserTestUtils.synthesizeMouseAtCenter(
+ ".top-site-button",
+ {},
+ gBrowser.selectedBrowser
+ );
+ await onLoad;
+ await onLocationChanged;
+ await promiseVisited;
+
+ info("Check the DB");
+ await assertDatabase({
+ targetURL: destinationURL,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+
+ info("Clean up");
+ unpin(link);
+ await clearHistoryAndBookmarks();
+ });
+});
+
+add_task(async function noTriggeringURL() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ Services.telemetry.clearScalars();
+
+ const dummyTriggeringSponsoredURL =
+ "https://example.com/dummyTriggeringSponsoredURL";
+ const targetURL = "https://example.com/";
+
+ info("Setup dummy triggering sponsored URL");
+ browser.setAttribute("triggeringSponsoredURL", dummyTriggeringSponsoredURL);
+ browser.setAttribute("triggeringSponsoredURLVisitTimeMS", Date.now());
+
+ info("Open URL whose host is the same as dummy triggering sponsored URL");
+ let promiseVisited = waitForVisitNotification(targetURL);
+ await UrlbarTestUtils.promiseAutocompleteResultPopup({
+ window,
+ value: targetURL,
+ waitForFocus: SimpleTest.waitForFocus,
+ });
+ const onLoad = BrowserTestUtils.browserLoaded(
+ gBrowser.selectedBrowser,
+ false,
+ targetURL
+ );
+ EventUtils.synthesizeKey("KEY_Enter");
+ await onLoad;
+ await promiseVisited;
+
+ info("Check DB");
+ await assertDatabase({
+ targetURL,
+ expected: {
+ source: VISIT_SOURCE_SPONSORED,
+ frecency: FRECENCY.SPONSORED,
+ },
+ });
+
+ info("Check telemetry");
+ const scalars = TelemetryTestUtils.getProcessScalars("parent", false, true);
+ TelemetryTestUtils.assertScalar(
+ scalars,
+ "places.sponsored_visit_no_triggering_url",
+ 1
+ );
+
+ await clearHistoryAndBookmarks();
+ });
+});
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..c744e8ee01
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js
@@ -0,0 +1,126 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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({
+ async before() {
+ // Some reason test-linux1804-64-qr/debug can end up with example.com, so
+ // clear history so we only have the expected default top sites.
+ await clearHistoryAndBookmarks();
+ await 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
+ );
+
+ Assert.equal(contextMenuItems.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 < contextMenuItems.length; i++) {
+ await ContentTaskUtils.waitForCondition(
+ () => contextMenuItems[i].textContent === 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
+ );
+ await ContentTaskUtils.waitForCondition(
+ () => 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..9cbb49bf2f
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_section.js
@@ -0,0 +1,299 @@
+"use strict";
+
+// Check TopSites edit modal and overlay show up.
+test_newtab({
+ before: setTestTopSites,
+ // it should be able to click the topsites add button to reveal the add top site modal and overlay.
+ test: async function topsites_edit() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites .context-menu-button"),
+ "Should find a visible topsite context menu button [topsites_edit]"
+ );
+
+ // Open the section context menu.
+ content.document.querySelector(".top-sites .context-menu-button").click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites .context-menu"),
+ "Should find a visible topsite context menu [topsites_edit]"
+ );
+
+ const topsitesAddBtn = content.document.querySelector(
+ ".top-sites li:nth-child(2) 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: setTestTopSites,
+ // 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 });
+
+ // Wait for context menu button to load
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites .context-menu-button"),
+ "Should find a visible topsite context menu button [topsites_add]"
+ );
+
+ content.document.querySelector(".top-sites .context-menu-button").click();
+
+ // Wait for context menu to load
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites .context-menu"),
+ "Should find a visible topsite context menu [topsites_add]"
+ );
+
+ // Find topsites edit button
+ const topsitesAddBtn = content.document.querySelector(
+ ".top-sites li:nth-child(2) button"
+ );
+
+ topsitesAddBtn.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".modalOverlayOuter"),
+ "No overlay found"
+ );
+
+ 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("[href='https://bugzilla.mozilla.org']"),
+ "No Topsite found"
+ );
+
+ // Remove topsite after test is complete
+ let topsiteContextBtn = content.document.querySelector(
+ ".top-sites-list li:nth-child(1) .context-menu-button"
+ );
+ topsiteContextBtn.click();
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites-list .context-menu"),
+ "No context menu found"
+ );
+
+ const dismissBtn = content.document.querySelector(
+ ".top-sites li:nth-child(7) button"
+ );
+ dismissBtn.click();
+
+ // Wait for Topsite to be removed
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ !content.document.querySelector(
+ "[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 1 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,
+ isGeneralPurposeEngine: false,
+ },
+ "The Urlbar is in search mode."
+ );
+ ok(
+ gURLBar.hasAttribute("searchmode"),
+ "The Urlbar has the searchmode attribute."
+ );
+ },
+});
+
+// test_newtab is not used here as this test requires two steps into the
+// content process with chrome process activity in-between.
+add_task(async function test_search_topsite_remove_engine() {
+ // Open about:newtab without using the default load listener
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ 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"
+ );
+
+ await setDefaultTopSites();
+
+ let [topSiteAlias, numTopSites] = await SpecialPowers.spawn(
+ browser,
+ [],
+ async () => {
+ 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 one topsite");
+ return [searchTopSites[0].innerText.trim(), searchTopSites.length];
+ }
+ );
+
+ await Services.search.removeEngine(
+ await Services.search.getEngineByAlias(topSiteAlias)
+ );
+
+ registerCleanupFunction(() => {
+ Services.search.restoreDefaultEngines();
+ });
+
+ await SpecialPowers.spawn(
+ browser,
+ [numTopSites],
+ async originalNumTopSites => {
+ await ContentTaskUtils.waitForCondition(
+ () => !content.document.querySelector(".search-shortcut .title.pinned"),
+ "Wait for pinned search topsites"
+ );
+
+ const searchTopSites = content.document.querySelectorAll(".title.pinned");
+ is(
+ searchTopSites.length,
+ originalNumTopSites - 1,
+ "There should be one less search topsites"
+ );
+ }
+ );
+
+ BrowserTestUtils.removeTab(tab);
+});
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..c7a502fdd0
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_trigger_listeners.js
@@ -0,0 +1,343 @@
+const { ASRouterTriggerListeners } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTriggerListeners.jsm"
+);
+
+const mockIdleService = {
+ _observers: new Set(),
+ _fireObservers(state) {
+ for (let observer of this._observers.values()) {
+ observer.observe(this, state, null);
+ }
+ },
+ QueryInterface: ChromeUtils.generateQI(["nsIUserIdleService"]),
+ idleTime: 1200000,
+ addIdleObserver(observer, time) {
+ this._observers.add(observer);
+ },
+ removeIdleObserver(observer, time) {
+ this._observers.delete(observer);
+ },
+};
+
+const sleepMs = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms)); // eslint-disable-line mozilla/no-arbitrary-setTimeout
+
+const inChaosMode = !!parseInt(Services.env.get("MOZ_CHAOSMODE"), 16);
+
+add_setup(async function () {
+ // Runtime increases in chaos mode on Mac.
+ if (inChaosMode && AppConstants.platform === "macosx") {
+ requestLongerTimeout(2);
+ }
+
+ 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"
+ );
+});
+
+add_task(async function test_captivePortalLogin() {
+ const stub = sinon.stub();
+ const captivePortalTrigger =
+ ASRouterTriggerListeners.get("captivePortalLogin");
+
+ captivePortalTrigger.init(stub);
+
+ Services.obs.notifyObservers(this, "captive-portal-login-success", {});
+
+ Assert.ok(stub.called, "Called after login event");
+
+ captivePortalTrigger.uninit();
+
+ Services.obs.notifyObservers(this, "captive-portal-login-success", {});
+
+ Assert.equal(stub.callCount, 1, "Not called after uninit");
+});
+
+add_task(async function test_preferenceObserver() {
+ const stub = sinon.stub();
+ const poTrigger = ASRouterTriggerListeners.get("preferenceObserver");
+
+ poTrigger.uninit();
+
+ poTrigger.init(stub, ["foo.bar", "bar.foo"]);
+
+ Services.prefs.setStringPref("foo.bar", "foo.bar");
+
+ Assert.ok(stub.calledOnce, "Called for pref foo.bar");
+ Assert.deepEqual(
+ stub.firstCall.args[1],
+ {
+ id: "preferenceObserver",
+ param: { type: "foo.bar" },
+ },
+ "Called with expected arguments"
+ );
+
+ Services.prefs.setStringPref("bar.foo", "bar.foo");
+ Assert.ok(stub.calledTwice, "Called again for second pref.");
+ Services.prefs.clearUserPref("foo.bar");
+ Assert.ok(stub.calledThrice, "Called when clearing the pref as well.");
+
+ stub.resetHistory();
+ poTrigger.uninit();
+
+ Services.prefs.clearUserPref("bar.foo");
+ Assert.ok(stub.notCalled, "Not called after uninit");
+});
+
+add_task(async function test_nthTabClosed() {
+ const handlerStub = sinon.stub();
+ const tabClosedTrigger = ASRouterTriggerListeners.get("nthTabClosed");
+ tabClosedTrigger.uninit();
+ tabClosedTrigger.init(handlerStub);
+
+ let tab1 = await BrowserTestUtils.openNewForegroundTab(gBrowser);
+ let tab2 = await BrowserTestUtils.openNewForegroundTab(gBrowser);
+
+ BrowserTestUtils.removeTab(tab1);
+ Assert.ok(handlerStub.calledOnce, "Called once after first tab closed");
+
+ BrowserTestUtils.removeTab(tab2);
+ Assert.ok(handlerStub.calledTwice, "Called twice after second tab closed");
+
+ handlerStub.resetHistory();
+ tabClosedTrigger.uninit();
+
+ Assert.ok(handlerStub.notCalled, "Not called after uninit");
+});
+
+add_task(async function test_cookieBannerDetected() {
+ const handlerStub = sinon.stub();
+ const bannerDetectedTrigger = ASRouterTriggerListeners.get(
+ "cookieBannerDetected"
+ );
+ bannerDetectedTrigger.uninit();
+ bannerDetectedTrigger.init(handlerStub);
+
+ const win = await BrowserTestUtils.openNewBrowserWindow();
+ let eventWait = BrowserTestUtils.waitForEvent(win, "cookiebannerdetected");
+ win.dispatchEvent(new Event("cookiebannerdetected"));
+ await eventWait;
+ let closeWindow = BrowserTestUtils.closeWindow(win);
+
+ Assert.ok(
+ handlerStub.called,
+ "Called after `cookiebannerdetected` event fires"
+ );
+
+ handlerStub.resetHistory();
+ bannerDetectedTrigger.uninit();
+
+ Assert.ok(handlerStub.notCalled, "Not called after uninit");
+ await closeWindow;
+});
+
+function getIdleTriggerMock() {
+ const idleTrigger = ASRouterTriggerListeners.get("activityAfterIdle");
+ idleTrigger.uninit();
+ const sandbox = sinon.createSandbox();
+ const handlerStub = sandbox.stub();
+ sandbox.stub(idleTrigger, "_triggerDelay").value(0);
+ sandbox.stub(idleTrigger, "_wakeDelay").value(30);
+ sandbox.stub(idleTrigger, "_idleService").value(mockIdleService);
+ let restored = false;
+ const restore = () => {
+ if (restored) return;
+ restored = true;
+ idleTrigger.uninit();
+ sandbox.restore();
+ };
+ registerCleanupFunction(restore);
+ idleTrigger.init(handlerStub);
+ return { idleTrigger, handlerStub, restore };
+}
+
+// Test that the trigger fires under normal conditions.
+add_task(async function test_activityAfterIdle() {
+ const { handlerStub, restore } = getIdleTriggerMock();
+ let firedOnActive = new Promise(resolve =>
+ handlerStub.callsFake(() => resolve(true))
+ );
+ mockIdleService._fireObservers("idle");
+ await TestUtils.waitForTick();
+ ok(handlerStub.notCalled, "Not called when idle");
+ mockIdleService._fireObservers("active");
+ ok(await firedOnActive, "Called once when active after idle");
+ restore();
+});
+
+// Test that the trigger does not fire when the active window is private.
+add_task(async function test_activityAfterIdlePrivateWindow() {
+ const { handlerStub, restore } = getIdleTriggerMock();
+ let privateWin = await BrowserTestUtils.openNewBrowserWindow({
+ private: true,
+ });
+ ok(PrivateBrowsingUtils.isWindowPrivate(privateWin), "Window is private");
+ await TestUtils.waitForTick();
+ mockIdleService._fireObservers("idle");
+ await TestUtils.waitForTick();
+ mockIdleService._fireObservers("active");
+ await TestUtils.waitForTick();
+ ok(handlerStub.notCalled, "Not called when active window is private");
+ await BrowserTestUtils.closeWindow(privateWin);
+ restore();
+});
+
+// Test that the trigger does not fire when the window is minimized, but does
+// fire after the window is restored.
+add_task(async function test_activityAfterIdleHiddenWindow() {
+ const { handlerStub, restore } = getIdleTriggerMock();
+ let firedOnRestore = new Promise(resolve =>
+ handlerStub.callsFake(() => resolve(true))
+ );
+ window.minimize();
+ await BrowserTestUtils.waitForCondition(
+ () => window.windowState === window.STATE_MINIMIZED,
+ "Window should be minimized"
+ );
+ mockIdleService._fireObservers("idle");
+ await TestUtils.waitForTick();
+ mockIdleService._fireObservers("active");
+ await TestUtils.waitForTick();
+ ok(handlerStub.notCalled, "Not called when window is minimized");
+ window.restore();
+ ok(await firedOnRestore, "Called once after restoring minimized window");
+ restore();
+});
+
+// Test that the trigger does not fire immediately after waking from sleep.
+add_task(async function test_activityAfterIdleWake() {
+ const { handlerStub, restore } = getIdleTriggerMock();
+ let firedAfterWake = new Promise(resolve =>
+ handlerStub.callsFake(() => resolve(true))
+ );
+ mockIdleService._fireObservers("wake_notification");
+ mockIdleService._fireObservers("idle");
+ await sleepMs(1);
+ mockIdleService._fireObservers("active");
+ await sleepMs(inChaosMode ? 32 : 300);
+ ok(handlerStub.notCalled, "Not called immediately after waking from sleep");
+
+ mockIdleService._fireObservers("idle");
+ await TestUtils.waitForTick();
+ mockIdleService._fireObservers("active");
+ ok(
+ await firedAfterWake,
+ "Called once after waiting for wake delay before firing idle"
+ );
+ restore();
+});
+
+add_task(async function test_formAutofillTrigger() {
+ const sandbox = sinon.createSandbox();
+ const handlerStub = sandbox.stub();
+ const formAutofillTrigger = ASRouterTriggerListeners.get("formAutofill");
+ sandbox.stub(formAutofillTrigger, "_triggerDelay").value(0);
+ formAutofillTrigger.uninit();
+ formAutofillTrigger.init(handlerStub);
+
+ function notifyCreditCardSaved() {
+ Services.obs.notifyObservers(
+ {
+ wrappedJSObject: { sourceSync: false, collectionName: "creditCards" },
+ },
+ formAutofillTrigger._topic,
+ "add"
+ );
+ }
+
+ // Saving credit cards for autofill currently fails for some hardware
+ // configurations, so mock the event instead of really adding a card.
+ notifyCreditCardSaved();
+ await sleepMs(1);
+ Assert.ok(handlerStub.called, "Called after event");
+
+ // Test that the trigger doesn't fire when the credit card manager is open.
+ handlerStub.resetHistory();
+ await BrowserTestUtils.withNewTab(
+ { gBrowser, url: "about:preferences#privacy" },
+ async browser => {
+ await SpecialPowers.spawn(browser, [], async () =>
+ (
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector("#creditCardAutofill button"),
+ "Waiting for credit card manager button"
+ )
+ )?.click()
+ );
+ await BrowserTestUtils.waitForCondition(
+ () => browser.contentWindow?.gSubDialog?.dialogs.length
+ );
+ notifyCreditCardSaved();
+ await sleepMs(1);
+ Assert.ok(
+ handlerStub.notCalled,
+ "Not called when credit card manager is open"
+ );
+ }
+ );
+
+ formAutofillTrigger.uninit();
+ handlerStub.resetHistory();
+ notifyCreditCardSaved();
+ await sleepMs(1);
+ Assert.ok(handlerStub.notCalled, "Not called after uninit");
+
+ sandbox.restore();
+ formAutofillTrigger.uninit();
+});
diff --git a/browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js b/browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js
new file mode 100644
index 0000000000..8168715289
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js
@@ -0,0 +1,152 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettings } = ChromeUtils.importESModule(
+ "resource://services-settings/remote-settings.sys.mjs"
+);
+const { RemoteSettingsExperimentLoader } = ChromeUtils.importESModule(
+ "resource://nimbus/lib/RemoteSettingsExperimentLoader.sys.mjs"
+);
+const { ExperimentAPI } = ChromeUtils.importESModule(
+ "resource://nimbus/ExperimentAPI.sys.mjs"
+);
+const { ExperimentFakes, ExperimentTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/NimbusTestUtils.sys.mjs"
+);
+
+const client = RemoteSettings("nimbus-desktop-experiments");
+
+const TEST_MESSAGE_CONTENT = {
+ id: "ON_LOAD_TEST_MESSAGE",
+ template: "cfr_doorhanger",
+ content: {
+ bucket_id: "ON_LOAD_TEST_MESSAGE",
+ anchor_id: "PanelUI-menu-button",
+ layout: "icon_and_message",
+ icon: "chrome://browser/content/cfr-lightning.svg",
+ icon_dark_theme: "chrome://browser/content/cfr-lightning-dark.svg",
+ icon_class: "cfr-doorhanger-small-icon",
+ heading_text: "Heading",
+ text: "Text",
+ buttons: {
+ primary: {
+ label: { value: "Primary CTA", attributes: { accesskey: "P" } },
+ action: { navigate: true },
+ },
+ secondary: [
+ {
+ label: { value: "Secondary CTA", attributes: { accesskey: "S" } },
+ action: { type: "CANCEL" },
+ },
+ ],
+ },
+ skip_address_bar_notifier: true,
+ },
+ targeting: "true",
+ trigger: { id: "messagesLoaded" },
+};
+
+add_task(async function test_messagesLoaded_reach_experiment() {
+ const sandbox = sinon.createSandbox();
+ const sendTriggerSpy = sandbox.spy(ASRouter, "sendTriggerMessage");
+ const routeSpy = sandbox.spy(ASRouter, "routeCFRMessage");
+ const reachSpy = sandbox.spy(ASRouter, "_recordReachEvent");
+ const triggerMatch = sandbox.match({ id: "messagesLoaded" });
+ const featureId = "cfr";
+ const recipe = ExperimentFakes.recipe(
+ `messages_loaded_test_${Services.uuid
+ .generateUUID()
+ .toString()
+ .slice(1, -1)}`,
+ {
+ id: `messages-loaded-test`,
+ bucketConfig: {
+ count: 100,
+ start: 0,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ branches: [
+ {
+ slug: "control",
+ ratio: 1,
+ features: [
+ {
+ featureId,
+ value: { ...TEST_MESSAGE_CONTENT, id: "messages-loaded-test-1" },
+ },
+ ],
+ },
+ {
+ slug: "treatment",
+ ratio: 1,
+ features: [
+ {
+ featureId,
+ value: { ...TEST_MESSAGE_CONTENT, id: "messages-loaded-test-2" },
+ },
+ ],
+ },
+ ],
+ }
+ );
+ Assert.ok(
+ await ExperimentTestUtils.validateExperiment(recipe),
+ "Valid recipe"
+ );
+
+ await client.db.importChanges({}, Date.now(), [recipe], { clear: true });
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["app.shield.optoutstudies.enabled", true],
+ ["datareporting.healthreport.uploadEnabled", true],
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.messaging-experiments",
+ `{"id":"messaging-experiments","enabled":true,"type":"remote-experiments","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+
+ const filterFn = m =>
+ ["messages-loaded-test-1", "messages-loaded-test-2"].includes(m?.id);
+ await BrowserTestUtils.waitForCondition(
+ () => ASRouter.state.messages.filter(filterFn).length > 1,
+ "Should load the test messages"
+ );
+ Assert.ok(sendTriggerSpy.calledWith(triggerMatch, true), "Trigger fired");
+ Assert.ok(
+ routeSpy.calledWith(
+ sandbox.match(filterFn),
+ gBrowser.selectedBrowser,
+ triggerMatch
+ ),
+ "Trigger routed to the correct message"
+ );
+ Assert.ok(
+ reachSpy.calledWith(sandbox.match(filterFn)),
+ "Trigger recorded a reach event"
+ );
+ Assert.ok(
+ ASRouter.state.messages.find(m => filterFn(m) && m.forReachEvent)
+ ?.forReachEvent.sent,
+ "Reach message will not be sent again"
+ );
+
+ sandbox.restore();
+ await client.db.clear();
+ await SpecialPowers.popPrefEnv();
+ await ASRouter._updateMessageProviders();
+});
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..b9c7e6b4ba
--- /dev/null
+++ b/browser/components/newtab/test/browser/ds_layout.json
@@ -0,0 +1,90 @@
+{
+ "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://global/skin/icons/pocket.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/file_pdf.PDF b/browser/components/newtab/test/browser/file_pdf.PDF
new file mode 100644
index 0000000000..593558f9a4
--- /dev/null
+++ b/browser/components/newtab/test/browser/file_pdf.PDF
@@ -0,0 +1,12 @@
+%PDF-1.0
+1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj
+xref
+0 4
+0000000000 65535 f
+0000000010 00000 n
+0000000053 00000 n
+0000000102 00000 n
+trailer<</Size 4/Root 1 0 R>>
+startxref
+149
+%EOF \ No newline at end of file
diff --git a/browser/components/newtab/test/browser/head.js b/browser/components/newtab/test/browser/head.js
new file mode 100644
index 0000000000..cc0239e148
--- /dev/null
+++ b/browser/components/newtab/test/browser/head.js
@@ -0,0 +1,392 @@
+"use strict";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "ObjectUtils",
+ "resource://gre/modules/ObjectUtils.jsm"
+);
+ChromeUtils.defineESModuleGetters(this, {
+ PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
+});
+ChromeUtils.defineModuleGetter(
+ this,
+ "QueryCache",
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+// eslint-disable-next-line no-unused-vars
+const { FxAccounts } = ChromeUtils.importESModule(
+ "resource://gre/modules/FxAccounts.sys.mjs"
+);
+// We import sinon here to make it available across all mochitest test files
+// eslint-disable-next-line no-unused-vars
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+// Set the content pref to make it available across tests
+const ABOUT_WELCOME_OVERRIDE_CONTENT_PREF = "browser.aboutwelcome.screens";
+// Test differently for windows 7 as theme screens are removed.
+// eslint-disable-next-line no-unused-vars
+const win7Content = AppConstants.isPlatformAndVersionAtMost("win", "6.1");
+
+function popPrefs() {
+ return SpecialPowers.popPrefEnv();
+}
+function pushPrefs(...prefs) {
+ return SpecialPowers.pushPrefEnv({ set: prefs });
+}
+// eslint-disable-next-line no-unused-vars
+async function getAboutWelcomeParent(browser) {
+ let windowGlobalParent = browser.browsingContext.currentWindowGlobal;
+ return windowGlobalParent.getActor("AboutWelcome");
+}
+// eslint-disable-next-line no-unused-vars
+async function setAboutWelcomeMultiStage(value = "") {
+ return pushPrefs([ABOUT_WELCOME_OVERRIDE_CONTENT_PREF, value]);
+}
+
+/**
+ * Setup functions to test welcome UI
+ */
+// eslint-disable-next-line no-unused-vars
+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"
+ );
+ }
+ }
+ );
+}
+
+// eslint-disable-next-line no-unused-vars
+async function test_element_styles(
+ browser,
+ elementSelector,
+ expectedStyles = {},
+ unexpectedStyles = {}
+) {
+ await ContentTask.spawn(
+ browser,
+ [elementSelector, expectedStyles, unexpectedStyles],
+ async ([selector, expected, unexpected]) => {
+ const element = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(selector)
+ );
+ const computedStyles = content.window.getComputedStyle(element);
+ Object.entries(expected).forEach(([attr, val]) =>
+ is(
+ computedStyles[attr],
+ val,
+ `${selector} should have computed ${attr} of ${val}`
+ )
+ );
+ Object.entries(unexpected).forEach(([attr, val]) =>
+ isnot(
+ computedStyles[attr],
+ val,
+ `${selector} should not have computed ${attr} of ${val}`
+ )
+ );
+ }
+ );
+}
+
+// eslint-disable-next-line no-unused-vars
+async function onButtonClick(browser, elementId) {
+ await ContentTask.spawn(
+ browser,
+ { elementId },
+ async ({ elementId: buttonId }) => {
+ let button = await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(buttonId),
+ buttonId
+ );
+ button.click();
+ }
+ );
+}
+
+// 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 setAboutWelcomePref(value) {
+ return pushPrefs(["browser.aboutwelcome.enabled", value]);
+}
+
+// eslint-disable-next-line no-unused-vars
+async function openMRAboutWelcome() {
+ await setAboutWelcomePref(true); // NB: Calls pushPrefs
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+
+ return {
+ browser: tab.linkedBrowser,
+ cleanup: async () => {
+ BrowserTestUtils.removeTab(tab);
+ await popPrefs(); // for setAboutWelcomePref()
+ },
+ };
+}
+
+// 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.loadURIString(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/redirect_to.sjs b/browser/components/newtab/test/browser/redirect_to.sjs
new file mode 100644
index 0000000000..b52ebdc63e
--- /dev/null
+++ b/browser/components/newtab/test/browser/redirect_to.sjs
@@ -0,0 +1,9 @@
+"use strict";
+
+function handleRequest(request, response) {
+ // redirect_to.sjs?ctxmenu-image.png
+ // redirects to : ctxmenu-image.png
+ const redirectUrl = request.queryString;
+ response.setStatusLine(request.httpVersion, "302", "Found");
+ response.setHeader("Location", redirectUrl, false);
+}
diff --git a/browser/components/newtab/test/browser/snippet.json b/browser/components/newtab/test/browser/snippet.json
new file mode 100644
index 0000000000..ae6a1a4bff
--- /dev/null
+++ b/browser/components/newtab/test/browser/snippet.json
@@ -0,0 +1,46 @@
+{
+ "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://example.com/"
+ }
+ }
+ },
+ "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"
+ },
+ {
+ "weight": 50,
+ "id": "10534",
+ "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://example.com/"
+ }
+ }
+ },
+ "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..7d65fcb0e1
--- /dev/null
+++ b/browser/components/newtab/test/browser/topstories.json
@@ -0,0 +1,53 @@
+{
+ "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..e655121447
--- /dev/null
+++ b/browser/components/newtab/test/schemas/pings.js
@@ -0,0 +1,304 @@
+import {
+ CONTENT_MESSAGE_TYPE,
+ MAIN_MESSAGE_TYPE,
+} from "common/Actions.sys.mjs";
+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/AWScreenUtils.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/AWScreenUtils.test.jsx
new file mode 100644
index 0000000000..a9f401f6b7
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/AWScreenUtils.test.jsx
@@ -0,0 +1,140 @@
+import { AWScreenUtils } from "lib/AWScreenUtils.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { ASRouter } from "lib/ASRouter.jsm";
+
+describe("AWScreenUtils", () => {
+ let sandbox;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set({
+ ASRouter,
+ ASRouterTargeting: {
+ Environment: {},
+ },
+ });
+
+ sandbox = sinon.createSandbox();
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+ describe("removeScreens", () => {
+ it("should run callback function once for each array element", async () => {
+ const callback = sandbox.stub().resolves(false);
+ const arr = ["foo", "bar"];
+ await AWScreenUtils.removeScreens(arr, callback);
+ assert.calledTwice(callback);
+ });
+ it("should remove screen when passed function evaluates true", async () => {
+ const callback = sandbox.stub().resolves(true);
+ const arr = ["foo", "bar"];
+ await AWScreenUtils.removeScreens(arr, callback);
+ assert.deepEqual(arr, []);
+ });
+ });
+ describe("evaluateScreenTargeting", () => {
+ it("should return the eval result if the eval succeeds", async () => {
+ const evalStub = sandbox.stub(ASRouter, "evaluateExpression").resolves({
+ evaluationStatus: {
+ success: true,
+ result: false,
+ },
+ });
+ const result = await AWScreenUtils.evaluateScreenTargeting(
+ "test expression"
+ );
+ assert.calledOnce(evalStub);
+ assert.equal(result, false);
+ });
+ it("should return true if the targeting eval fails", async () => {
+ const evalStub = sandbox.stub(ASRouter, "evaluateExpression").resolves({
+ evaluationStatus: {
+ success: false,
+ result: false,
+ },
+ });
+ const result = await AWScreenUtils.evaluateScreenTargeting(
+ "test expression"
+ );
+ assert.calledOnce(evalStub);
+ assert.equal(result, true);
+ });
+ });
+ describe("evaluateTargetingAndRemoveScreens", () => {
+ it("should manipulate an array of screens", async () => {
+ const screens = [
+ {
+ id: "first",
+ targeting: true,
+ },
+ {
+ id: "second",
+ targeting: false,
+ },
+ ];
+
+ const expectedScreens = [
+ {
+ id: "first",
+ targeting: true,
+ },
+ ];
+ sandbox.stub(ASRouter, "evaluateExpression").callsFake(targeting => {
+ return {
+ evaluationStatus: {
+ success: true,
+ result: targeting.expression,
+ },
+ };
+ });
+ const evaluatedStrings =
+ await AWScreenUtils.evaluateTargetingAndRemoveScreens(screens);
+ assert.deepEqual(evaluatedStrings, expectedScreens);
+ });
+ it("should not remove screens with no targeting", async () => {
+ const screens = [
+ {
+ id: "first",
+ },
+ {
+ id: "second",
+ targeting: false,
+ },
+ ];
+
+ const expectedScreens = [
+ {
+ id: "first",
+ },
+ ];
+ sandbox
+ .stub(AWScreenUtils, "evaluateScreenTargeting")
+ .callsFake(targeting => {
+ if (targeting === undefined) {
+ return true;
+ }
+ return targeting;
+ });
+ const evaluatedStrings =
+ await AWScreenUtils.evaluateTargetingAndRemoveScreens(screens);
+ assert.deepEqual(evaluatedStrings, expectedScreens);
+ });
+ });
+
+ describe("addScreenImpression", () => {
+ it("Should call addScreenImpression with provided screen ID", () => {
+ const addScreenImpressionStub = sandbox.stub(
+ ASRouter,
+ "addScreenImpression"
+ );
+ const testScreen = { id: "test" };
+ AWScreenUtils.addScreenImpression(testScreen);
+
+ assert.calledOnce(addScreenImpressionStub);
+ assert.equal(addScreenImpressionStub.firstCall.args[0].id, testScreen.id);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/CTAParagraph.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/CTAParagraph.test.jsx
new file mode 100644
index 0000000000..57773b0e82
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/CTAParagraph.test.jsx
@@ -0,0 +1,49 @@
+import React from "react";
+import { shallow } from "enzyme";
+import { CTAParagraph } from "content-src/aboutwelcome/components/CTAParagraph";
+
+describe("CTAParagraph component", () => {
+ let sandbox;
+ let wrapper;
+ let handleAction;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ handleAction = sandbox.stub();
+ wrapper = shallow(
+ <CTAParagraph
+ content={{
+ text: {
+ raw: "Link Text",
+ string_name: "Test Name",
+ },
+ }}
+ handleAction={handleAction}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render CTAParagraph component", () => {
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render CTAParagraph component if only CTA text is passed", () => {
+ wrapper.setProps({ content: { text: "CTA Text" } });
+ assert.ok(wrapper.exists());
+ });
+
+ it("should call handleAction method when button is link is clicked", () => {
+ const btnLink = wrapper.find(".cta-paragraph span");
+ btnLink.simulate("click");
+ assert.calledOnce(handleAction);
+ });
+
+ it("should not render CTAParagraph component if CTA text is not passed", () => {
+ wrapper.setProps({ content: { text: null } });
+ assert.ok(wrapper.isEmptyRender());
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/HeroImage.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/HeroImage.test.jsx
new file mode 100644
index 0000000000..8c9bdc8e50
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/HeroImage.test.jsx
@@ -0,0 +1,40 @@
+import React from "react";
+import { shallow } from "enzyme";
+import { HeroImage } from "content-src/aboutwelcome/components/HeroImage";
+
+describe("HeroImage component", () => {
+ const imageUrl = "https://example.com";
+ const imageHeight = "100px";
+ const imageAlt = "Alt text";
+
+ let wrapper;
+ beforeEach(() => {
+ wrapper = shallow(
+ <HeroImage url={imageUrl} alt={imageAlt} height={imageHeight} />
+ );
+ });
+
+ it("should render HeroImage component", () => {
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render an image element with src prop", () => {
+ let imgEl = wrapper.find("img");
+ assert.strictEqual(imgEl.prop("src"), imageUrl);
+ });
+
+ it("should render image element with alt text prop", () => {
+ let imgEl = wrapper.find("img");
+ assert.equal(imgEl.prop("alt"), imageAlt);
+ });
+
+ it("should render an image with a set height prop", () => {
+ let imgEl = wrapper.find("img");
+ assert.propertyVal(imgEl.prop("style"), "height", imageHeight);
+ });
+
+ it("should not render HeroImage component", () => {
+ wrapper.setProps({ url: null });
+ assert.ok(wrapper.isEmptyRender());
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/MRColorways.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/MRColorways.test.jsx
new file mode 100644
index 0000000000..c8829d76a7
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MRColorways.test.jsx
@@ -0,0 +1,328 @@
+import React from "react";
+import { shallow } from "enzyme";
+import {
+ Colorways,
+ computeColorWay,
+ ColorwayDescription,
+ computeVariationIndex,
+} from "content-src/aboutwelcome/components/MRColorways";
+import { WelcomeScreen } from "content-src/aboutwelcome/components/MultiStageAboutWelcome";
+
+describe("Multistage AboutWelcome module", () => {
+ let sandbox;
+ let COLORWAY_SCREEN_PROPS;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ COLORWAY_SCREEN_PROPS = {
+ id: "test-colorway-screen",
+ totalNumberofScreens: 1,
+ content: {
+ subtitle: "test subtitle",
+ tiles: {
+ type: "colorway",
+ action: {
+ theme: "<event>",
+ },
+ defaultVariationIndex: 0,
+ systemVariations: ["automatic", "light"],
+ variations: ["soft", "bold"],
+ colorways: [
+ {
+ id: "default",
+ label: "Default",
+ },
+ {
+ id: "abstract",
+ label: "Abstract",
+ },
+ ],
+ },
+ primary_button: {
+ action: {},
+ label: "test button",
+ },
+ },
+ messageId: "test-mr-colorway-screen",
+ activeTheme: "automatic",
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ describe("MRColorway component", () => {
+ it("should render WelcomeScreen", () => {
+ const wrapper = shallow(<WelcomeScreen {...COLORWAY_SCREEN_PROPS} />);
+
+ assert.ok(wrapper.exists());
+ });
+
+ it("should use default when activeTheme is not set", () => {
+ const wrapper = shallow(<Colorways {...COLORWAY_SCREEN_PROPS} />);
+ wrapper.setProps({ activeTheme: null });
+
+ const colorwaysOptionIcons = wrapper.find(
+ ".tiles-theme-section .theme .icon"
+ );
+ assert.strictEqual(colorwaysOptionIcons.length, 2);
+
+ // Default automatic theme is selected by default
+ assert.strictEqual(
+ colorwaysOptionIcons.first().prop("className").includes("selected"),
+ true
+ );
+
+ assert.strictEqual(
+ colorwaysOptionIcons.first().prop("className").includes("default"),
+ true
+ );
+ });
+
+ it("should use default when activeTheme is alpenglow", () => {
+ const wrapper = shallow(<Colorways {...COLORWAY_SCREEN_PROPS} />);
+ wrapper.setProps({ activeTheme: "alpenglow" });
+
+ const colorwaysOptionIcons = wrapper.find(
+ ".tiles-theme-section .theme .icon"
+ );
+ assert.strictEqual(colorwaysOptionIcons.length, 2);
+
+ // Default automatic theme is selected when unsupported in colorway alpenglow theme is active
+ assert.strictEqual(
+ colorwaysOptionIcons.first().prop("className").includes("selected"),
+ true
+ );
+
+ assert.strictEqual(
+ colorwaysOptionIcons.first().prop("className").includes("default"),
+ true
+ );
+ });
+
+ it("should render colorways options", () => {
+ const wrapper = shallow(<Colorways {...COLORWAY_SCREEN_PROPS} />);
+
+ const colorwaysOptions = wrapper.find(
+ ".tiles-theme-section .theme input[name='theme']"
+ );
+
+ const colorwaysOptionIcons = wrapper.find(
+ ".tiles-theme-section .theme .icon"
+ );
+
+ const colorwaysLabels = wrapper.find(
+ ".tiles-theme-section .theme span.sr-only"
+ );
+
+ assert.strictEqual(colorwaysOptions.length, 2);
+ assert.strictEqual(colorwaysOptionIcons.length, 2);
+ assert.strictEqual(colorwaysLabels.length, 2);
+
+ // First colorway option
+ // Default theme radio option is selected by default
+ assert.strictEqual(
+ colorwaysOptionIcons.first().prop("className").includes("selected"),
+ true
+ );
+
+ //Colorway should be using id property
+ assert.strictEqual(
+ colorwaysOptions.first().prop("data-colorway"),
+ "default"
+ );
+
+ // Second colorway option
+ assert.strictEqual(
+ colorwaysOptionIcons.last().prop("className").includes("selected"),
+ false
+ );
+
+ //Colorway should be using id property
+ assert.strictEqual(
+ colorwaysOptions.last().prop("data-colorway"),
+ "abstract"
+ );
+
+ //Colorway should be labelled for screen readers (parent label is for tooltip only, and does not describe the Colorway)
+ assert.strictEqual(
+ colorwaysOptions.last().prop("aria-labelledby"),
+ "abstract-label"
+ );
+ });
+
+ it("should handle colorway clicks", () => {
+ sandbox.stub(React, "useEffect").callsFake((fn, vals) => {
+ if (vals === undefined) {
+ fn();
+ } else if (vals[0] === "in") {
+ fn();
+ }
+ });
+
+ const handleAction = sandbox.stub();
+ const wrapper = shallow(
+ <Colorways handleAction={handleAction} {...COLORWAY_SCREEN_PROPS} />
+ );
+ const colorwaysOptions = wrapper.find(
+ ".tiles-theme-section .theme input[name='theme']"
+ );
+
+ let props = wrapper.find(ColorwayDescription).props();
+ assert.propertyVal(props.colorway, "label", "Default");
+
+ const option = colorwaysOptions.last();
+ assert.propertyVal(option.props(), "value", "abstract-soft");
+ colorwaysOptions.last().simulate("click");
+ assert.calledOnce(handleAction);
+ });
+
+ it("should render colorway description", () => {
+ const wrapper = shallow(<Colorways {...COLORWAY_SCREEN_PROPS} />);
+
+ let descriptionsWrapper = wrapper.find(ColorwayDescription);
+ assert.ok(descriptionsWrapper.exists());
+
+ let props = descriptionsWrapper.props();
+
+ // Colorway description should display Default theme desc by default
+ assert.strictEqual(props.colorway.label, "Default");
+ });
+
+ it("ColorwayDescription should display active colorway desc", () => {
+ let TEST_COLORWAY_PROPS = {
+ colorway: {
+ label: "Activist",
+ description: "Test Activist",
+ },
+ };
+ const descWrapper = shallow(
+ <ColorwayDescription {...TEST_COLORWAY_PROPS} />
+ );
+ assert.ok(descWrapper.exists());
+ const descText = descWrapper.find(".colorway-text");
+ assert.equal(
+ descText.props()["data-l10n-args"].includes("Activist"),
+ true
+ );
+ });
+
+ it("should computeColorWayId for default active theme", () => {
+ let TEST_COLORWAY_PROPS = {
+ ...COLORWAY_SCREEN_PROPS,
+ };
+
+ const colorwayId = computeColorWay(
+ TEST_COLORWAY_PROPS.activeTheme,
+ TEST_COLORWAY_PROPS.content.tiles.systemVariations
+ );
+ assert.strictEqual(colorwayId, "default");
+ });
+
+ it("should computeColorWayId for non-default active theme", () => {
+ let TEST_COLORWAY_PROPS = {
+ ...COLORWAY_SCREEN_PROPS,
+ activeTheme: "abstract-soft",
+ };
+
+ const colorwayId = computeColorWay(
+ TEST_COLORWAY_PROPS.activeTheme,
+ TEST_COLORWAY_PROPS.content.tiles.systemVariations
+ );
+ assert.strictEqual(colorwayId, "abstract");
+ });
+
+ it("should computeVariationIndex for default active theme", () => {
+ let TEST_COLORWAY_PROPS = {
+ ...COLORWAY_SCREEN_PROPS,
+ };
+
+ const variationIndex = computeVariationIndex(
+ TEST_COLORWAY_PROPS.activeTheme,
+ TEST_COLORWAY_PROPS.content.tiles.systemVariations,
+ TEST_COLORWAY_PROPS.content.tiles.variations,
+ TEST_COLORWAY_PROPS.content.tiles.defaultVariationIndex
+ );
+ assert.strictEqual(
+ variationIndex,
+ TEST_COLORWAY_PROPS.content.tiles.defaultVariationIndex
+ );
+ });
+
+ it("should computeVariationIndex for active theme", () => {
+ let TEST_COLORWAY_PROPS = {
+ ...COLORWAY_SCREEN_PROPS,
+ };
+
+ const variationIndex = computeVariationIndex(
+ "light",
+ TEST_COLORWAY_PROPS.content.tiles.systemVariations,
+ TEST_COLORWAY_PROPS.content.tiles.variations,
+ TEST_COLORWAY_PROPS.content.tiles.defaultVariationIndex
+ );
+ assert.strictEqual(variationIndex, 1);
+ });
+
+ it("should computeVariationIndex for colorway theme", () => {
+ let TEST_COLORWAY_PROPS = {
+ ...COLORWAY_SCREEN_PROPS,
+ };
+
+ const variationIndex = computeVariationIndex(
+ "abstract-bold",
+ TEST_COLORWAY_PROPS.content.tiles.systemVariations,
+ TEST_COLORWAY_PROPS.content.tiles.variations,
+ TEST_COLORWAY_PROPS.content.tiles.defaultVariationIndex
+ );
+ assert.strictEqual(variationIndex, 1);
+ });
+
+ describe("random colorways", () => {
+ let test;
+ beforeEach(() => {
+ COLORWAY_SCREEN_PROPS.handleAction = sandbox.stub();
+ sandbox.stub(window, "matchMedia");
+ // eslint-disable-next-line max-nested-callbacks
+ sandbox.stub(React, "useEffect").callsFake((fn, vals) => {
+ if (vals?.length === 0) {
+ fn();
+ }
+ });
+ test = () => {
+ shallow(<Colorways {...COLORWAY_SCREEN_PROPS} />);
+ return COLORWAY_SCREEN_PROPS.handleAction.firstCall.firstArg
+ .currentTarget;
+ };
+ });
+
+ it("should select a random colorway", () => {
+ const { value } = test();
+
+ assert.strictEqual(value, "abstract-soft");
+ assert.calledThrice(React.useEffect);
+ assert.notCalled(window.matchMedia);
+ });
+
+ it("should select a random soft colorway when not dark", () => {
+ window.matchMedia.returns({ matches: false });
+ COLORWAY_SCREEN_PROPS.content.tiles.darkVariation = 1;
+
+ const { value } = test();
+
+ assert.strictEqual(value, "abstract-soft");
+ assert.calledThrice(React.useEffect);
+ assert.calledOnce(window.matchMedia);
+ });
+
+ it("should select a random bold colorway when dark", () => {
+ window.matchMedia.returns({ matches: true });
+ COLORWAY_SCREEN_PROPS.content.tiles.darkVariation = 1;
+
+ const { value } = test();
+
+ assert.strictEqual(value, "abstract-bold");
+ assert.calledThrice(React.useEffect);
+ assert.calledOnce(window.matchMedia);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/MobileDownloads.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/MobileDownloads.test.jsx
new file mode 100644
index 0000000000..e3ed5d2bb0
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MobileDownloads.test.jsx
@@ -0,0 +1,69 @@
+import React from "react";
+import { shallow, mount } from "enzyme";
+import { GlobalOverrider } from "test/unit/utils";
+import { MobileDownloads } from "content-src/aboutwelcome/components/MobileDownloads";
+
+describe("Multistage AboutWelcome MobileDownloads module", () => {
+ let globals;
+ let sandbox;
+
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ globals.set({
+ AWFinish: () => Promise.resolve(),
+ AWSendToDeviceEmailsSupported: () => Promise.resolve(),
+ });
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("Mobile Downloads component", () => {
+ const MOBILE_DOWNLOADS_PROPS = {
+ data: {
+ QR_code: {
+ image_url:
+ "chrome://browser/components/privatebrowsing/content/assets/focus-qr-code.svg",
+ alt_text: {
+ string_id: "spotlight-focus-promo-qr-code",
+ },
+ },
+ email: {
+ link_text: "Email yourself a link",
+ },
+ marketplace_buttons: ["ios", "android"],
+ },
+ handleAction: () => {
+ window.AWFinish();
+ },
+ };
+
+ it("should render MobileDownloads", () => {
+ const wrapper = shallow(<MobileDownloads {...MOBILE_DOWNLOADS_PROPS} />);
+
+ assert.ok(wrapper.exists());
+ });
+
+ it("should handle action on markeplace badge click", () => {
+ const wrapper = mount(<MobileDownloads {...MOBILE_DOWNLOADS_PROPS} />);
+
+ const stub = sandbox.stub(global, "AWFinish");
+ wrapper.find(".ios button").simulate("click");
+ wrapper.find(".android button").simulate("click");
+
+ assert.calledTwice(stub);
+ });
+
+ it("should handle action on email button click", () => {
+ const wrapper = shallow(<MobileDownloads {...MOBILE_DOWNLOADS_PROPS} />);
+
+ const stub = sandbox.stub(global, "AWFinish");
+ wrapper.find("button.email-link").simulate("click");
+
+ assert.calledOnce(stub);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/MultiSelect.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/MultiSelect.test.jsx
new file mode 100644
index 0000000000..cb1ce3651a
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MultiSelect.test.jsx
@@ -0,0 +1,151 @@
+import React from "react";
+import { shallow, mount } from "enzyme";
+import { MultiSelect } from "content-src/aboutwelcome/components/MultiSelect";
+
+describe("Multistage AboutWelcome module", () => {
+ let sandbox;
+ let MULTISELECT_SCREEN_PROPS;
+ let setActiveMultiSelect;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ setActiveMultiSelect = sandbox.stub();
+ MULTISELECT_SCREEN_PROPS = {
+ id: "multiselect-screen",
+ content: {
+ position: "split",
+ split_narrow_bkg_position: "-60px",
+ image_alt_text: {
+ string_id: "mr2022-onboarding-default-image-alt",
+ },
+ background:
+ "url('chrome://activity-stream/content/data/content/assets/mr-settodefault.svg') var(--mr-secondary-position) no-repeat var(--mr-screen-background-color)",
+ progress_bar: true,
+ logo: {},
+ title: "Test Title",
+ subtitle: "Test SubTitle",
+ tiles: {
+ type: "multiselect",
+ data: [
+ {
+ id: "checkbox-1",
+ defaultValue: true,
+ label: {
+ string_id: "mr2022-onboarding-set-default-primary-button-label",
+ },
+ action: {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ {
+ id: "checkbox-2",
+ defaultValue: true,
+ label: "Test Checkbox 2",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ },
+ {
+ id: "checkbox-3",
+ defaultValue: false,
+ label: "Test Checkbox 3",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ },
+ ],
+ },
+ primary_button: {
+ label: "Save and Continue",
+ action: {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ navigate: true,
+ data: { actions: [] },
+ },
+ },
+ secondary_button: {
+ label: "Skip",
+ action: {
+ navigate: true,
+ },
+ has_arrow_icon: true,
+ },
+ },
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ describe("MultiSelect component", () => {
+ it("should call setActiveMultiSelect with ids of checkboxes with defaultValue true", () => {
+ const wrapper = mount(
+ <MultiSelect
+ setActiveMultiSelect={setActiveMultiSelect}
+ {...MULTISELECT_SCREEN_PROPS}
+ />
+ );
+
+ wrapper.setProps({ activeMultiSelect: null });
+ assert.calledOnce(setActiveMultiSelect);
+ assert.calledWith(setActiveMultiSelect, ["checkbox-1", "checkbox-2"]);
+ });
+
+ it("should use activeMultiSelect ids to set checked state for respective checkbox", () => {
+ const wrapper = mount(
+ <MultiSelect
+ setActiveMultiSelect={setActiveMultiSelect}
+ {...MULTISELECT_SCREEN_PROPS}
+ />
+ );
+
+ wrapper.setProps({ activeMultiSelect: ["checkbox-1", "checkbox-2"] });
+ const checkBoxes = wrapper.find(".checkbox-container input");
+ assert.strictEqual(checkBoxes.length, 3);
+
+ assert.strictEqual(checkBoxes.first().props().checked, true);
+ assert.strictEqual(checkBoxes.at(1).props().checked, true);
+ assert.strictEqual(checkBoxes.last().props().checked, false);
+ });
+
+ it("should filter out id when checkbox is unchecked", () => {
+ const wrapper = shallow(
+ <MultiSelect
+ setActiveMultiSelect={setActiveMultiSelect}
+ {...MULTISELECT_SCREEN_PROPS}
+ />
+ );
+ wrapper.setProps({ activeMultiSelect: ["checkbox-1", "checkbox-2"] });
+
+ const ckbx1 = wrapper.find(".checkbox-container input").at(0);
+ assert.strictEqual(ckbx1.prop("value"), "checkbox-1");
+ ckbx1.simulate("change", {
+ currentTarget: { value: "checkbox-1", checked: false },
+ });
+ assert.calledWith(setActiveMultiSelect, ["checkbox-2"]);
+ });
+
+ it("should add id when checkbox is checked", () => {
+ const wrapper = shallow(
+ <MultiSelect
+ setActiveMultiSelect={setActiveMultiSelect}
+ {...MULTISELECT_SCREEN_PROPS}
+ />
+ );
+ wrapper.setProps({ activeMultiSelect: ["checkbox-1", "checkbox-2"] });
+
+ const ckbx3 = wrapper.find(".checkbox-container input").at(2);
+ assert.strictEqual(ckbx3.prop("value"), "checkbox-3");
+ ckbx3.simulate("change", {
+ currentTarget: { value: "checkbox-3", checked: true },
+ });
+ assert.calledWith(setActiveMultiSelect, [
+ "checkbox-1",
+ "checkbox-2",
+ "checkbox-3",
+ ]);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/MultiStageAWProton.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/MultiStageAWProton.test.jsx
new file mode 100644
index 0000000000..22070101cf
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MultiStageAWProton.test.jsx
@@ -0,0 +1,564 @@
+import { AboutWelcomeDefaults } from "aboutwelcome/lib/AboutWelcomeDefaults.jsm";
+import { MultiStageProtonScreen } from "content-src/aboutwelcome/components/MultiStageProtonScreen";
+import { AWScreenUtils } from "lib/AWScreenUtils.jsm";
+import React from "react";
+import { mount } from "enzyme";
+
+describe("MultiStageAboutWelcomeProton module", () => {
+ let sandbox;
+ let clock;
+ beforeEach(() => {
+ clock = sinon.useFakeTimers();
+ sandbox = sinon.createSandbox();
+ });
+ afterEach(() => {
+ clock.restore();
+ sandbox.restore();
+ });
+
+ describe("MultiStageAWProton component", () => {
+ it("should render MultiStageProton Screen", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render secondary section for split positioned screens", () => {
+ const SCREEN_PROPS = {
+ content: {
+ position: "split",
+ title: "test title",
+ hero_text: "test subtitle",
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".welcome-text h1").text(), "test title");
+ assert.equal(
+ wrapper.find(".section-secondary h1").text(),
+ "test subtitle"
+ );
+ assert.equal(wrapper.find("main").prop("pos"), "split");
+ });
+
+ it("should render secondary section with content background for split positioned screens", () => {
+ const BACKGROUND_URL =
+ "chrome://activity-stream/content/data/content/assets/confetti.svg";
+ const SCREEN_PROPS = {
+ content: {
+ position: "split",
+ background: `url(${BACKGROUND_URL}) var(--mr-secondary-position) no-repeat`,
+ split_narrow_bkg_position: "10px",
+ title: "test title",
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.ok(
+ wrapper
+ .find("div.section-secondary")
+ .prop("style")
+ .background.includes("--mr-secondary-position")
+ );
+ assert.ok(
+ wrapper.find("div.section-secondary").prop("style")[
+ "--mr-secondary-background-position-y"
+ ],
+ "10px"
+ );
+ });
+
+ it("should render with secondary section for split positioned screens", () => {
+ const SCREEN_PROPS = {
+ content: {
+ position: "split",
+ title: "test title",
+ hero_text: "test subtitle",
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".welcome-text h1").text(), "test title");
+ assert.equal(
+ wrapper.find(".section-secondary h1").text(),
+ "test subtitle"
+ );
+ assert.equal(wrapper.find("main").prop("pos"), "split");
+ });
+
+ it("should render with no secondary section for center positioned screens", () => {
+ const SCREEN_PROPS = {
+ content: {
+ position: "center",
+ title: "test title",
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".section-secondary").exists(), false);
+ assert.equal(wrapper.find(".welcome-text h1").text(), "test title");
+ assert.equal(wrapper.find("main").prop("pos"), "center");
+ });
+
+ it("should not render multiple action buttons if an additional button does not exist", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.isFalse(wrapper.find(".additional-cta").exists());
+ });
+
+ it("should render an additional action button with primary styling if no style has been specified", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ additional_button: {
+ label: "test additional button",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.isTrue(wrapper.find(".additional-cta.primary").exists());
+ });
+
+ it("should render an additional action button with secondary styling", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ additional_button: {
+ label: "test additional button",
+ style: "secondary",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".additional-cta.secondary").exists(), true);
+ });
+
+ it("should render an additional action button with primary styling", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ additional_button: {
+ label: "test additional button",
+ style: "primary",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".additional-cta.primary").exists(), true);
+ });
+
+ it("should render an additional action with link styling", () => {
+ const SCREEN_PROPS = {
+ content: {
+ position: "split",
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ additional_button: {
+ label: "test additional button",
+ style: "link",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".additional-cta.cta-link").exists(), true);
+ });
+
+ it("should render an additional button with vertical orientation", () => {
+ const SCREEN_PROPS = {
+ content: {
+ position: "center",
+ title: "test title",
+ primary_button: {
+ label: "test primary button",
+ },
+ additional_button: {
+ label: "test additional button",
+ style: "secondary",
+ flow: "column",
+ },
+ },
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(
+ wrapper.find(".additional-cta-container[flow='column']").exists(),
+ true
+ );
+ });
+
+ it("should not render a progress bar if there is 1 step", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ progress_bar: true,
+ },
+ isSingleScreen: true,
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".steps.progress-bar").exists(), false);
+ });
+
+ it("should render a progress bar if there are 2 steps", () => {
+ const SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ progress_bar: true,
+ },
+ totalNumberOfScreens: 2,
+ };
+ const wrapper = mount(<MultiStageProtonScreen {...SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".steps.progress-bar").exists(), true);
+ });
+ });
+
+ describe("AboutWelcomeDefaults for proton", () => {
+ const getData = () => AboutWelcomeDefaults.getDefaults();
+
+ async function prepConfig(config, evalFalseScreenIds) {
+ let data = await getData();
+
+ if (evalFalseScreenIds?.length) {
+ data.screens.forEach(async screen => {
+ if (evalFalseScreenIds.includes(screen.id)) {
+ screen.targeting = false;
+ }
+ });
+ data.screens = await AWScreenUtils.evaluateTargetingAndRemoveScreens(
+ data.screens
+ );
+ }
+
+ return AboutWelcomeDefaults.prepareContentForReact({
+ ...data,
+ ...config,
+ });
+ }
+ beforeEach(() => {
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(true);
+ sandbox.stub(AWScreenUtils, "evaluateScreenTargeting").returnsArg(0);
+ // This is necessary because there are still screens being removed with
+ // `removeScreens` in `prepareContentForReact()`. Once we've migrated
+ // to using screen targeting instead of manually removing screens,
+ // we can remove this stub.
+ sandbox
+ .stub(global.AWScreenUtils, "removeScreens")
+ .callsFake((screens, callback) =>
+ AWScreenUtils.removeScreens(screens, callback)
+ );
+ });
+ it("should have 'pin' button by default", async () => {
+ const data = await prepConfig({ needPin: true }, [
+ "AW_EASY_SETUP",
+ "AW_WELCOME_BACK",
+ ]);
+ assert.propertyVal(
+ data.screens[0].content.primary_button.action,
+ "type",
+ "PIN_FIREFOX_TO_TASKBAR"
+ );
+ });
+ it("should have 'pin' button if we need default and pin", async () => {
+ const data = await prepConfig(
+ {
+ needDefault: true,
+ needPin: true,
+ },
+ ["AW_EASY_SETUP", "AW_WELCOME_BACK"]
+ );
+
+ assert.propertyVal(
+ data.screens[0].content.primary_button.action,
+ "type",
+ "PIN_FIREFOX_TO_TASKBAR"
+ );
+ assert.propertyVal(data.screens[0], "id", "AW_PIN_FIREFOX");
+ assert.propertyVal(data.screens[1], "id", "AW_SET_DEFAULT");
+ assert.lengthOf(data.screens, getData().screens.length - 3);
+ });
+ it("should keep 'pin' and remove 'default' if already default", async () => {
+ const data = await prepConfig({ needPin: true }, [
+ "AW_EASY_SETUP",
+ "AW_WELCOME_BACK",
+ ]);
+
+ assert.propertyVal(data.screens[0], "id", "AW_PIN_FIREFOX");
+ assert.propertyVal(data.screens[1], "id", "AW_IMPORT_SETTINGS");
+ assert.lengthOf(data.screens, getData().screens.length - 4);
+ });
+ it("should switch to 'default' if already pinned", async () => {
+ const data = await prepConfig({ needDefault: true }, [
+ "AW_EASY_SETUP",
+ "AW_WELCOME_BACK",
+ ]);
+
+ assert.propertyVal(data.screens[0], "id", "AW_ONLY_DEFAULT");
+ assert.propertyVal(data.screens[1], "id", "AW_IMPORT_SETTINGS");
+ assert.lengthOf(data.screens, getData().screens.length - 4);
+ });
+ it("should switch to 'start' if already pinned and default", async () => {
+ const data = await prepConfig({}, ["AW_EASY_SETUP", "AW_WELCOME_BACK"]);
+
+ assert.propertyVal(data.screens[0], "id", "AW_GET_STARTED");
+ assert.propertyVal(data.screens[1], "id", "AW_IMPORT_SETTINGS");
+ assert.lengthOf(data.screens, getData().screens.length - 4);
+ });
+ it("should have a FxA button", async () => {
+ const data = await prepConfig({}, ["AW_WELCOME_BACK"]);
+
+ assert.notProperty(data, "skipFxA");
+ assert.property(data.screens[0].content, "secondary_button_top");
+ });
+ it("should remove the FxA button if pref disabled", async () => {
+ global.Services.prefs.getBoolPref.returns(false);
+
+ const data = await prepConfig();
+
+ assert.property(data, "skipFxA", true);
+ assert.notProperty(data.screens[0].content, "secondary_button_top");
+ });
+ it("should remove the caption if deleteIfNotEn is true", async () => {
+ sandbox.stub(global.Services.locale, "appLocaleAsBCP47").value("de");
+
+ const data = await prepConfig({
+ id: "DEFAULT_ABOUTWELCOME_PROTON",
+ template: "multistage",
+ transitions: true,
+ background_url:
+ "chrome://activity-stream/content/data/content/assets/confetti.svg",
+ screens: [
+ {
+ id: "AW_PIN_FIREFOX",
+ content: {
+ position: "corner",
+ help_text: {
+ deleteIfNotEn: true,
+ string_id: "mr1-onboarding-welcome-image-caption",
+ },
+ },
+ },
+ ],
+ });
+
+ assert.notProperty(data.screens[0].content, "help_text");
+ });
+ });
+
+ describe("AboutWelcomeDefaults for MR split template proton", () => {
+ const getData = () => AboutWelcomeDefaults.getDefaults(true);
+ beforeEach(() => {
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(true);
+ });
+
+ it("should use 'split' position template by default", async () => {
+ const data = await getData();
+ assert.propertyVal(data.screens[0].content, "position", "split");
+ });
+
+ it("should not include noodles by default", async () => {
+ const data = await getData();
+ assert.notProperty(data.screens[0].content, "has_noodles");
+ });
+ });
+
+ describe("AboutWelcomeDefaults prepareMobileDownload", () => {
+ const TEST_CONTENT = {
+ screens: [
+ {
+ id: "AW_MOBILE_DOWNLOAD",
+ content: {
+ title: "test",
+ hero_image: {
+ url: "https://example.com/test.svg",
+ },
+ cta_paragraph: {
+ text: {},
+ action: {},
+ },
+ },
+ },
+ ],
+ };
+ it("should not set url for default qrcode svg", async () => {
+ sandbox.stub(global.AppConstants, "isChinaRepack").returns(false);
+ const data = await AboutWelcomeDefaults.prepareContentForReact(
+ TEST_CONTENT
+ );
+ assert.propertyVal(
+ data.screens[0].content.hero_image,
+ "url",
+ "https://example.com/test.svg"
+ );
+ });
+ it("should set url for cn qrcode svg", async () => {
+ sandbox.stub(global.AppConstants, "isChinaRepack").returns(true);
+ const data = await AboutWelcomeDefaults.prepareContentForReact(
+ TEST_CONTENT
+ );
+ assert.propertyVal(
+ data.screens[0].content.hero_image,
+ "url",
+ "https://example.com/test-cn.svg"
+ );
+ });
+ });
+
+ describe("AboutWelcomeDefaults prepareContentForReact", () => {
+ it("should not set action without screens", async () => {
+ const data = await AboutWelcomeDefaults.prepareContentForReact({
+ ua: "test",
+ });
+
+ assert.propertyVal(data, "ua", "test");
+ assert.notProperty(data, "screens");
+ });
+ it("should set action for import action", async () => {
+ const TEST_CONTENT = {
+ ua: "test",
+ screens: [
+ {
+ id: "AW_IMPORT_SETTINGS",
+ content: {
+ primary_button: {
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ },
+ },
+ },
+ },
+ ],
+ };
+ const data = await AboutWelcomeDefaults.prepareContentForReact(
+ TEST_CONTENT
+ );
+ assert.propertyVal(data, "ua", "test");
+ assert.propertyVal(
+ data.screens[0].content.primary_button.action.data,
+ "source",
+ "test"
+ );
+ });
+ it("should not set action if the action type != SHOW_MIGRATION_WIZARD", async () => {
+ const TEST_CONTENT = {
+ ua: "test",
+ screens: [
+ {
+ id: "AW_IMPORT_SETTINGS",
+ content: {
+ primary_button: {
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: {},
+ },
+ },
+ },
+ },
+ ],
+ };
+ const data = await AboutWelcomeDefaults.prepareContentForReact(
+ TEST_CONTENT
+ );
+ assert.propertyVal(data, "ua", "test");
+ assert.notPropertyVal(
+ data.screens[0].content.primary_button.action.data,
+ "source",
+ "test"
+ );
+ });
+ it("should remove theme screens on win7", async () => {
+ sandbox
+ .stub(global.AppConstants, "isPlatformAndVersionAtMost")
+ .returns(true);
+ sandbox
+ .stub(global.AWScreenUtils, "removeScreens")
+ .callsFake((screens, screen) =>
+ AWScreenUtils.removeScreens(screens, screen)
+ );
+
+ const { screens } = await AboutWelcomeDefaults.prepareContentForReact({
+ screens: [
+ {
+ content: {
+ tiles: { type: "theme" },
+ },
+ },
+ { id: "hello" },
+ {
+ content: {
+ tiles: { type: "theme" },
+ },
+ },
+ { id: "world" },
+ ],
+ });
+
+ assert.deepEqual(screens, [{ id: "hello" }, { id: "world" }]);
+ });
+ it("shouldn't remove colorway screens on win7", async () => {
+ sandbox
+ .stub(global.AppConstants, "isPlatformAndVersionAtMost")
+ .returns(true);
+ sandbox
+ .stub(global.AWScreenUtils, "removeScreens")
+ .callsFake((screens, screen) =>
+ AWScreenUtils.removeScreens(screens, screen)
+ );
+
+ const { screens } = await AboutWelcomeDefaults.prepareContentForReact({
+ screens: [
+ {
+ content: {
+ tiles: { type: "colorway" },
+ },
+ },
+ { id: "hello" },
+ {
+ content: {
+ tiles: { type: "theme" },
+ },
+ },
+ { id: "world" },
+ ],
+ });
+
+ assert.deepEqual(screens, [
+ {
+ content: {
+ tiles: { type: "colorway" },
+ },
+ },
+ { id: "hello" },
+ { id: "world" },
+ ]);
+ });
+ });
+});
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..d017f94b7f
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx
@@ -0,0 +1,824 @@
+import { GlobalOverrider } from "test/unit/utils";
+import {
+ MultiStageAboutWelcome,
+ SecondaryCTA,
+ StepsIndicator,
+ ProgressBar,
+ WelcomeScreen,
+} from "content-src/aboutwelcome/components/MultiStageAboutWelcome";
+import { Themes } from "content-src/aboutwelcome/components/Themes";
+import React from "react";
+import { shallow, mount } from "enzyme";
+import { AboutWelcomeDefaults } from "aboutwelcome/lib/AboutWelcomeDefaults.jsm";
+import { AboutWelcomeUtils } from "content-src/lib/aboutwelcome-utils";
+
+describe("MultiStageAboutWelcome module", () => {
+ let globals;
+ let sandbox;
+
+ const DEFAULT_PROPS = {
+ defaultScreens: AboutWelcomeDefaults.getDefaults().screens,
+ metricsFlowUri: "http://localhost/",
+ message_id: "DEFAULT_ABOUTWELCOME",
+ utm_term: "default",
+ startScreen: 0,
+ };
+
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ globals.set({
+ AWGetSelectedTheme: () => Promise.resolve("automatic"),
+ AWSendEventTelemetry: () => {},
+ AWWaitForMigrationClose: () => Promise.resolve(),
+ AWSelectTheme: () => Promise.resolve(),
+ AWFinish: () => 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 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 screens = [
+ {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ primary_button: {
+ label: "Test button",
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ];
+
+ const PRIMARY_ACTION_PROPS = {
+ defaultScreens: screens,
+ metricsFlowUri: "http://localhost/",
+ message_id: "DEFAULT_ABOUTWELCOME",
+ utm_term: "default",
+ startScreen: 0,
+ };
+
+ const stub = sinon.stub(AboutWelcomeUtils, "sendActionTelemetry");
+ let wrapper = mount(<MultiStageAboutWelcome {...PRIMARY_ACTION_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");
+ stub.restore();
+ });
+
+ it("should autoAdvance on last screen and send appropriate telemetry", () => {
+ let clock = sinon.useFakeTimers();
+ const screens = [
+ {
+ auto_advance: "primary_button",
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ primary_button: {
+ label: "Test Button",
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ ];
+ const AUTO_ADVANCE_PROPS = {
+ defaultScreens: screens,
+ metricsFlowUri: "http://localhost/",
+ message_id: "DEFAULT_ABOUTWELCOME",
+ utm_term: "default",
+ startScreen: 0,
+ };
+ const wrapper = mount(<MultiStageAboutWelcome {...AUTO_ADVANCE_PROPS} />);
+ wrapper.update();
+ const finishStub = sandbox.stub(global, "AWFinish");
+ const telemetryStub = sinon.stub(
+ AboutWelcomeUtils,
+ "sendActionTelemetry"
+ );
+
+ assert.notCalled(finishStub);
+ clock.tick(20001);
+ assert.calledOnce(finishStub);
+ assert.calledOnce(telemetryStub);
+ assert.equal(telemetryStub.lastCall.args[2], "AUTO_ADVANCE");
+ clock.restore();
+ finishStub.restore();
+ telemetryStub.restore();
+ });
+
+ it("should send telemetry ping on collectSelect", () => {
+ const screens = [
+ {
+ id: "EASY_SETUP_TEST",
+ content: {
+ tiles: {
+ type: "multiselect",
+ data: [
+ {
+ id: "checkbox-1",
+ defaultValue: true,
+ },
+ ],
+ },
+ primary_button: {
+ label: "Test Button",
+ action: {
+ collectSelect: true,
+ },
+ },
+ },
+ },
+ ];
+ const EASY_SETUP_PROPS = {
+ defaultScreens: screens,
+ message_id: "DEFAULT_ABOUTWELCOME",
+ startScreen: 0,
+ };
+ const stub = sinon.stub(AboutWelcomeUtils, "sendActionTelemetry");
+ let wrapper = mount(<MultiStageAboutWelcome {...EASY_SETUP_PROPS} />);
+ wrapper.update();
+
+ let welcomeScreenWrapper = wrapper.find(WelcomeScreen);
+ const btnPrimary = welcomeScreenWrapper.find(".primary");
+ btnPrimary.simulate("click");
+ assert.calledTwice(stub);
+ assert.equal(
+ stub.firstCall.args[0],
+ welcomeScreenWrapper.props().messageId
+ );
+ assert.equal(stub.firstCall.args[1], "primary_button");
+ assert.equal(
+ stub.lastCall.args[0],
+ welcomeScreenWrapper.props().messageId
+ );
+ assert.ok(stub.lastCall.args[1].includes("checkbox-1"));
+ assert.equal(stub.lastCall.args[2], "SELECT_CHECKBOX");
+ stub.restore();
+ });
+ });
+
+ describe("WelcomeScreen component", () => {
+ describe("get started screen", () => {
+ const screen = AboutWelcomeDefaults.getDefaults().screens.find(
+ s => s.id === "AW_PIN_FIREFOX"
+ );
+
+ const GET_STARTED_SCREEN_PROPS = {
+ id: screen.id,
+ totalNumberOfScreens: 1,
+ content: screen.content,
+ messageId: `${DEFAULT_PROPS.message_id}_${screen.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 render secondary.top button", () => {
+ let SCREEN_PROPS = {
+ content: {
+ title: "Step",
+ secondary_button_top: {
+ text: "test",
+ label: "test label",
+ },
+ },
+ position: "top",
+ };
+ const wrapper = mount(<SecondaryCTA {...SCREEN_PROPS} />);
+ assert.ok(wrapper.find("div.secondary-cta.top").exists());
+ });
+
+ it("should render the arrow icon in the secondary button", () => {
+ let SCREEN_PROPS = {
+ content: {
+ title: "Step",
+ secondary_button: {
+ has_arrow_icon: true,
+ label: "test label",
+ },
+ },
+ };
+ const wrapper = mount(<SecondaryCTA {...SCREEN_PROPS} />);
+ assert.ok(wrapper.find("button.arrow-icon").exists());
+ });
+
+ it("should render steps indicator", () => {
+ let PROPS = { totalNumberOfScreens: 1 };
+ const wrapper = mount(<StepsIndicator {...PROPS} />);
+ assert.ok(wrapper.find("div.indicator").exists());
+ });
+
+ it("should assign the total number of screens and current screen to the aria-valuemax and aria-valuenow labels", () => {
+ const EXTRA_PROPS = { totalNumberOfScreens: 3, order: 1 };
+ const wrapper = mount(
+ <WelcomeScreen {...GET_STARTED_SCREEN_PROPS} {...EXTRA_PROPS} />
+ );
+ const steps = wrapper.find(`div.steps`);
+ assert.ok(steps.exists());
+ const { attributes } = steps.getDOMNode();
+ assert.equal(
+ parseInt(attributes.getNamedItem("aria-valuemax").value, 10),
+ EXTRA_PROPS.totalNumberOfScreens
+ );
+ assert.equal(
+ parseInt(attributes.getNamedItem("aria-valuenow").value, 10),
+ EXTRA_PROPS.order + 1
+ );
+ });
+
+ it("should render progress bar", () => {
+ let SCREEN_PROPS = {
+ step: 1,
+ previousStep: 0,
+ totalNumberOfScreens: 2,
+ };
+ const wrapper = mount(<ProgressBar {...SCREEN_PROPS} />);
+ assert.ok(wrapper.find("div.indicator").exists());
+ assert.propertyVal(
+ wrapper.find("div.indicator").prop("style"),
+ "--progress-bar-progress",
+ "50%"
+ );
+ });
+
+ it("should have a primary, secondary and secondary.top button in the rendered input", () => {
+ const wrapper = mount(<WelcomeScreen {...GET_STARTED_SCREEN_PROPS} />);
+ assert.ok(wrapper.find(".primary").exists());
+ assert.ok(
+ wrapper
+ .find(".secondary-cta button.secondary[value='secondary_button']")
+ .exists()
+ );
+ assert.ok(
+ wrapper
+ .find(
+ ".secondary-cta.top button.secondary[value='secondary_button_top']"
+ )
+ .exists()
+ );
+ });
+ });
+
+ describe("theme screen", () => {
+ const THEME_SCREEN_PROPS = {
+ id: "test-theme-screen",
+ totalNumberOfScreens: 1,
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ tiles: {
+ type: "theme",
+ action: {
+ theme: "<event>",
+ },
+ data: [
+ {
+ theme: "automatic",
+ label: "test-label",
+ tooltip: "test-tooltip",
+ description: "test-description",
+ },
+ ],
+ },
+ primary_button: {
+ action: {},
+ label: "test button",
+ },
+ },
+ navigate: null,
+ messageId: `${DEFAULT_PROPS.message_id}_"test-theme-screen"`,
+ 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 check this.props.activeTheme in the rendered input", () => {
+ const wrapper = shallow(<Themes {...THEME_SCREEN_PROPS} />);
+
+ const selectedThemeInput = wrapper.find(".theme input[checked=true]");
+ assert.strictEqual(
+ selectedThemeInput.prop("value"),
+ THEME_SCREEN_PROPS.activeTheme
+ );
+ });
+ });
+ describe("import screen", () => {
+ const IMPORT_SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ help_text: {
+ text: "test help text",
+ position: "default",
+ },
+ },
+ };
+ it("should render ImportScreen", () => {
+ const wrapper = mount(<WelcomeScreen {...IMPORT_SCREEN_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+ it("should not have a primary or secondary button", () => {
+ const wrapper = mount(<WelcomeScreen {...IMPORT_SCREEN_PROPS} />);
+ assert.isFalse(wrapper.find(".primary").exists());
+ assert.isFalse(
+ wrapper.find(".secondary button[value='secondary_button']").exists()
+ );
+ assert.isFalse(
+ wrapper
+ .find(".secondary button[value='secondary_button_top']")
+ .exists()
+ );
+ });
+ });
+ describe("#handleAction", () => {
+ let SCREEN_PROPS;
+ let TEST_ACTION;
+ beforeEach(() => {
+ SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ primary_button: {
+ action: {},
+ label: "test button",
+ },
+ },
+ navigate: sandbox.stub(),
+ setActiveTheme: sandbox.stub(),
+ UTMTerm: "you_tee_emm",
+ };
+ TEST_ACTION = SCREEN_PROPS.content.primary_button.action;
+ sandbox.stub(AboutWelcomeUtils, "handleUserAction").resolves();
+ });
+ it("should handle navigate", () => {
+ TEST_ACTION.navigate = true;
+ const wrapper = mount(<WelcomeScreen {...SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+
+ assert.calledOnce(SCREEN_PROPS.navigate);
+ });
+ it("should handle theme", () => {
+ TEST_ACTION.theme = "test";
+ const wrapper = mount(<WelcomeScreen {...SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+
+ assert.calledWith(SCREEN_PROPS.setActiveTheme, "test");
+ });
+ it("should handle dismiss", () => {
+ SCREEN_PROPS.content.dismiss_button = {
+ action: { dismiss: true },
+ };
+ const finishStub = sandbox.stub(global, "AWFinish");
+ const wrapper = mount(<WelcomeScreen {...SCREEN_PROPS} />);
+
+ wrapper.find(".dismiss-button").simulate("click");
+
+ assert.calledOnce(finishStub);
+ });
+ it("should handle SHOW_FIREFOX_ACCOUNTS", () => {
+ TEST_ACTION.type = "SHOW_FIREFOX_ACCOUNTS";
+ const wrapper = mount(<WelcomeScreen {...SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ data: {
+ extraParams: {
+ utm_campaign: "firstrun",
+ utm_medium: "referral",
+ utm_source: "activity-stream",
+ utm_term: "you_tee_emm-screen",
+ },
+ },
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ });
+ });
+ it("should handle SHOW_MIGRATION_WIZARD", () => {
+ TEST_ACTION.type = "SHOW_MIGRATION_WIZARD";
+ const wrapper = mount(<WelcomeScreen {...SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "SHOW_MIGRATION_WIZARD",
+ });
+ });
+ it("should handle SHOW_MIGRATION_WIZARD INSIDE MULTI_ACTION", async () => {
+ const migrationCloseStub = sandbox.stub(
+ global,
+ "AWWaitForMigrationClose"
+ );
+ const MULTI_ACTION_SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ primary_button: {
+ action: {
+ type: "MULTI_ACTION",
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ ],
+ },
+ },
+ label: "test button",
+ },
+ },
+ navigate: sandbox.stub(),
+ };
+ const wrapper = mount(<WelcomeScreen {...MULTI_ACTION_SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ ],
+ },
+ });
+ // handleUserAction returns a Promise, so let's let the microtask queue
+ // flush so that anything waiting for the handleUserAction Promise to
+ // resolve can run.
+ await new Promise(resolve => queueMicrotask(resolve));
+ assert.calledOnce(migrationCloseStub);
+ });
+
+ it("should handle SHOW_MIGRATION_WIZARD INSIDE NESTED MULTI_ACTION", async () => {
+ const migrationCloseStub = sandbox.stub(
+ global,
+ "AWWaitForMigrationClose"
+ );
+ const MULTI_ACTION_SCREEN_PROPS = {
+ content: {
+ title: "test title",
+ subtitle: "test subtitle",
+ primary_button: {
+ action: {
+ type: "MULTI_ACTION",
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ },
+ {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ label: "test button",
+ },
+ },
+ navigate: sandbox.stub(),
+ };
+ const wrapper = mount(<WelcomeScreen {...MULTI_ACTION_SCREEN_PROPS} />);
+
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "PIN_FIREFOX_TO_TASKBAR",
+ },
+ {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ },
+ {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: {},
+ },
+ ],
+ },
+ },
+ ],
+ },
+ });
+ // handleUserAction returns a Promise, so let's let the microtask queue
+ // flush so that anything waiting for the handleUserAction Promise to
+ // resolve can run.
+ await new Promise(resolve => queueMicrotask(resolve));
+ assert.calledOnce(migrationCloseStub);
+ });
+ it("should unset prefs from unchecked checkboxes", () => {
+ const PREF_SCREEN_PROPS = {
+ content: {
+ title: "Checkboxes",
+ tiles: {
+ type: "multiselect",
+ data: [
+ {
+ id: "checkbox-1",
+ label: "checkbox 1",
+ checkedAction: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "pref-a",
+ value: true,
+ },
+ },
+ },
+ uncheckedAction: {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "pref-a",
+ },
+ },
+ },
+ },
+ {
+ id: "checkbox-2",
+ label: "checkbox 2",
+ checkedAction: {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "pref-b",
+ value: "pref-b",
+ },
+ },
+ },
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "pref-c",
+ value: 3,
+ },
+ },
+ },
+ ],
+ },
+ },
+ uncheckedAction: {
+ type: "SET_PREF",
+ data: {
+ pref: { name: "pref-b" },
+ },
+ },
+ },
+ ],
+ },
+ primary_button: {
+ label: "Set Prefs",
+ action: {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ isDynamic: true,
+ navigate: true,
+ data: {
+ actions: [],
+ },
+ },
+ },
+ },
+ navigate: sandbox.stub(),
+ setActiveMultiSelect: sandbox.stub(),
+ };
+
+ // No checkboxes checked. All prefs will be unset and pref-c will not be
+ // reset.
+ {
+ const wrapper = mount(
+ <WelcomeScreen {...PREF_SCREEN_PROPS} activeMultiSelect={[]} />
+ );
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ isDynamic: true,
+ navigate: true,
+ data: {
+ actions: [
+ { type: "SET_PREF", data: { pref: { name: "pref-a" } } },
+ { type: "SET_PREF", data: { pref: { name: "pref-b" } } },
+ ],
+ },
+ });
+
+ AboutWelcomeUtils.handleUserAction.resetHistory();
+ }
+
+ // The first checkbox is checked. Only pref-a will be set and pref-c
+ // will not be reset.
+ {
+ const wrapper = mount(
+ <WelcomeScreen
+ {...PREF_SCREEN_PROPS}
+ activeMultiSelect={["checkbox-1"]}
+ />
+ );
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ isDynamic: true,
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: {
+ pref: {
+ name: "pref-a",
+ value: true,
+ },
+ },
+ },
+ { type: "SET_PREF", data: { pref: { name: "pref-b" } } },
+ ],
+ },
+ });
+
+ AboutWelcomeUtils.handleUserAction.resetHistory();
+ }
+
+ // The second checkbox is checked. Prefs pref-b and pref-c will be set.
+ {
+ const wrapper = mount(
+ <WelcomeScreen
+ {...PREF_SCREEN_PROPS}
+ activeMultiSelect={["checkbox-2"]}
+ />
+ );
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ isDynamic: true,
+ navigate: true,
+ data: {
+ actions: [
+ { type: "SET_PREF", data: { pref: { name: "pref-a" } } },
+ {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: { pref: { name: "pref-b", value: "pref-b" } },
+ },
+ {
+ type: "SET_PREF",
+ data: { pref: { name: "pref-c", value: 3 } },
+ },
+ ],
+ },
+ },
+ ],
+ },
+ });
+
+ AboutWelcomeUtils.handleUserAction.resetHistory();
+ }
+
+ // // Both checkboxes are checked. All prefs will be set.
+ {
+ const wrapper = mount(
+ <WelcomeScreen
+ {...PREF_SCREEN_PROPS}
+ activeMultiSelect={["checkbox-1", "checkbox-2"]}
+ />
+ );
+ wrapper.find(".primary").simulate("click");
+ assert.calledWith(AboutWelcomeUtils.handleUserAction, {
+ type: "MULTI_ACTION",
+ collectSelect: true,
+ isDynamic: true,
+ navigate: true,
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: { pref: { name: "pref-a", value: true } },
+ },
+ {
+ type: "MULTI_ACTION",
+ data: {
+ actions: [
+ {
+ type: "SET_PREF",
+ data: { pref: { name: "pref-b", value: "pref-b" } },
+ },
+ {
+ type: "SET_PREF",
+ data: { pref: { name: "pref-c", value: 3 } },
+ },
+ ],
+ },
+ },
+ ],
+ },
+ });
+
+ AboutWelcomeUtils.handleUserAction.resetHistory();
+ }
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/aboutwelcome/OnboardingVideoTest.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/OnboardingVideoTest.test.jsx
new file mode 100644
index 0000000000..db6d8ba10a
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/OnboardingVideoTest.test.jsx
@@ -0,0 +1,45 @@
+import React from "react";
+import { mount } from "enzyme";
+import { OnboardingVideo } from "content-src/aboutwelcome/components/OnboardingVideo";
+
+describe("OnboardingVideo component", () => {
+ let sandbox;
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ const SCREEN_PROPS = {
+ content: {
+ title: "Test title",
+ video_container: {
+ video_url: "test url",
+ },
+ },
+ };
+
+ it("should handle video_start action when video is played", () => {
+ const handleAction = sandbox.stub();
+ const wrapper = mount(
+ <OnboardingVideo handleAction={handleAction} {...SCREEN_PROPS} />
+ );
+ wrapper.find("video").simulate("play");
+ assert.calledWith(handleAction, {
+ currentTarget: { value: "video_start" },
+ });
+ });
+ it("should handle video_end action when video has completed playing", () => {
+ const handleAction = sandbox.stub();
+ const wrapper = mount(
+ <OnboardingVideo handleAction={handleAction} {...SCREEN_PROPS} />
+ );
+ wrapper.find("video").simulate("ended");
+ assert.calledWith(handleAction, {
+ currentTarget: { value: "video_end" },
+ });
+ });
+});
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..732200b408
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouter.test.js
@@ -0,0 +1,3040 @@
+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.sys.mjs";
+import ProviderResponseSchema from "content-src/asrouter/schemas/provider-response.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.sys.mjs";
+
+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 FakeToolbarBadgeHub;
+ let FakeToolbarPanelHub;
+ let FakeMomentsPageHub;
+ let ASRouterTargeting;
+ let screenImpressions;
+
+ 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));
+ getStub
+ .withArgs("screenImpressions")
+ .returns(Promise.resolve(screenImpressions));
+ 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;
+ screenImpressions = {};
+ sandbox = sinon.createSandbox();
+ 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,
+ isFxASignedIn: false,
+ 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: "",
+ "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");
+
+ 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(),
+ };
+ 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(),
+ };
+ let fakeNimbusFeatures = [
+ "cfr",
+ "infobar",
+ "spotlight",
+ "moments-page",
+ "pbNewtab",
+ ].reduce((features, featureId) => {
+ features[featureId] = {
+ getAllVariables: sandbox.stub().returns(null),
+ recordExposureEvent: sandbox.stub(),
+ };
+ return features;
+ }, {});
+ 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,
+ gBrowser: { selectedBrowser: {} },
+ gURLBar: {},
+ isSeparateAboutWelcome: true,
+ AttributionCode: fakeAttributionCode,
+ SnippetsTestMessageProvider,
+ PanelTestProvider,
+ MacAttribution: { applicationPath: "" },
+ 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");
+ }
+ },
+ NimbusFeatures: fakeNimbusFeatures,
+ ExperimentAPI: {
+ getExperimentMetaData: sandbox.stub().returns({
+ slug: "experiment-slug",
+ active: true,
+ branch: { slug: "experiment-branch-slug" },
+ }),
+ getExperiment: sandbox.stub().returns({
+ branch: {
+ slug: "unit-slug",
+ feature: {
+ featureId: "foo",
+ value: { id: "test-message" },
+ },
+ },
+ }),
+ getAllBranches: sandbox.stub().resolves([]),
+ 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: {
+ // This is just a subset of supported locales that happen to be used in
+ // the test.
+ isLocaleSupported: locale => ["en-US", "ja-JP-mac"].includes(locale),
+ },
+ });
+ 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 only be called once", async () => {
+ Router = new _ASRouter();
+ let state = await initASRouter(Router);
+
+ assert.equal(state, Router.state);
+
+ assert.isNull(await Router.init({}));
+ });
+ it("should only be called once", async () => {
+ Router = new _ASRouter();
+ initASRouter(Router);
+ let secondCall = await Router.init({});
+
+ assert.isNull(
+ secondCall,
+ "Should not init twice, it should exit early with null"
+ );
+ });
+ 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(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,
+ }
+ );
+ });
+ 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 set state.screenImpressions to the screenImpressions object in persistent storage", async () => {
+ screenImpressions = { test: 123 };
+
+ Router = new _ASRouter();
+ await initASRouter(Router);
+
+ assert.deepEqual(Router.state.screenImpressions, screenImpressions);
+ });
+ 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.calledWithExactly(
+ global.Services.obs.addObserver,
+ Router._onLocaleChanged,
+ "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(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(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(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(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ 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(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(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(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(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(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 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 parse the message's messagesLoaded trigger and immediately fire trigger", async () => {
+ setMessageProviderPref([
+ {
+ id: "foo",
+ type: "local",
+ enabled: true,
+ messages: [
+ {
+ id: "bar3",
+ template: "simple_template",
+ trigger: { id: "messagesLoaded" },
+ content: { title: "Bar3", body: "Bar123" },
+ },
+ ],
+ },
+ ]);
+ Router = new _ASRouter(Object.freeze(FAKE_LOCAL_PROVIDERS));
+ sandbox.spy(Router, "sendTriggerMessage");
+ await initASRouter(Router);
+ assert.calledOnce(Router.sendTriggerMessage);
+ assert.calledWith(
+ Router.sendTriggerMessage,
+ sandbox.match({ id: "messagesLoaded" }),
+ true
+ );
+ });
+ it("should gracefully handle messages loading before a window or browser exists", async () => {
+ sandbox.stub(global, "gBrowser").value(undefined);
+ sandbox
+ .stub(global.Services.wm, "getMostRecentBrowserWindow")
+ .returns(undefined);
+ setMessageProviderPref([
+ {
+ id: "foo",
+ type: "local",
+ enabled: true,
+ messages: [
+ "whatsnew_panel_message",
+ "cfr_doorhanger",
+ "toolbar_badge",
+ "update_action",
+ "infobar",
+ "spotlight",
+ "toast_notification",
+ ].map((template, i) => {
+ return {
+ id: `foo${i}`,
+ template,
+ trigger: { id: "messagesLoaded" },
+ content: { title: `Foo${i}`, body: "Bar123" },
+ };
+ }),
+ },
+ ]);
+ Router = new _ASRouter(Object.freeze(FAKE_LOCAL_PROVIDERS));
+ sandbox.spy(Router, "sendTriggerMessage");
+ await initASRouter(Router);
+ assert.calledWith(
+ Router.sendTriggerMessage,
+ sandbox.match({ id: "messagesLoaded" }),
+ true
+ );
+ });
+ 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.downloadToDisk = spy;
+ const provider = {
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ collection: "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",
+ collection: "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.calledWithExactly(
+ global.Services.obs.removeObserver,
+ Router._onLocaleChanged,
+ "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: {},
+ });
+
+ // Called once for the messagesLoaded trigger and once for the above call.
+ assert.calledTwice(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ assert.calledTwice(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 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("#reachEvent", () => {
+ let experimentAPIStub;
+ let featureIds = ["cfr", "moments-page", "infobar", "spotlight"];
+ beforeEach(() => {
+ let getExperimentMetaDataStub = sandbox.stub();
+ let getAllBranchesStub = sandbox.stub();
+ featureIds.forEach(feature => {
+ global.NimbusFeatures[feature].getAllVariables.returns({
+ id: `message-${feature}`,
+ });
+ getExperimentMetaDataStub.withArgs({ featureId: feature }).returns({
+ slug: `slug-${feature}`,
+ branch: {
+ slug: `branch-${feature}`,
+ },
+ });
+ getAllBranchesStub.withArgs(`slug-${feature}`).resolves([
+ {
+ slug: `other-branch-${feature}`,
+ [feature]: { value: { trigger: "unit-test" } },
+ },
+ ]);
+ });
+ experimentAPIStub = {
+ getExperimentMetaData: getExperimentMetaDataStub,
+ getAllBranches: getAllBranchesStub,
+ };
+ globals.set("ExperimentAPI", experimentAPIStub);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should tag `forReachEvent` for all the expected message types", async () => {
+ // This should match the `providers.messaging-experiments`
+ let response = await MessageLoaderUtils.loadMessagesForProvider({
+ type: "remote-experiments",
+ featureIds,
+ });
+
+ // 1 message for reach 1 for expose
+ assert.property(response, "messages");
+ assert.lengthOf(response.messages, featureIds.length * 2);
+ assert.lengthOf(
+ response.messages.filter(m => m.forReachEvent),
+ featureIds.length
+ );
+ });
+ });
+
+ 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.calledTwice(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ assert.calledTwice(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 for each valid feature", async () => {
+ ["cfr_doorhanger", "update_action", "infobar", "spotlight"].forEach(
+ async template => {
+ let featureMap = {
+ cfr_doorhanger: "cfr",
+ spotlight: "spotlight",
+ infobar: "infobar",
+ update_action: "moments-page",
+ };
+ assert.notCalled(
+ global.NimbusFeatures[featureMap[template]].recordExposureEvent
+ );
+
+ let messages = [
+ {
+ id: "foo1",
+ template,
+ trigger: { id: "foo" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ ];
+ sandbox.stub(Router, "handleMessageRequest").resolves(messages);
+
+ await Router.sendTriggerMessage({
+ tabId: 0,
+ browser: {},
+ id: "foo",
+ });
+
+ assert.calledOnce(
+ global.NimbusFeatures[featureMap[template]].recordExposureEvent
+ );
+ }
+ );
+ });
+ });
+
+ describe("forceAttribution", () => {
+ let setReferrerUrl;
+ beforeEach(() => {
+ setReferrerUrl = sinon.spy();
+ global.Cc["@mozilla.org/mac-attribution;1"] = {
+ getService: () => ({ setReferrerUrl }),
+ };
+
+ sandbox.stub(global.Services.env, "set");
+ });
+ 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(global.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(console, "error");
+
+ assert.equal(false, Router._validPreviewEndpoint("http://foo.com"));
+ assert.calledTwice(console.error);
+ });
+ });
+
+ describe("impressions", () => {
+ describe("#addImpression for groups", () => {
+ it("should save an impression in each group-with-frequency in a message", async () => {
+ const fooMessageImpressions = [0];
+ const aGroupImpressions = [0, 1, 2];
+ const bGroupImpressions = [3, 4, 5];
+ const cGroupImpressions = [6, 7, 8];
+
+ const message = {
+ id: "foo",
+ provider: "bar",
+ groups: ["a", "b", "c"],
+ };
+ const groups = [
+ { id: "a", frequency: { lifetime: 3 } },
+ { id: "b", frequency: { lifetime: 4 } },
+ { id: "c", 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.a = aGroupImpressions;
+ gImpressions.b = bGroupImpressions;
+ gImpressions.c = cGroupImpressions;
+ messageImpressions.foo = fooMessageImpressions;
+ return {
+ providers,
+ messageImpressions,
+ groups,
+ groupImpressions: gImpressions,
+ };
+ });
+
+ await Router.addImpression(message);
+
+ assert.deepEqual(
+ Router.state.groupImpressions.a,
+ [0, 1, 2, 0],
+ "a impressions"
+ );
+ assert.deepEqual(
+ Router.state.groupImpressions.b,
+ [3, 4, 5, 0],
+ "b impressions"
+ );
+ assert.deepEqual(
+ Router.state.groupImpressions.c,
+ [6, 7, 8, 0],
+ "c impressions"
+ );
+ });
+ });
+
+ 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",
+ collection: "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",
+ collection: "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,
+ collection: "collection",
+ 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,
+ collection: "collection",
+ 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,
+ collection: "collection",
+ 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,
+ collection: "collection",
+ 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,
+ collection: "collection",
+ 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",
+ featureIds: ["spotlight"],
+ };
+
+ await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.calledOnce(global.NimbusFeatures.spotlight.getAllVariables);
+ assert.calledOnce(global.ExperimentAPI.getExperimentMetaData);
+ assert.calledWithExactly(global.ExperimentAPI.getExperimentMetaData, {
+ featureId: "spotlight",
+ });
+ });
+ it("should handle the case of no experiments in the ExperimentAPI", async () => {
+ const args = {
+ type: "remote-experiments",
+ featureIds: ["infobar"],
+ };
+
+ 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",
+ featureIds: ["infobar"],
+ };
+ const enrollment = {
+ branch: {
+ slug: "branch01",
+ infobar: {
+ featureId: "infobar",
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.NimbusFeatures.infobar.getAllVariables.returns(
+ enrollment.branch.infobar.value
+ );
+ global.ExperimentAPI.getExperimentMetaData.returns({
+ branch: { slug: enrollment.branch.slug },
+ });
+ global.ExperimentAPI.getAllBranches.returns([
+ enrollment.branch,
+ {
+ slug: "control",
+ infobar: {
+ featureId: "infobar",
+ value: null,
+ },
+ },
+ ]);
+
+ 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",
+ featureIds: ["cfr"],
+ };
+
+ global.NimbusFeatures.cfr.getAllVariables.returns(null);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.lengthOf(result.messages, 0);
+ });
+ it("should fetch branches with trigger", async () => {
+ const args = {
+ type: "remote-experiments",
+ featureIds: ["cfr"],
+ };
+ const enrollment = {
+ slug: "exp01",
+ branch: {
+ slug: "branch01",
+ cfr: {
+ featureId: "cfr",
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.NimbusFeatures.cfr.getAllVariables.returns(
+ enrollment.branch.cfr.value
+ );
+ global.ExperimentAPI.getExperimentMetaData.returns({
+ slug: enrollment.slug,
+ active: true,
+ branch: { slug: enrollment.branch.slug },
+ });
+ global.ExperimentAPI.getAllBranches.resolves([
+ enrollment.branch,
+ {
+ slug: "branch02",
+ cfr: {
+ featureId: "cfr",
+ value: { id: "id02", trigger: { id: "openURL" } },
+ },
+ },
+ {
+ // This branch should not be loaded as it doesn't have the trigger
+ slug: "branch03",
+ cfr: {
+ featureId: "cfr",
+ 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",
+ featureIds: ["cfr"],
+ };
+ const enrollment = {
+ slug: "exp01",
+ branch: {
+ slug: "branch01",
+ cfr: {
+ featureId: "cfr",
+ value: {},
+ },
+ },
+ };
+
+ // Nedds to match the `featureIds` value to return an enrollment
+ // for that feature
+ global.NimbusFeatures.cfr.getAllVariables.returns(
+ enrollment.branch.cfr.value
+ );
+ global.ExperimentAPI.getExperimentMetaData.returns({
+ slug: enrollment.slug,
+ active: true,
+ branch: { slug: enrollment.branch.slug },
+ });
+ global.ExperimentAPI.getAllBranches.resolves([
+ enrollment.branch,
+ {
+ slug: "branch02",
+ cfr: {
+ featureId: "cfr",
+ value: { id: "id02", trigger: { id: "openURL" } },
+ },
+ },
+ {
+ // This branch should not be loaded as it doesn't have the trigger
+ slug: "branch03",
+ cfr: {
+ featureId: "cfr",
+ 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",
+ });
+ });
+ });
+ describe("#_remoteSettingsLoader", () => {
+ let provider;
+ let spy;
+ beforeEach(() => {
+ provider = {
+ id: "cfr",
+ collection: "cfr",
+ };
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .resolves([{ id: "message_1" }]);
+ spy = sandbox.spy();
+ global.Downloader.prototype.downloadToDisk = spy;
+ });
+ it("should be called with the expected dir path", async () => {
+ const dlSpy = sandbox.spy(global, "Downloader");
+
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.calledWith(
+ dlSpy,
+ "main",
+ "ms-language-packs",
+ "browser",
+ "newtab"
+ );
+ });
+ it("should allow fetch for known locales", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+
+ 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");
+ 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 fallback to 'ja-JP-mac' for locale 'ja-JP-macos'", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "ja-JP-macos");
+ const getRecordSpy = sandbox.spy(
+ global.KintoHttpClient.prototype,
+ "getRecord"
+ );
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.ok(getRecordSpy.args[0][0].includes("ja-JP-mac"));
+ assert.calledOnce(spy);
+ });
+ it("should not allow fetch for unsupported locales", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "unkown");
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.notCalled(spy);
+ });
+ });
+ describe("#resetMessageState", () => {
+ it("should reset all message impressions", async () => {
+ await Router.setState({
+ messages: [{ id: "1" }, { id: "2" }],
+ });
+ await Router.setState({
+ messageImpressions: { 1: [0, 1, 2], 2: [0, 1, 2] },
+ }); // Add impressions for test messages
+ let impressions = Object.values(Router.state.messageImpressions);
+ assert.equal(impressions.filter(i => i.length).length, 2); // Both messages have impressions
+
+ Router.resetMessageState();
+ impressions = Object.values(Router.state.messageImpressions);
+
+ assert.isEmpty(impressions.filter(i => i.length)); // Both messages now have zero impressions
+ assert.calledWithExactly(Router._storage.set, "messageImpressions", {
+ 1: [],
+ 2: [],
+ });
+ });
+ });
+ describe("#resetGroupsState", () => {
+ it("should reset all group impressions", async () => {
+ await Router.setState({
+ groups: [{ id: "1" }, { id: "2" }],
+ });
+ await Router.setState({
+ groupImpressions: { 1: [0, 1, 2], 2: [0, 1, 2] },
+ }); // Add impressions for test groups
+ let impressions = Object.values(Router.state.groupImpressions);
+ assert.equal(impressions.filter(i => i.length).length, 2); // Both groups have impressions
+
+ Router.resetGroupsState();
+ impressions = Object.values(Router.state.groupImpressions);
+
+ assert.isEmpty(impressions.filter(i => i.length)); // Both groups now have zero impressions
+ assert.calledWithExactly(Router._storage.set, "groupImpressions", {
+ 1: [],
+ 2: [],
+ });
+ });
+ });
+});
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..346f0e02f3
--- /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.sys.mjs";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.sys.mjs";
+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..938c85d7de
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js
@@ -0,0 +1,153 @@
+/*eslint max-nested-callbacks: ["error", 10]*/
+import { ASRouterNewTabHook } from "lib/ASRouterNewTabHook.sys.mjs";
+
+describe("ASRouterNewTabHook", () => {
+ let sandbox = null;
+ let initParams = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ initParams = {
+ router: {
+ init: sandbox.stub().callsFake(() => {
+ // Fake the initialization
+ initParams.router.initialized = true;
+ }),
+ 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..1b494bbe0e
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js
@@ -0,0 +1,106 @@
+import { ASRouterParent } from "actors/ASRouterParent.sys.mjs";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.sys.mjs";
+
+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(),
+ 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,
+ },
+ };
+ asRouterParent.tabId = ASRouterParent.nextTabId;
+ });
+ 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);
+ assert.equal(result, "handle-message-result");
+ });
+ it("it messages all actors on BLOCK_MESSAGE_BY_ID messages", async () => {
+ const MESSAGE_ID = 1;
+ const result = await asRouterParent.receiveMessage({
+ name: msg.BLOCK_MESSAGE_BY_ID,
+ data: { id: MESSAGE_ID, campaign: "message-campaign" },
+ });
+ assert.calledOnce(handleMessage);
+ // Check that we correctly pass the tabId
+ assert.calledWithExactly(
+ handleMessage,
+ sinon.match.any,
+ sinon.match.any,
+ { id: sinon.match.number, browser: sinon.match.any }
+ );
+ assert.calledWithExactly(
+ ASRouterParent.tabs.messageAll,
+ "ClearMessages",
+ // When blocking an id the entire campaign is blocked
+ // and all other snippets become invalid
+ ["message-campaign"]
+ );
+ assert.equal(result, "handle-message-result");
+ });
+ });
+});
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..1f35ab875e
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js
@@ -0,0 +1,428 @@
+import { ASRouterParentProcessMessageHandler } from "lib/ASRouterParentProcessMessageHandler.jsm";
+import { _ASRouter } from "lib/ASRouter.jsm";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.sys.mjs";
+
+describe("ASRouterParentProcessMessageHandler", () => {
+ let handler = null;
+ let sandbox = null;
+ let config = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ const returnValue = { value: 1 };
+ const router = new _ASRouter();
+ [
+ "addImpression",
+ "addPreviewEndpoint",
+ "evaluateExpression",
+ "forceAttribution",
+ "forceWNPanel",
+ "closeWNPanel",
+ "forcePBWindow",
+ "resetGroupsState",
+ ].forEach(method => sandbox.stub(router, `${method}`).resolves());
+ [
+ "blockMessageById",
+ "loadMessagesFromAllProviders",
+ "sendNewTabMessage",
+ "sendTriggerMessage",
+ "routeCFRMessage",
+ "setMessageById",
+ "updateTargetingParameters",
+ "unblockMessageById",
+ "unblockAll",
+ ].forEach(method =>
+ sandbox.stub(router, `${method}`).resolves(returnValue)
+ );
+ router._storage = {
+ set: sandbox.stub().resolves(),
+ get: sandbox.stub().resolves(),
+ };
+ sandbox.stub(router, "setState").callsFake(callback => {
+ if (typeof callback === "function") {
+ callback({
+ messageBlockList: [
+ {
+ id: 0,
+ },
+ {
+ id: 1,
+ },
+ {
+ id: 2,
+ },
+ {
+ id: 3,
+ },
+ {
+ id: 4,
+ },
+ ],
+ });
+ }
+ return Promise.resolve(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("default calls SpecialMessageActions.handleAction", async () => {
+ await handler.handleMessage(
+ msg.USER_ACTION,
+ {
+ type: "SOMETHING",
+ },
+ { browser: { ownerGlobal: {} } }
+ );
+ 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("FORCE_PRIVATE_BROWSING_WINDOW action", () => {
+ it("default calls forcePBWindow", () => {
+ handler.handleMessage(
+ msg.FORCE_PRIVATE_BROWSING_WINDOW,
+ {},
+ { browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.forcePBWindow);
+ assert.calledWith(config.router.forcePBWindow, { ownerGlobal: {} });
+ });
+ });
+ describe("MODIFY_MESSAGE_JSON action", () => {
+ it("default calls routeCFRMessage", async () => {
+ const result = await handler.handleMessage(
+ msg.MODIFY_MESSAGE_JSON,
+ {
+ content: {
+ text: "something",
+ },
+ },
+ { browser: { ownerGlobal: {} }, id: 100 }
+ );
+ assert.calledOnce(config.router.routeCFRMessage);
+ assert.calledWith(
+ config.router.routeCFRMessage,
+ { text: "something" },
+ { ownerGlobal: {} },
+ { content: { text: "something" } },
+ true
+ );
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("OVERRIDE_MESSAGE action", () => {
+ it("default calls setMessageById", 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..3ad759d6b9
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js
@@ -0,0 +1,491 @@
+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;
+ let resetStub;
+ let hasUserValueStub;
+ let childListStub;
+ let setStringPrefStub;
+
+ beforeEach(() => {
+ ASRouterPreferences = new _ASRouterPreferences();
+
+ sandbox = sinon.createSandbox();
+ addObserverStub = sandbox.stub(global.Services.prefs, "addObserver");
+ stringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+ resetStub = sandbox.stub(global.Services.prefs, "clearUserPref");
+ setStringPrefStub = sandbox.stub(global.Services.prefs, "setStringPref");
+ FAKE_PROVIDERS.forEach(provider => {
+ stringPrefStub
+ .withArgs(`${PROVIDER_PREF_BRANCH}${provider.id}`)
+ .returns(JSON.stringify(provider));
+ });
+
+ boolPrefStub = sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .returns(false);
+
+ hasUserValueStub = sandbox
+ .stub(global.Services.prefs, "prefHasUserValue")
+ .returns(false);
+
+ childListStub = sandbox.stub(global.Services.prefs, "getChildList");
+ childListStub
+ .withArgs(PROVIDER_PREF_BRANCH)
+ .returns(
+ FAKE_PROVIDERS.map(provider => `${PROVIDER_PREF_BRANCH}${provider.id}`)
+ );
+ });
+
+ 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 migrate the provider prefs", () => {
+ ASRouterPreferences.uninit();
+ // Should be migrated because they contain bucket and not collection
+ const MIGRATE_PROVIDERS = [
+ { id: "baz", bucket: "buk" },
+ { id: "qux", bucket: "buk" },
+ ];
+ // Should be cleared to defaults because it throws on setStringPref
+ const ERROR_PROVIDER = { id: "err", bucket: "buk" };
+ // Should not be migrated because, although modified, it lacks bucket
+ const MODIFIED_SAFE_PROVIDER = { id: "safe" };
+ const ALL_PROVIDERS = [
+ ...MIGRATE_PROVIDERS,
+ ...FAKE_PROVIDERS, // Should not be migrated because they're unmodified
+ MODIFIED_SAFE_PROVIDER,
+ ERROR_PROVIDER,
+ ];
+ // The migrator should attempt to read prefs for all of these providers
+ const TRY_PROVIDERS = [
+ ...MIGRATE_PROVIDERS,
+ MODIFIED_SAFE_PROVIDER,
+ ERROR_PROVIDER,
+ ];
+
+ // Update the full list of provider prefs
+ childListStub
+ .withArgs(PROVIDER_PREF_BRANCH)
+ .returns(
+ ALL_PROVIDERS.map(provider => getPrefNameForProvider(provider.id))
+ );
+ // Stub the pref values so the migrator can read them
+ ALL_PROVIDERS.forEach(provider => {
+ stringPrefStub
+ .withArgs(getPrefNameForProvider(provider.id))
+ .returns(JSON.stringify(provider));
+ });
+
+ // Consider these providers' prefs "modified"
+ TRY_PROVIDERS.forEach(provider => {
+ hasUserValueStub
+ .withArgs(`${PROVIDER_PREF_BRANCH}${provider.id}`)
+ .returns(true);
+ });
+ // Spoof an error when trying to set the pref for this provider so we can
+ // test that the pref is gracefully reset on error
+ setStringPrefStub
+ .withArgs(getPrefNameForProvider(ERROR_PROVIDER.id))
+ .throws();
+
+ ASRouterPreferences.init();
+
+ // The migrator should have tried to check each pref for user modification
+ ALL_PROVIDERS.forEach(provider =>
+ assert.calledWith(hasUserValueStub, getPrefNameForProvider(provider.id))
+ );
+ // Test that we don't call getStringPref for providers that don't have a
+ // user-defined value
+ FAKE_PROVIDERS.forEach(provider =>
+ assert.neverCalledWith(
+ stringPrefStub,
+ getPrefNameForProvider(provider.id)
+ )
+ );
+ // But we do call it for providers that do have a user-defined value
+ TRY_PROVIDERS.forEach(provider =>
+ assert.calledWith(stringPrefStub, getPrefNameForProvider(provider.id))
+ );
+
+ // Test that we don't call setStringPref to migrate providers that don't
+ // have a bucket property
+ assert.neverCalledWith(
+ setStringPrefStub,
+ getPrefNameForProvider(MODIFIED_SAFE_PROVIDER.id)
+ );
+
+ /**
+ * For a given provider, return a sinon matcher that matches if the value
+ * looks like a migrated version of the original provider. Requires that:
+ * its id matches the original provider's id; it has no bucket; and its
+ * collection is set to the value of the original provider's bucket.
+ * @param {object} provider the provider object to compare to
+ * @returns {object} custom matcher object for sinon
+ */
+ function providerJsonMatches(provider) {
+ return sandbox.match(migrated => {
+ const parsed = JSON.parse(migrated);
+ return (
+ parsed.id === provider.id &&
+ !("bucket" in parsed) &&
+ parsed.collection === provider.bucket
+ );
+ });
+ }
+
+ // Test that we call setStringPref to migrate providers that have a bucket
+ // property and don't have a collection property
+ MIGRATE_PROVIDERS.forEach(provider =>
+ assert.calledWith(
+ setStringPrefStub,
+ getPrefNameForProvider(provider.id),
+ providerJsonMatches(provider) // Verify the migrated pref value
+ )
+ );
+
+ // Test that we clear the pref for providers that throw when we try to
+ // read or write them
+ assert.calledWith(resetStub, getPrefNameForProvider(ERROR_PROVIDER.id));
+ });
+ 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", () => {
+ setPrefForProvider("foo", { id: "foo", enabled: false });
+ assert.isFalse(ASRouterPreferences.providers[0].enabled);
+
+ ASRouterPreferences.enableOrDisableProvider("foo", true);
+
+ assert.calledWith(
+ setStringPrefStub,
+ getPrefNameForProvider("foo"),
+ JSON.stringify({ id: "foo", enabled: true })
+ );
+ });
+ it("should disable an existing provider if second param is false", () => {
+ setPrefForProvider("foo", { id: "foo", enabled: true });
+ assert.isTrue(ASRouterPreferences.providers[0].enabled);
+
+ ASRouterPreferences.enableOrDisableProvider("foo", false);
+
+ assert.calledWith(
+ setStringPrefStub,
+ 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", () => {
+ 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));
+ childListStub
+ .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);
+ childListStub.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.console, "error");
+
+ ASRouterPreferences._transformPersonalizedCfrScores("");
+
+ assert.calledOnce(global.console.error);
+ });
+ 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..a6e0eea3af
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js
@@ -0,0 +1,574 @@
+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;
+ let doesAppNeedPinStub;
+ let getAddonsByTypesStub;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ clock = sinon.useFakeTimers();
+ frecentStub = sandbox.stub(
+ global.NewTabUtils.activityStreamProvider,
+ "getTopFrecentSites"
+ );
+ topsitesCache = new CachedTargetingGetter("getTopFrecentSites");
+ globals = new GlobalOverrider();
+ globals.set(
+ "TargetingContext",
+ class {
+ static combineContexts(...args) {
+ return sinon.stub();
+ }
+
+ evalWithDefault(expr) {
+ return sinon.stub();
+ }
+ }
+ );
+ doesAppNeedPinStub = sandbox.stub().resolves();
+ getAddonsByTypesStub = sandbox.stub().resolves();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ clock.restore();
+ globals.restore();
+ });
+
+ it("should cache allow for optional getter argument", async () => {
+ let pinCachedGetter = new CachedTargetingGetter(
+ "doesAppNeedPin",
+ true,
+ undefined,
+ { doesAppNeedPin: doesAppNeedPinStub }
+ );
+ // Need to tick forward because Date.now() is stubbed
+ clock.tick(sixHours);
+
+ await pinCachedGetter.get();
+ await pinCachedGetter.get();
+ await pinCachedGetter.get();
+
+ // Called once; cached request
+ assert.calledOnce(doesAppNeedPinStub);
+
+ // Called with option argument
+ assert.calledWith(doesAppNeedPinStub, true);
+
+ // Expire and call again
+ clock.tick(sixHours);
+ await pinCachedGetter.get();
+
+ // Call goes through
+ assert.calledTwice(doesAppNeedPinStub);
+
+ let themesCachedGetter = new CachedTargetingGetter(
+ "getAddonsByTypes",
+ ["foo"],
+ undefined,
+ { getAddonsByTypes: getAddonsByTypesStub }
+ );
+
+ // Need to tick forward because Date.now() is stubbed
+ clock.tick(sixHours);
+
+ await themesCachedGetter.get();
+ await themesCachedGetter.get();
+ await themesCachedGetter.get();
+
+ // Called once; cached request
+ assert.calledOnce(getAddonsByTypesStub);
+
+ // Called with option argument
+ assert.calledWith(getAddonsByTypesStub, ["foo"]);
+
+ // Expire and call again
+ clock.tick(sixHours);
+ await themesCachedGetter.get();
+
+ // Call goes through
+ assert.calledTwice(getAddonsByTypesStub);
+ });
+
+ 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(global.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(global.fxAccounts.listAttachedOAuthClients);
+
+ clock.tick(fourHours);
+ await authClientsCache.get();
+ assert.calledTwice(global.fxAccounts.listAttachedOAuthClients);
+ });
+
+ it("should not make additional request before 4 hours", async () => {
+ clock.tick(fourHours);
+
+ await authClientsCache.get();
+ assert.calledOnce(global.fxAccounts.listAttachedOAuthClients);
+
+ await authClientsCache.get();
+ assert.calledOnce(global.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(),
+ setTelemetrySource: sandbox.stub(),
+ };
+ globals = new GlobalOverrider();
+ globals.set(
+ "TargetingContext",
+ class {
+ static combineContexts(...args) {
+ return fakeTargetingContext.combineContexts.apply(sandbox, args);
+ }
+
+ setTelemetrySource(id) {
+ fakeTargetingContext.setTelemetrySource(id);
+ }
+
+ evalWithDefault(expr) {
+ return fakeTargetingContext.evalWithDefault(expr);
+ }
+ }
+ );
+ evalStub = fakeTargetingContext.evalWithDefault;
+ });
+ afterEach(() => {
+ clock.restore();
+ sandbox.restore();
+ globals.restore();
+ });
+ it("should provide message.id as source", async () => {
+ await ASRouterTargeting.checkMessageTargeting(
+ {
+ id: "message",
+ targeting: "true",
+ },
+ fakeTargetingContext,
+ sandbox.stub(),
+ false
+ );
+ assert.calledOnce(fakeTargetingContext.evalWithDefault);
+ assert.calledWithExactly(fakeTargetingContext.evalWithDefault, "true");
+ assert.calledWithExactly(
+ fakeTargetingContext.setTelemetrySource,
+ "message"
+ );
+ });
+ 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;
+ beforeEach(() => {
+ globals.set({ ASRouterPreferences });
+ sandbox = sinon.createSandbox();
+ });
+ 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 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 }
+ );
+ });
+});
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..52a7785e05
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js
@@ -0,0 +1,778 @@
+import { ASRouterTriggerListeners } from "lib/ASRouterTriggerListeners.jsm";
+import { ASRouterPreferences } from "lib/ASRouterPreferences.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 captivePortalLoginListener =
+ ASRouterTriggerListeners.get("captivePortalLogin");
+ const bookmarkedURLListener =
+ ASRouterTriggerListeners.get("openBookmarkedURL");
+ const openArticleURLListener = ASRouterTriggerListeners.get("openArticleURL");
+ const nthTabClosedListener = ASRouterTriggerListeners.get("nthTabClosed");
+ const idleListener = ASRouterTriggerListeners.get("activityAfterIdle");
+ const formAutofillListener = ASRouterTriggerListeners.get("formAutofill");
+ const cookieBannerDetectedListener = ASRouterTriggerListeners.get(
+ "cookieBannerDetected"
+ );
+ const hosts = ["www.mozilla.com", "www.mozilla.org"];
+
+ const regionFake = {
+ _home: "cn",
+ _current: "cn",
+ get home() {
+ return this._home;
+ },
+ get current() {
+ return this._current;
+ },
+ };
+
+ 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);
+ },
+ });
+ globals.set("Region", regionFake);
+ globals.set("ASRouterPreferences", ASRouterPreferences);
+ });
+
+ 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("captivePortal", () => {
+ describe("observe", () => {
+ it("should not call the trigger handler if _shouldShowCaptivePortalVPNPromo returns false", () => {
+ sandbox
+ .stub(captivePortalLoginListener, "_shouldShowCaptivePortalVPNPromo")
+ .returns(false);
+ captivePortalLoginListener._triggerHandler = sandbox.spy();
+
+ captivePortalLoginListener.observe(
+ null,
+ "captive-portal-login-success"
+ );
+
+ assert.notCalled(captivePortalLoginListener._triggerHandler);
+ });
+
+ it("should call the trigger handler if _shouldShowCaptivePortalVPNPromo returns true", () => {
+ sandbox
+ .stub(captivePortalLoginListener, "_shouldShowCaptivePortalVPNPromo")
+ .returns(true);
+ sandbox.stub(Services.wm, "getMostRecentBrowserWindow").returns({
+ gBrowser: {
+ selectedBrowser: true,
+ },
+ });
+ captivePortalLoginListener._triggerHandler = sandbox.spy();
+
+ captivePortalLoginListener.observe(
+ null,
+ "captive-portal-login-success"
+ );
+
+ assert.calledOnce(captivePortalLoginListener._triggerHandler);
+ });
+ });
+ });
+
+ 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("nthTabClosed", () => {
+ describe("#init", () => {
+ beforeEach(() => {
+ nthTabClosedListener.init(triggerHandler);
+ });
+ afterEach(() => {
+ nthTabClosedListener.uninit();
+ });
+
+ it("should set ._initialized to true and save the triggerHandler", () => {
+ assert.ok(nthTabClosedListener._initialized);
+ assert.equal(nthTabClosedListener._triggerHandler, triggerHandler);
+ });
+
+ it("if already initialised, it should only update the trigger handler", () => {
+ const newTriggerHandler = () => {};
+ nthTabClosedListener.init(newTriggerHandler);
+ assert.ok(nthTabClosedListener._initialized);
+ assert.equal(nthTabClosedListener._triggerHandler, newTriggerHandler);
+ });
+
+ it("should add an event listeners to all existing browser windows", () => {
+ assert.calledOnce(existingWindow.addEventListener);
+ assert.calledWith(existingWindow.addEventListener, "TabClose");
+ });
+ });
+
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ nthTabClosedListener.init(triggerHandler);
+ nthTabClosedListener.uninit();
+ });
+ it("should set ._initialized to false and clear the triggerHandler, closed tabs count", () => {
+ assert.notOk(nthTabClosedListener._initialized);
+ assert.equal(nthTabClosedListener._triggerHandler, null);
+ assert.equal(nthTabClosedListener._closedTabs, 0);
+ });
+
+ it("should do nothing if already uninitialised", () => {
+ nthTabClosedListener.uninit();
+ assert.notOk(nthTabClosedListener._initialized);
+ });
+
+ it("should remove event listeners from all existing browser windows", () => {
+ assert.calledOnce(existingWindow.removeEventListener);
+ });
+ });
+ });
+
+ describe("activityAfterIdle", () => {
+ let addObsStub;
+ let removeObsStub;
+ describe("#init", () => {
+ beforeEach(() => {
+ addObsStub = sandbox.stub(global.Services.obs, "addObserver");
+ sandbox
+ .stub(global.Services.wm, "getEnumerator")
+ .returns([{ closed: false, document: { hidden: false } }]);
+ idleListener.init(triggerHandler);
+ });
+ afterEach(() => {
+ idleListener.uninit();
+ });
+
+ it("should set ._initialized to true and save the triggerHandler", () => {
+ assert.ok(idleListener._initialized);
+ assert.equal(idleListener._triggerHandler, triggerHandler);
+ });
+
+ it("if already initialised, it should only update the trigger handler", () => {
+ const newTriggerHandler = () => {};
+ idleListener.init(newTriggerHandler);
+ assert.ok(idleListener._initialized);
+ assert.equal(idleListener._triggerHandler, newTriggerHandler);
+ });
+
+ it("should add observers for idle and activity", () => {
+ assert.called(addObsStub);
+ });
+
+ it("should add event listeners to all existing browser windows", () => {
+ assert.called(existingWindow.addEventListener);
+ });
+ });
+
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ removeObsStub = sandbox.stub(global.Services.obs, "removeObserver");
+ sandbox.stub(global.Services.wm, "getEnumerator").returns([]);
+ idleListener.init(triggerHandler);
+ idleListener.uninit();
+ });
+ it("should set ._initialized to false and clear the triggerHandler and timestamps", () => {
+ assert.notOk(idleListener._initialized);
+ assert.equal(idleListener._triggerHandler, null);
+ assert.equal(idleListener._quietSince, null);
+ });
+
+ it("should do nothing if already uninitialised", () => {
+ idleListener.uninit();
+ assert.notOk(idleListener._initialized);
+ });
+
+ it("should remove observers for idle and activity", () => {
+ assert.called(removeObsStub);
+ });
+
+ it("should remove event listeners from all existing browser windows", () => {
+ assert.called(existingWindow.removeEventListener);
+ });
+ });
+ });
+
+ describe("formAutofill", () => {
+ let addObsStub;
+ let removeObsStub;
+ describe("#init", () => {
+ beforeEach(() => {
+ addObsStub = sandbox.stub(global.Services.obs, "addObserver");
+ formAutofillListener.init(triggerHandler);
+ });
+ afterEach(() => {
+ formAutofillListener.uninit();
+ });
+
+ it("should set ._initialized to true and save the triggerHandler", () => {
+ assert.ok(formAutofillListener._initialized);
+ assert.equal(formAutofillListener._triggerHandler, triggerHandler);
+ });
+
+ it("if already initialised, it should only update the trigger handler", () => {
+ const newTriggerHandler = () => {};
+ formAutofillListener.init(newTriggerHandler);
+ assert.ok(formAutofillListener._initialized);
+ assert.equal(formAutofillListener._triggerHandler, newTriggerHandler);
+ });
+
+ it(`should add observer for ${formAutofillListener._topic}`, () => {
+ assert.called(addObsStub);
+ });
+ });
+
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ removeObsStub = sandbox.stub(global.Services.obs, "removeObserver");
+ formAutofillListener.init(triggerHandler);
+ formAutofillListener.uninit();
+ });
+
+ it("should set ._initialized to false and clear the triggerHandler", () => {
+ assert.notOk(formAutofillListener._initialized);
+ assert.equal(formAutofillListener._triggerHandler, null);
+ });
+
+ it("should do nothing if already uninitialised", () => {
+ formAutofillListener.uninit();
+ assert.notOk(formAutofillListener._initialized);
+ });
+
+ it(`should remove observers for ${formAutofillListener._topic}`, () => {
+ assert.called(removeObsStub);
+ });
+ });
+ });
+
+ 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);
+ });
+ });
+ });
+
+ describe("cookieBannerDetected", () => {
+ describe("#init", () => {
+ beforeEach(() => {
+ cookieBannerDetectedListener.init(triggerHandler);
+ });
+ afterEach(() => {
+ cookieBannerDetectedListener.uninit();
+ });
+
+ it("should set ._initialized to true and save the triggerHandler", () => {
+ assert.ok(cookieBannerDetectedListener._initialized);
+ assert.equal(
+ cookieBannerDetectedListener._triggerHandler,
+ triggerHandler
+ );
+ });
+
+ it("if already initialised, it should only update the trigger handler", () => {
+ const newTriggerHandler = () => {};
+ cookieBannerDetectedListener.init(newTriggerHandler);
+ assert.ok(cookieBannerDetectedListener._initialized);
+ assert.equal(
+ cookieBannerDetectedListener._triggerHandler,
+ newTriggerHandler
+ );
+ });
+
+ it("should add an event listeners to all existing browser windows", () => {
+ assert.calledOnce(existingWindow.addEventListener);
+ });
+ });
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ cookieBannerDetectedListener.init(triggerHandler);
+ cookieBannerDetectedListener.uninit();
+ });
+ it("should set ._initialized to false and clear the triggerHandler and timestamps", () => {
+ assert.notOk(cookieBannerDetectedListener._initialized);
+ assert.equal(cookieBannerDetectedListener._triggerHandler, null);
+ });
+
+ it("should do nothing if already uninitialised", () => {
+ cookieBannerDetectedListener.uninit();
+ assert.notOk(cookieBannerDetectedListener._initialized);
+ });
+
+ it("should remove event listeners from all existing browser windows", () => {
+ assert.called(existingWindow.removeEventListener);
+ });
+ });
+ });
+});
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..a5748d59ce
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js
@@ -0,0 +1,32 @@
+import { CFRMessageProvider } from "lib/CFRMessageProvider.sys.mjs";
+
+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 11 messages", () => {
+ assert.lengthOf(messages, 11);
+ });
+ 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`);
+ }
+ });
+});
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..744b9f148c
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js
@@ -0,0 +1,1252 @@
+/* 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.sys.mjs";
+
+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",
+ ];
+ 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",
+ });
+ });
+ });
+
+ 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 and send dismiss telemetry on 'dismissed'", () => {
+ pageAction._expand();
+
+ sandbox.spy(pageAction, "_sendTelemetry");
+
+ pageAction._popupStateChange("dismissed");
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "collapsed"
+ );
+
+ assert.equal(
+ pageAction._sendTelemetry.lastCall.args[0].event,
+ "DISMISS"
+ );
+ });
+ 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.console, "error");
+
+ 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 * 16).toFixed(1)}px`
+ );
+ assert.equal(
+ footerEmptyStars.style.width,
+ `${(0.8 * 16).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}`
+ );
+ });
+ 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 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,
+ persistWhileVisible: false,
+ popupIconClass: fakeRecommendation.content.icon_class,
+ recordTelemetryInPrivateBrowsing:
+ fakeRecommendation.content.show_in_private_browsing,
+ name: {
+ string_id: "cfr-doorhanger-extension-author",
+ args: { name: fakeRecommendation.content.addon.author },
+ },
+ }
+ );
+ });
+ });
+ 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("showPopup", () => {
+ let savedRec;
+ let pageAction;
+ let fakeAnchorId = "fake_anchor_id";
+ let sandboxShowPopup = sinon.createSandbox();
+ let fakePopUp = {
+ id: "fake_id",
+ template: "cfr_doorhanger",
+ content: {
+ skip_address_bar_notifier: true,
+ heading_text: "Fake Heading Text",
+ anchor_id: "fake_anchor_id",
+ },
+ };
+ beforeEach(() => {
+ const { id, content } = fakePopUp;
+ savedRec = {
+ id,
+ host: fakeHost,
+ content,
+ };
+ CFRPageActions.RecommendationMap.set(fakeBrowser, savedRec);
+ pageAction = new PageAction(window, dispatchStub);
+
+ sandboxShowPopup.stub(window.document, "getElementById");
+ sandboxShowPopup.stub(pageAction, "_renderPopup");
+ globals.set({
+ CustomizableUI: {
+ getWidget: sandboxShowPopup
+ .stub()
+ .withArgs(fakeAnchorId)
+ .returns({ areaType: "menu-panel" }),
+ },
+ });
+ });
+ afterEach(() => {
+ sandboxShowPopup.restore();
+ globals.restore();
+ });
+
+ it("Should use default anchor_id if an alternate hasn't been provided", async () => {
+ await pageAction.showPopup();
+
+ assert.calledWith(window.document.getElementById, fakeAnchorId);
+ });
+
+ it("Should use alt_anchor_if if one has been provided AND the anchor_id has been removed", async () => {
+ let fakeAltAnchorId = "fake_alt_anchor_id";
+
+ fakePopUp.content.alt_anchor_id = fakeAltAnchorId;
+ await pageAction.showPopup();
+ assert.calledWith(window.document.getElementById, fakeAltAnchorId);
+ });
+ });
+
+ 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 successfully add a private browsing recommendation and send correct telemetry", async () => {
+ global.PrivateBrowsingUtils.isWindowPrivate.returns(true);
+ fakeRecommendation.content.show_in_private_browsing = true;
+ assert.isTrue(
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+
+ const pageAction = CFRPageActions.PageActionMap.get(
+ fakeBrowser.ownerGlobal
+ );
+ await pageAction.showAddressBarNotifier(fakeRecommendation, true);
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ is_private: true,
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "IMPRESSION",
+ },
+ });
+ });
+ 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 browser does not exist", async () => {
+ assert.isFalse(
+ await CFRPageActions.addRecommendation(
+ undefined,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ 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/RemoteL10n.test.js b/browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js
new file mode 100644
index 0000000000..34adfc88f1
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js
@@ -0,0 +1,217 @@
+import { RemoteL10n, _RemoteL10n } from "lib/RemoteL10n.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("RemoteL10n", () => {
+ let sandbox;
+ let globals;
+ let domL10nStub;
+ let l10nRegStub;
+ let l10nRegInstance;
+ let fileSourceStub;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ domL10nStub = sandbox.stub();
+ l10nRegInstance = {
+ hasSource: sandbox.stub(),
+ registerSources: sandbox.stub(),
+ removeSources: sandbox.stub(),
+ };
+
+ fileSourceStub = sandbox.stub();
+ l10nRegStub = {
+ getInstance: () => {
+ return l10nRegInstance;
+ },
+ };
+ globals.set("DOMLocalization", domL10nStub);
+ globals.set("L10nRegistry", l10nRegStub);
+ globals.set("L10nFileSource", fileSourceStub);
+ });
+ 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);
+ l10nRegInstance.hasSource.returns(false);
+ 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, 2);
+ assert.deepEqual(args[0], [
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ "browser/newtab/asrouter.ftl",
+ "toolkit/branding/accounts.ftl",
+ "toolkit/branding/brandings.ftl",
+ ]);
+ assert.isFalse(args[1]);
+ assert.calledOnce(l10nRegInstance.hasSource);
+ assert.calledOnce(l10nRegInstance.registerSources);
+ assert.notCalled(l10nRegInstance.removeSources);
+ });
+ it("should load the local Fluent file if USE_REMOTE_L10N_PREF is false", () => {
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(false);
+ l10nRegInstance.hasSource.returns(true);
+ 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, 2);
+ assert.deepEqual(args[0], [
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ "browser/newtab/asrouter.ftl",
+ "toolkit/branding/accounts.ftl",
+ "toolkit/branding/brandings.ftl",
+ ]);
+ assert.isFalse(args[1]);
+ assert.calledOnce(l10nRegInstance.hasSource);
+ assert.notCalled(l10nRegInstance.registerSources);
+ assert.calledOnce(l10nRegInstance.removeSources);
+ });
+ });
+ 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"));
+ });
+ });
+ describe("#formatLocalizableText", () => {
+ let instance;
+ let formatValueStub;
+ beforeEach(() => {
+ instance = new _RemoteL10n();
+ formatValueStub = sandbox.stub();
+ sandbox
+ .stub(instance, "l10n")
+ .get(() => ({ formatValue: formatValueStub }));
+ });
+ it("should localize a string_id", async () => {
+ formatValueStub.resolves("VALUE");
+
+ assert.equal(
+ await instance.formatLocalizableText({ string_id: "ID" }),
+ "VALUE"
+ );
+ assert.calledOnce(formatValueStub);
+ });
+ it("should pass through a string", async () => {
+ formatValueStub.reset();
+
+ assert.equal(
+ await instance.formatLocalizableText("unchanged"),
+ "unchanged"
+ );
+ assert.isFalse(formatValueStub.called);
+ });
+ });
+});
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..07c2a4d4be
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/RichText.test.jsx
@@ -0,0 +1,101 @@
+import {
+ convertLinks,
+ RichText,
+} from "content-src/asrouter/components/RichText/RichText";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import {
+ Localized,
+ LocalizationProvider,
+ ReactLocalization,
+} from "@fluent/react";
+import { mount } from "enzyme";
+import React from "react";
+
+function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+}
+
+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"
+ />,
+ mockL10nWrapper({ text: "<em>foo</em>" })
+ );
+
+ const localized = wrapper.find(Localized);
+ assert.propertyVal(localized.props().elems.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..fc8fbe15ac
--- /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.sys.mjs";
+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..eaef468488
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js
@@ -0,0 +1,88 @@
+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 = ["messageImpressions", "screenImpressions"];
+ 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..e63256315b
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/compatibility-reference/snippets-fx57.js
@@ -0,0 +1,125 @@
+/**
+ * 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..392ca66ae3
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/constants.js
@@ -0,0 +1,137 @@
+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",
+ collection: "collectionname",
+ 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",
+ icon_class: "Fake Icon class",
+ 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" },
+ },
+ ],
+ },
+ },
+};
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..bd4ab00468
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/EOYSnippet.test.jsx
@@ -0,0 +1,213 @@
+import { EOYSnippet } from "content-src/asrouter/templates/EOYSnippet/EOYSnippet";
+import { GlobalOverrider } from "test/unit/utils";
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/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;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ /**
+ * 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} />,
+ mockL10nWrapper(props.content)
+ );
+ // 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']").exists());
+ });
+
+ 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..bef14c6982
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx
@@ -0,0 +1,112 @@
+import { CFRMessageProvider } from "lib/CFRMessageProvider.sys.mjs";
+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", async () => {
+ const messages = await CFRMessageProvider.getMessages();
+ let doorhangerMessage = messages.find(m => m.id === "FACEBOOK_CONTAINER_3");
+ assert.ok(doorhangerMessage, "Message found");
+ assert.jsonSchema(
+ { ...doorhangerMessage, content: DEFAULT_CONTENT },
+ CFRDoorhangerSchema
+ );
+ });
+ it("should validate L10N_CONTENT", async () => {
+ const messages = await CFRMessageProvider.getMessages();
+ let doorhangerMessage = messages.find(m => m.id === "FACEBOOK_CONTAINER_3");
+ assert.ok(doorhangerMessage, "Message found");
+ assert.jsonSchema(
+ { ...doorhangerMessage, content: L10N_CONTENT },
+ CFRDoorhangerSchema
+ );
+ });
+ it("should validate all messages from CFRMessageProvider", async () => {
+ const messages = await CFRMessageProvider.getMessages();
+ messages.forEach(msg => assert.jsonSchema(msg, 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..56828d266b
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx
@@ -0,0 +1,106 @@
+import { FXASignupSnippet } from "content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet";
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/react";
+import schema from "content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.sys.mjs";
+
+describe("FXASignupSnippet", () => {
+ let DEFAULT_CONTENT;
+ let sandbox;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ 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} />,
+ mockL10nWrapper(props.content)
+ );
+ // 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} />,
+ mockL10nWrapper(DEFAULT_CONTENT)
+ );
+ // 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..cb80abdae0
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx
@@ -0,0 +1,108 @@
+import { mount } from "enzyme";
+import { NewsletterSnippet } from "content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/react";
+import schema from "content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.sys.mjs";
+
+describe("NewsletterSnippet", () => {
+ let sandbox;
+ let DEFAULT_CONTENT;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ 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} />,
+ mockL10nWrapper(props.content)
+ );
+ // 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} />,
+ mockL10nWrapper(DEFAULT_CONTENT)
+ );
+ // 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/SendToDeviceSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx
new file mode 100644
index 0000000000..3c60967643
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx
@@ -0,0 +1,277 @@
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/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.sys.mjs";
+
+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 mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ 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} />,
+ mockL10nWrapper(props.content)
+ );
+ // 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} />,
+ mockL10nWrapper(DEFAULT_CONTENT)
+ );
+ // 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} />,
+ mockL10nWrapper(props.content)
+ );
+ }
+
+ 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..df9e544a54
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx
@@ -0,0 +1,81 @@
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/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;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ /**
+ * 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} />,
+ mockL10nWrapper(props.content)
+ );
+ }
+
+ 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..7c169525e4
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx
@@ -0,0 +1,259 @@
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/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;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ /**
+ * 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} />, mockL10nWrapper(props.content));
+ }
+
+ 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..12e4f96863
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx
@@ -0,0 +1,354 @@
+import { mount } from "enzyme";
+import React from "react";
+import { FluentBundle, FluentResource } from "@fluent/bundle";
+import { LocalizationProvider, ReactLocalization } from "@fluent/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;
+
+ function mockL10nWrapper(content) {
+ const bundle = new FluentBundle("en-US");
+ for (const [id, value] of Object.entries(content)) {
+ if (typeof value === "string") {
+ bundle.addResource(new FluentResource(`${id} = ${value}`));
+ }
+ }
+ const l10n = new ReactLocalization([bundle]);
+ return {
+ wrappingComponent: LocalizationProvider,
+ wrappingComponentProps: { l10n },
+ };
+ }
+
+ /**
+ * 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} />,
+ mockL10nWrapper(props.content)
+ );
+ }
+
+ 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..32e417ea3f
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Actions.test.js
@@ -0,0 +1,236 @@
+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.sys.mjs";
+
+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..1c85eafa50
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Dedupe.test.js
@@ -0,0 +1,38 @@
+import { Dedupe } from "common/Dedupe.sys.mjs";
+
+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..ab2a5b4d62
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Reducers.test.js
@@ -0,0 +1,1566 @@
+import { INITIAL_STATE, insertPinned, reducers } from "common/Reducers.sys.mjs";
+const {
+ TopSites,
+ App,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization,
+ DiscoveryStream,
+ Search,
+ ASRouter,
+} = reducers;
+import { actionTypes as at } from "common/Actions.sys.mjs";
+
+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_BOOKMARKS_REMOVED", () => {
+ const oldState = {
+ rows: [
+ { url: "foo.com" },
+ {
+ url: "bar.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ dateAdded: 123456,
+ },
+ ],
+ };
+ const action = {
+ type: at.PLACES_BOOKMARKS_REMOVED,
+ data: { urls: ["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_BOOKMARKS_REMOVED", () => {
+ const nextState = TopSites(undefined, {
+ type: at.PLACES_BOOKMARKS_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_LINKS_DELETED", () => {
+ const nextState = TopSites(undefined, { type: at.PLACES_LINKS_DELETED });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should remove the site on PLACES_LINKS_DELETED", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const deleteAction = {
+ type: at.PLACES_LINKS_DELETED,
+ data: { urls: ["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_LINKS_DELETED,
+ data: { urls: ["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_BLOCKED", () => {
+ const nextState = Sections(undefined, { type: at.PLACES_LINK_BLOCKED });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should not update state for empty action.data on PLACES_LINKS_DELETED", () => {
+ const nextState = Sections(undefined, { type: at.PLACES_LINKS_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_BOOKMARKS_REMOVED", () => {
+ const nextState = Sections(undefined, {
+ type: at.PLACES_BOOKMARKS_REMOVED,
+ });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should remove the bookmark when PLACES_BOOKMARKS_REMOVED is received", () => {
+ const action = {
+ type: at.PLACES_BOOKMARKS_REMOVED,
+ data: {
+ urls: ["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.urls[0]);
+ 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 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 recentSavesEnabled with DISCOVERY_STREAM_PREFS_SETUP", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_PREFS_SETUP,
+ data: { recentSavesEnabled: true },
+ });
+ assert.isTrue(state.recentSavesEnabled);
+ });
+ it("should set recentSavesData with DISCOVERY_STREAM_RECENT_SAVES", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_RECENT_SAVES,
+ data: { recentSaves: [1, 2, 3] },
+ });
+ assert.deepEqual(state.recentSavesData, [1, 2, 3]);
+ });
+ it("should set isUserLoggedIn with DISCOVERY_STREAM_POCKET_STATE_SET", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_POCKET_STATE_SET,
+ data: { isUserLoggedIn: true },
+ });
+ assert.isTrue(state.isUserLoggedIn);
+ });
+ 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_BOOKMARKS_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_BOOKMARKS_REMOVED,
+ data: {
+ urls: ["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 disable to true on DISABLE_SEARCH", () => {
+ const nextState = Search(undefined, { type: "DISABLE_SEARCH" });
+ assert.propertyVal(nextState, "disable", 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 disable to false on SHOW_SEARCH", () => {
+ const nextState = Search(undefined, { type: "SHOW_SEARCH" });
+ assert.propertyVal(nextState, "fakeFocus", false);
+ assert.propertyVal(nextState, "disable", 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..1bd01fb220
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx
@@ -0,0 +1,516 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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: {
+ lastUpdated: 1000,
+ initialized: true,
+ },
+ }}
+ />
+ );
+ });
+ it("should render with pref checkbox, lastUpdated, and initialized", () => {
+ assert.lengthOf(wrapper.find("TogglePrefCheckbox"), 1);
+ assert.equal(
+ wrapper.find("td").at(1).text(),
+ "Personalization Last Updated"
+ );
+ assert.equal(
+ wrapper.find("td").at(2).text(),
+ new Date(1000).toLocaleString()
+ );
+ assert.equal(
+ wrapper.find("td").at(3).text(),
+ "Personalization Initialized"
+ );
+ assert.equal(wrapper.find("td").at(4).text(), "true");
+ });
+ 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(2).text(), "(no data)");
+ });
+ it("should dispatch DISCOVERY_STREAM_PERSONALIZATION_TOGGLE", () => {
+ wrapper.instance().togglePersonalization();
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_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..3dd7a3d536
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Base.test.jsx
@@ -0,0 +1,130 @@
+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.sys.mjs";
+
+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 dispatch a user event when the customize menu is opened or closed", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <BaseContent
+ {...DEFAULT_PROPS}
+ dispatch={dispatch}
+ App={{ customizeMenuVisible: true }}
+ />
+ );
+ wrapper.instance().openCustomizationMenu();
+ assert.calledWith(dispatch, { type: "SHOW_PERSONALIZE" });
+ assert.calledWith(dispatch, ac.UserEvent({ event: "SHOW_PERSONALIZE" }));
+ wrapper.instance().closeCustomizationMenu();
+ assert.calledWith(dispatch, { type: "HIDE_PERSONALIZE" });
+ 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..5f07570b2e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Card.test.jsx
@@ -0,0 +1,510 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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.sys.mjs";
+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..f2a8e276b4
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx
@@ -0,0 +1,67 @@
+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: { featureConfig: {} } },
+};
+
+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"
+ );
+ });
+
+ 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);
+ });
+ });
+
+ describe("icon", () => {
+ it("no icon should be shown", () => {
+ assert.lengthOf(wrapper.find(".icon"), 0);
+ });
+ });
+});
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..baf203947e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx
@@ -0,0 +1,447 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..a471c09e66
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx
@@ -0,0 +1,182 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..4f7edadc41
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx
@@ -0,0 +1,227 @@
+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.sys.mjs";
+import { Provider } from "react-redux";
+import { combineReducers, createStore } from "redux";
+
+const DEFAULT_PROPS = {
+ onUpdate: () => {},
+ options: [],
+ tabbableOptionsLength: 0,
+};
+
+const DEFAULT_MENU_OPTIONS = [
+ "MoveUp",
+ "MoveDown",
+ "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 not add an icon to any items", () => {
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1", icon: "icon1" }, { type: "separator" }],
+ });
+ const wrapper = mountWithProps(props);
+ assert.lengthOf(wrapper.find(".icon-icon1"), 0);
+ });
+ 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..b4cf2b1261
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx
@@ -0,0 +1,72 @@
+import { actionCreators as ac } from "common/Actions.sys.mjs";
+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"
+ );
+ });
+});
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..7720e07327
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx
@@ -0,0 +1,313 @@
+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 { HorizontalRule } from "content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule";
+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/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://global/skin/icons/info.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,
+ },
+ }}
+ App={{
+ locale: "en-US",
+ }}
+ 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 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")
+ .find(".ds-top-sites")
+ .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..418a731ba1
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx
@@ -0,0 +1,354 @@
+import {
+ _CardGrid as CardGrid,
+ IntersectionObserver,
+ RecentSavesContainer,
+ OnboardingExperience,
+ DSSubHeader,
+} from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.sys.mjs";
+import { Provider } from "react-redux";
+import {
+ DSCard,
+ PlaceholderDSCard,
+} from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
+import { TopicsWidget } from "content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import React from "react";
+import { shallow, mount } from "enzyme";
+
+// Wrap this around any component that uses useSelector,
+// or any mount that uses a child that uses redux.
+function WrapWithProvider({ children, state = INITIAL_STATE }) {
+ let store = createStore(combineReducers(reducers), state);
+ return <Provider store={store}>{children}</Provider>;
+}
+
+describe("<CardGrid>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = shallow(
+ <CardGrid
+ Prefs={INITIAL_STATE.Prefs}
+ DiscoveryStream={INITIAL_STATE.DiscoveryStream}
+ />
+ );
+ });
+
+ 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 4 card classname to card grid", () => {
+ wrapper.setProps({
+ fourCardLayout: true,
+ data: { recommendations: [{}, {}] },
+ });
+
+ assert.ok(wrapper.find(".ds-card-grid-four-card-variant").exists());
+ });
+
+ it("should add no description classname to card grid", () => {
+ wrapper.setProps({
+ hideCardBackground: true,
+ data: { recommendations: [{}, {}] },
+ });
+
+ assert.ok(wrapper.find(".ds-card-grid-hide-background").exists());
+ });
+
+ it("should render sub header in the middle of the card grid for both regular and compact", () => {
+ const commonProps = {
+ essentialReadsHeader: true,
+ editorsPicksHeader: true,
+ items: 12,
+ data: {
+ recommendations: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
+ },
+ Prefs: INITIAL_STATE.Prefs,
+ DiscoveryStream: INITIAL_STATE.DiscoveryStream,
+ };
+ wrapper = mount(
+ <WrapWithProvider>
+ <CardGrid {...commonProps} />
+ </WrapWithProvider>
+ );
+
+ assert.ok(wrapper.find(DSSubHeader).exists());
+
+ wrapper.setProps({
+ compact: true,
+ });
+ wrapper = mount(
+ <WrapWithProvider>
+ <CardGrid {...commonProps} compact={true} />
+ </WrapWithProvider>
+ );
+
+ assert.ok(wrapper.find(DSSubHeader).exists());
+ });
+
+ it("should add/hide description classname to card grid", () => {
+ wrapper.setProps({
+ data: { recommendations: [{}, {}] },
+ });
+
+ assert.ok(wrapper.find(".ds-card-grid-include-descriptions").exists());
+
+ wrapper.setProps({
+ hideDescriptions: true,
+ data: { recommendations: [{}, {}] },
+ });
+
+ assert.ok(!wrapper.find(".ds-card-grid-include-descriptions").exists());
+ });
+
+ it("should create a widget card", () => {
+ wrapper.setProps({
+ widgets: {
+ positions: [{ index: 1 }],
+ data: [{ type: "TopicsWidget" }],
+ },
+ data: {
+ recommendations: [{}, {}, {}],
+ },
+ });
+
+ assert.ok(wrapper.find(TopicsWidget).exists());
+ });
+});
+
+// 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() {}
+
+ disconnect() {}
+ };
+}
+
+describe("<IntersectionObserver>", () => {
+ let wrapper;
+ let fakeWindow;
+ let intersectEntries;
+
+ beforeEach(() => {
+ intersectEntries = [{ isIntersecting: true }];
+ fakeWindow = {
+ IntersectionObserver: buildIntersectionObserver(intersectEntries),
+ };
+ wrapper = mount(<IntersectionObserver windowObj={fakeWindow} />);
+ });
+
+ it("should render an empty div", () => {
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.children().at(0).type(), "div");
+ });
+
+ it("should fire onIntersecting", () => {
+ const onIntersecting = sinon.stub();
+ wrapper = mount(
+ <IntersectionObserver
+ windowObj={fakeWindow}
+ onIntersecting={onIntersecting}
+ />
+ );
+ assert.calledOnce(onIntersecting);
+ });
+});
+
+describe("<RecentSavesContainer>", () => {
+ let wrapper;
+ let fakeWindow;
+ let intersectEntries;
+ let dispatch;
+
+ beforeEach(() => {
+ dispatch = sinon.stub();
+ intersectEntries = [{ isIntersecting: true }];
+ fakeWindow = {
+ IntersectionObserver: buildIntersectionObserver(intersectEntries),
+ };
+ wrapper = mount(
+ <WrapWithProvider
+ state={{
+ DiscoveryStream: {
+ isUserLoggedIn: true,
+ recentSavesData: [
+ {
+ resolved_id: "resolved_id",
+ top_image_url: "top_image_url",
+ title: "title",
+ resolved_url: "https://resolved_url",
+ domain: "domain",
+ excerpt: "excerpt",
+ },
+ ],
+ experimentData: {
+ utmSource: "utmSource",
+ utmContent: "utmContent",
+ utmCampaign: "utmCampaign",
+ },
+ },
+ }}
+ >
+ <RecentSavesContainer
+ gridClassName="ds-card-grid"
+ windowObj={fakeWindow}
+ dispatch={dispatch}
+ />
+ </WrapWithProvider>
+ ).find(RecentSavesContainer);
+ });
+
+ it("should render an IntersectionObserver when not visible", () => {
+ intersectEntries = [{ isIntersecting: false }];
+ fakeWindow = {
+ IntersectionObserver: buildIntersectionObserver(intersectEntries),
+ };
+ wrapper = mount(
+ <WrapWithProvider>
+ <RecentSavesContainer windowObj={fakeWindow} dispatch={dispatch} />
+ </WrapWithProvider>
+ ).find(RecentSavesContainer);
+
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(IntersectionObserver).exists());
+ });
+
+ it("should render nothing if visible until we log in", () => {
+ assert.ok(!wrapper.find(IntersectionObserver).exists());
+ assert.calledOnce(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.AlsoToMain({
+ type: at.DISCOVERY_STREAM_POCKET_STATE_INIT,
+ })
+ );
+ });
+
+ it("should render a grid if visible and logged in", () => {
+ assert.lengthOf(wrapper.find(".ds-card-grid"), 1);
+ assert.lengthOf(wrapper.find(DSSubHeader), 1);
+ assert.lengthOf(wrapper.find(PlaceholderDSCard), 2);
+ assert.lengthOf(wrapper.find(DSCard), 3);
+ });
+
+ it("should render a my list link with proper utm params", () => {
+ assert.equal(
+ wrapper.find(".section-sub-link").at(0).prop("url"),
+ "https://getpocket.com/a?utm_source=utmSource&utm_content=utmContent&utm_campaign=utmCampaign"
+ );
+ });
+
+ it("should fire a UserEvent for my list clicks", () => {
+ wrapper.find(".section-sub-link").at(0).simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: `CARDGRID_RECENT_SAVES_VIEW_LIST`,
+ })
+ );
+ });
+});
+
+describe("<OnboardingExperience>", () => {
+ let wrapper;
+ let fakeWindow;
+ let intersectEntries;
+ let dispatch;
+ let resizeCallback;
+
+ let fakeResizeObserver = class {
+ constructor(callback) {
+ resizeCallback = callback;
+ }
+
+ observe() {}
+
+ unobserve() {}
+
+ disconnect() {}
+ };
+
+ beforeEach(() => {
+ dispatch = sinon.stub();
+ intersectEntries = [{ isIntersecting: true, intersectionRatio: 1 }];
+ fakeWindow = {
+ ResizeObserver: fakeResizeObserver,
+ IntersectionObserver: buildIntersectionObserver(intersectEntries),
+ document: {
+ visibilityState: "visible",
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ },
+ };
+ wrapper = mount(
+ <WrapWithProvider state={{}}>
+ <OnboardingExperience windowObj={fakeWindow} dispatch={dispatch} />
+ </WrapWithProvider>
+ ).find(OnboardingExperience);
+ });
+
+ it("should render a ds-onboarding", () => {
+ assert.ok(wrapper.exists());
+ assert.lengthOf(wrapper.find(".ds-onboarding"), 1);
+ });
+
+ it("should dismiss on dismiss click", () => {
+ wrapper.find(".ds-dismiss-button").simulate("click");
+
+ assert.calledWith(
+ dispatch,
+ ac.DiscoveryStreamUserEvent({
+ event: "BLOCK",
+ source: "POCKET_ONBOARDING",
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.SetPref("discoverystream.onboardingExperience.dismissed", true)
+ );
+ assert.equal(wrapper.getDOMNode().style["max-height"], "0px");
+ assert.equal(wrapper.getDOMNode().style.opacity, "0");
+ });
+
+ it("should update max-height on resize", () => {
+ sinon
+ .stub(wrapper.find(".ds-onboarding-ref").getDOMNode(), "offsetHeight")
+ .get(() => 123);
+ resizeCallback();
+ assert.equal(wrapper.getDOMNode().style["max-height"], "123px");
+ });
+
+ it("should fire intersection events", () => {
+ assert.calledWith(
+ dispatch,
+ ac.DiscoveryStreamUserEvent({
+ event: "IMPRESSION",
+ source: "POCKET_ONBOARDING",
+ })
+ );
+ });
+});
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..3721508a59
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx
@@ -0,0 +1,134 @@
+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 dispatch 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, isSponsoredTopSite: undefined },
+ { url: "456", pocket_id: undefined, isSponsoredTopSite: undefined },
+ { url: "789", pocket_id: undefined, isSponsoredTopSite: undefined },
+ ]);
+
+ assert.equal(secondCall.args[0].type, "DISCOVERY_STREAM_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..2ebba1d4e5
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx
@@ -0,0 +1,544 @@
+import {
+ _DSCard as DSCard,
+ readTimeFromWordCount,
+ DSSource,
+ DefaultMeta,
+ PlaceholderDSCard,
+} from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
+import {
+ DSContextFooter,
+ StatusMessage,
+ SponsorLabel,
+} from "content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { DSLinkMenu } from "content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu";
+import React from "react";
+import { INITIAL_STATE } from "common/Reducers.sys.mjs";
+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 = {
+ url: "about:robots",
+ title: "title",
+ App: {
+ isForStartupCache: false,
+ },
+ DiscoveryStream: INITIAL_STATE.DiscoveryStream,
+};
+
+describe("<DSCard>", () => {
+ let wrapper;
+ let sandbox;
+ let dispatch;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatch = sandbox.stub();
+ wrapper = shallow(<DSCard dispatch={dispatch} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ });
+
+ 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);
+ });
+
+ it("should render time to read", () => {
+ const discoveryStream = {
+ ...INITIAL_STATE.DiscoveryStream,
+ readTime: true,
+ };
+ wrapper = mount(
+ <DSCard
+ time_to_read={4}
+ {...DEFAULT_PROPS}
+ DiscoveryStream={discoveryStream}
+ />
+ );
+ wrapper.setState({ isSeen: true });
+ const defaultMeta = wrapper.find(DefaultMeta);
+ assert.lengthOf(defaultMeta, 1);
+ assert.equal(defaultMeta.props().timeToRead, 4);
+ });
+
+ it("should not show save to pocket button for spocs", () => {
+ wrapper.setProps({
+ id: "fooidx",
+ pos: 1,
+ type: "foo",
+ flightId: 12345,
+ saveToPocketCard: true,
+ });
+
+ let stpButton = wrapper.find(".card-stp-button");
+
+ assert.lengthOf(stpButton, 0);
+ });
+
+ it("should show save to pocket button for non-spocs", () => {
+ wrapper.setProps({
+ id: "fooidx",
+ pos: 1,
+ type: "foo",
+ saveToPocketCard: true,
+ });
+
+ let stpButton = wrapper.find(".card-stp-button");
+
+ assert.lengthOf(stpButton, 1);
+ });
+
+ describe("onLinkClick", () => {
+ let fakeWindow;
+
+ beforeEach(() => {
+ fakeWindow = {
+ requestIdleCallback: sinon.stub().returns(1),
+ cancelIdleCallback: sinon.stub(),
+ innerWidth: 1000,
+ innerHeight: 900,
+ };
+ wrapper = mount(
+ <DSCard {...DEFAULT_PROPS} dispatch={dispatch} windowObj={fakeWindow} />
+ );
+ });
+
+ 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.DiscoveryStreamUserEvent({
+ 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, type: "organic" }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+
+ 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.DiscoveryStreamUserEvent({
+ 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, type: "spoc" }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+
+ 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.DiscoveryStreamUserEvent({
+ 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", type: "organic" },
+ ],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+ });
+
+ 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());
+ });
+ });
+
+ 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,
+ },
+ DiscoveryStream: INITIAL_STATE.DiscoveryStream,
+ };
+ wrapper = mount(<DSCard {...props} />);
+ });
+
+ it("should be set as isSeen automatically", () => {
+ assert.isTrue(wrapper.instance().state.isSeen);
+ });
+ });
+
+ describe("DSCard onSaveClick", () => {
+ it("should fire telemetry for onSaveClick", () => {
+ wrapper.setProps({ id: "fooidx", pos: 1, type: "foo" });
+ wrapper.instance().onSaveClick();
+
+ assert.calledThrice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "about:robots", title: "title" } },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ source: "CARDGRID_HOVER",
+ action_position: 1,
+ value: { card_type: "organic" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ source: "CARDGRID_HOVER",
+ pocket: 0,
+ tiles: [
+ {
+ id: "fooidx",
+ pos: 1,
+ },
+ ],
+ })
+ );
+ });
+ });
+
+ describe("DSCard menu open states", () => {
+ let cardNode;
+ let fakeDocument;
+ let fakeWindow;
+
+ beforeEach(() => {
+ fakeDocument = { l10n: { translateFragment: sinon.stub() } };
+ fakeWindow = {
+ document: fakeDocument,
+ requestIdleCallback: sinon.stub().returns(1),
+ cancelIdleCallback: sinon.stub(),
+ };
+ wrapper = mount(<DSCard {...DEFAULT_PROPS} windowObj={fakeWindow} />);
+ wrapper.setState({ isSeen: true });
+ cardNode = wrapper.getDOMNode();
+ });
+
+ it("Should remove active on Menu Update", () => {
+ // Add active class name to DSCard wrapper
+ // to simulate menu open state
+ cardNode.classList.add("active");
+ assert.equal(
+ cardNode.className,
+ "ds-card ds-card-title-lines-3 ds-card-desc-lines-3 active"
+ );
+
+ wrapper.instance().onMenuUpdate(false);
+ wrapper.update();
+
+ assert.equal(
+ cardNode.className,
+ "ds-card ds-card-title-lines-3 ds-card-desc-lines-3"
+ );
+ });
+
+ it("Should add active on Menu Show", async () => {
+ await wrapper.instance().onMenuShow();
+ wrapper.update();
+ assert.equal(
+ cardNode.className,
+ "ds-card ds-card-title-lines-3 ds-card-desc-lines-3 active"
+ );
+ });
+
+ it("Should add last-item to support resized window", async () => {
+ fakeWindow.scrollMaxX = 20;
+ await wrapper.instance().onMenuShow();
+ wrapper.update();
+ assert.equal(
+ cardNode.className,
+ "ds-card ds-card-title-lines-3 ds-card-desc-lines-3 last-item active"
+ );
+ });
+
+ it("should remove .active and .last-item classes", () => {
+ const instance = wrapper.instance();
+ const remove = sinon.stub();
+ instance.contextMenuButtonHostElement = {
+ classList: { remove },
+ };
+ instance.onMenuUpdate();
+ assert.calledOnce(remove);
+ });
+
+ it("should add .active and .last-item classes", async () => {
+ const instance = wrapper.instance();
+ const add = sinon.stub();
+ instance.contextMenuButtonHostElement = {
+ classList: { add },
+ };
+ await instance.onMenuShow();
+ assert.calledOnce(add);
+ });
+ });
+});
+
+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);
+ });
+});
+
+describe("<DSSource> component", () => {
+ it("should return a default source without compact", () => {
+ const wrapper = shallow(<DSSource source="Mozilla" />);
+
+ let sourceElement = wrapper.find(".source");
+ assert.equal(sourceElement.text(), "Mozilla");
+ });
+ it("should return a default source with compact without a sponsor or time to read", () => {
+ const wrapper = shallow(<DSSource compact={true} source="Mozilla" />);
+
+ let sourceElement = wrapper.find(".source");
+ assert.equal(sourceElement.text(), "Mozilla");
+ });
+ it("should return a SponsorLabel with compact and a sponsor", () => {
+ const wrapper = shallow(
+ <DSSource newSponsoredLabel={true} sponsor="Mozilla" />
+ );
+ const sponsorLabel = wrapper.find(SponsorLabel);
+ assert.lengthOf(sponsorLabel, 1);
+ });
+ it("should return a time to read with compact and without a sponsor but with a time to read", () => {
+ const wrapper = shallow(
+ <DSSource compact={true} source="Mozilla" timeToRead="2000" />
+ );
+
+ let timeToRead = wrapper.find(".time-to-read");
+ assert.lengthOf(timeToRead, 1);
+
+ // Weirdly, we can test for the pressence of fluent, because time to read needs to be translated.
+ // This is also because we did a shallow render, that th contents of fluent would be empty anyway.
+ const fluentOrText = wrapper.find(FluentOrText);
+ assert.lengthOf(fluentOrText, 1);
+ });
+ it("should prioritize a SponsorLabel if for some reason it gets everything", () => {
+ const wrapper = shallow(
+ <DSSource
+ newSponsoredLabel={true}
+ sponsor="Mozilla"
+ source="Mozilla"
+ timeToRead="2000"
+ />
+ );
+ const sponsorLabel = wrapper.find(SponsorLabel);
+ assert.lengthOf(sponsorLabel, 1);
+ });
+});
+
+describe("readTimeFromWordCount function", () => {
+ it("should return proper read time", () => {
+ const result = readTimeFromWordCount(2000);
+ assert.equal(result, 10);
+ });
+ it("should return false with falsey word count", () => {
+ assert.isFalse(readTimeFromWordCount());
+ assert.isFalse(readTimeFromWordCount(0));
+ assert.isFalse(readTimeFromWordCount(""));
+ assert.isFalse(readTimeFromWordCount(null));
+ assert.isFalse(readTimeFromWordCount(undefined));
+ });
+ it("should return NaN with invalid word count", () => {
+ assert.isNaN(readTimeFromWordCount("zero"));
+ assert.isNaN(readTimeFromWordCount({}));
+ });
+});
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..08ac7868ce
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx
@@ -0,0 +1,138 @@
+import {
+ DSContextFooter,
+ StatusMessage,
+ DSMessageFooter,
+} 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()));
+ 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 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());
+ });
+ it("should render a story footer", () => {
+ wrapper = mount(
+ <DSMessageFooter
+ context_type={bookmarkBadge}
+ engagement={engagement}
+ display_engagement_labels={true}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(".story-footer"), 1);
+ });
+});
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..bb2ce3b0b3
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSImage.test.jsx
@@ -0,0 +1,146 @@
+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 image with no source and recent save", () => {
+ const img = mount(<DSImage isRecentSave={true} url="foo" title="bar" />);
+ img.setState({ isSeen: true });
+
+ img.update();
+
+ assert.equal(img.find("div").prop("className"), "placeholder-image");
+ });
+
+ it("should render a broken image with a source and a recent save", () => {
+ const img = mount(<DSImage isRecentSave={true} source="foo" />);
+ img.setState({ isSeen: true });
+
+ img.instance().onNonOptimizedImageError();
+ img.update();
+
+ assert.equal(img.find("div").prop("className"), "broken-image");
+ });
+
+ it("should render a broken image without a source and not a recent save", () => {
+ const img = mount(<DSImage isRecentSave={false} />);
+ 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..3aa128a32a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx
@@ -0,0 +1,151 @@
+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;
+
+ describe("DS link menu actions", () => {
+ beforeEach(() => {
+ wrapper = mount(<DSLinkMenu />);
+ });
+
+ afterEach(() => {
+ wrapper.unmount();
+ });
+
+ 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: {},
+ pocket_button_enabled: true,
+ };
+
+ 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, [
+ "CheckBookmark",
+ "CheckArchiveFromPocket",
+ "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, [
+ "CheckBookmark",
+ "CheckArchiveFromPocket",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "ShowPrivacyInfo",
+ ]);
+ });
+
+ it("should pass through the correct menu options to LinkMenu for save to Pocket button", () => {
+ wrapper = shallow(
+ <DSLinkMenu {...ValidDSLinkMenuProps} saveToPocketCard={true} />
+ );
+ wrapper
+ .find(ContextMenuButton)
+ .simulate("click", { preventDefault: () => {} });
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ assert.deepEqual(linkMenuProps.options, [
+ "CheckBookmark",
+ "CheckArchiveFromPocket",
+ "CheckDeleteFromPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ]);
+ });
+
+ it("should pass through the correct menu options to LinkMenu if Pocket is disabled", () => {
+ wrapper = shallow(
+ <DSLinkMenu {...ValidDSLinkMenuProps} pocket_button_enabled={false} />
+ );
+ wrapper
+ .find(ContextMenuButton)
+ .simulate("click", { preventDefault: () => {} });
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ assert.deepEqual(linkMenuProps.options, [
+ "CheckBookmark",
+ "CheckArchiveFromPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ]);
+ });
+ });
+});
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..7d9f13cc8a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx
@@ -0,0 +1,57 @@
+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..b4b743c7ff
--- /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.sys.mjs";
+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.DiscoveryStreamUserEvent({
+ 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..1888e194af
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx
@@ -0,0 +1,94 @@
+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,
+ isSponsoredTopSite: undefined,
+ },
+ ]);
+
+ assert.equal(secondCall.args[0].type, "DISCOVERY_STREAM_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/Highlights.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Highlights.test.jsx
new file mode 100644
index 0000000000..d8c16d8e71
--- /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.sys.mjs";
+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..1d4778e342
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx
@@ -0,0 +1,278 @@
+"use strict";
+
+import {
+ ImpressionStats,
+ INTERSECTION_RATIO,
+} from "content-src/components/DiscoveryStreamImpressionStats/ImpressionStats";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+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, type: "organic" },
+ { id: 2, pos: 1, type: "organic" },
+ { id: 3, pos: 2, type: "organic" },
+ ]);
+ });
+ 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,
+ rows: [{ id: 1, pos: 1, advertiser: "test advertiser" }],
+ source: "TOP_SITES",
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ // Loaded content + DISCOVERY_STREAM_SPOC_IMPRESSION + TOP_SITES_SPONSORED_IMPRESSION_STATS + impression
+ assert.callCount(dispatch, 4);
+
+ const [action] = dispatch.secondCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_SPOC_IMPRESSION);
+ assert.deepEqual(action.data, { flightId });
+ });
+ it("should send a TOP_SITES_SPONSORED_IMPRESSION_STATS when the wrapped item has a flightId", () => {
+ const dispatch = sinon.spy();
+ const flightId = "a_flight_id";
+ const props = {
+ dispatch,
+ flightId,
+ rows: [{ id: 1, pos: 1, advertiser: "test advertiser" }],
+ source: "TOP_SITES",
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ // Loaded content + DISCOVERY_STREAM_SPOC_IMPRESSION + TOP_SITES_SPONSORED_IMPRESSION_STATS + impression
+ assert.callCount(dispatch, 4);
+
+ const [action] = dispatch.getCall(2).args;
+ assert.equal(action.type, at.TOP_SITES_SPONSORED_IMPRESSION_STATS);
+ assert.deepEqual(action.data, {
+ type: "impression",
+ tile_id: 1,
+ source: "newtab",
+ advertiser: "test advertiser",
+ position: 1,
+ });
+ });
+ 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, type: "organic" },
+ { id: 2, pos: 1, type: "organic" },
+ { id: 3, pos: 2, type: "organic" },
+ ]);
+ });
+ 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/Navigation.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx
new file mode 100644
index 0000000000..ef5baf50c1
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx
@@ -0,0 +1,131 @@
+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={{}} locale="en-US" />);
+ });
+
+ 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);
+ });
+
+ it("should render 2 extra Topics", () => {
+ wrapper.setProps({
+ newFooterSection: true,
+ links: [
+ { url: "https://foo.com", name: "foo" },
+ { url: "https://bar.com", name: "bar" },
+ ],
+ extraLinks: [
+ { url: "https://foo.com", name: "foo" },
+ { url: "https://bar.com", name: "bar" },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find("ul").children(), 4);
+ });
+});
+
+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/PrivacyLink.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/PrivacyLink.test.jsx
new file mode 100644
index 0000000000..285cc16c0e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/PrivacyLink.test.jsx
@@ -0,0 +1,29 @@
+import { PrivacyLink } from "content-src/components/DiscoveryStreamComponents/PrivacyLink/PrivacyLink";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<PrivacyLink>", () => {
+ let wrapper;
+ let sandbox;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ wrapper = shallow(
+ <PrivacyLink
+ properties={{
+ url: "url",
+ title: "Privacy Link",
+ }}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-privacy-link").exists());
+ });
+});
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/TopicsWidget.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopicsWidget.test.jsx
new file mode 100644
index 0000000000..f879600a8f
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopicsWidget.test.jsx
@@ -0,0 +1,238 @@
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.sys.mjs";
+import { Provider } from "react-redux";
+import {
+ _TopicsWidget as TopicsWidgetBase,
+ TopicsWidget,
+} from "content-src/components/DiscoveryStreamComponents/TopicsWidget/TopicsWidget";
+import { SafeAnchor } from "content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { mount } from "enzyme";
+import React from "react";
+
+describe("Discovery Stream <TopicsWidget>", () => {
+ let sandbox;
+ let wrapper;
+ let dispatch;
+ let fakeWindow;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatch = sandbox.stub();
+ fakeWindow = {
+ innerWidth: 1000,
+ innerHeight: 900,
+ };
+
+ wrapper = mount(
+ <TopicsWidgetBase
+ dispatch={dispatch}
+ source="CARDGRID_WIDGET"
+ position={2}
+ id={1}
+ windowObj={fakeWindow}
+ DiscoveryStream={{
+ experimentData: {
+ utmCampaign: "utmCampaign",
+ utmContent: "utmContent",
+ utmSource: "utmSource",
+ },
+ }}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-topics-widget").exists());
+ });
+
+ it("should connect with DiscoveryStream store", () => {
+ let store = createStore(combineReducers(reducers), INITIAL_STATE);
+ wrapper = mount(
+ <Provider store={store}>
+ <TopicsWidget />
+ </Provider>
+ );
+
+ const topicsWidget = wrapper.find(TopicsWidgetBase);
+ assert.ok(topicsWidget.exists());
+ assert.lengthOf(topicsWidget, 1);
+ assert.deepEqual(
+ topicsWidget.props().DiscoveryStream.experimentData,
+ INITIAL_STATE.DiscoveryStream.experimentData
+ );
+ });
+
+ describe("dispatch", () => {
+ it("should dispatch loaded event", () => {
+ assert.callCount(dispatch, 1);
+ const [first] = dispatch.getCalls();
+ assert.calledWith(
+ first,
+ ac.DiscoveryStreamLoadedContent({
+ source: "CARDGRID_WIDGET",
+ tiles: [
+ {
+ id: 1,
+ pos: 2,
+ },
+ ],
+ })
+ );
+ });
+
+ it("should dispatch click event for technology", () => {
+ // Click technology topic.
+ wrapper.find(SafeAnchor).at(0).simulate("click");
+
+ // First call is DiscoveryStreamLoadedContent, which is already tested.
+ const [second, third, fourth] = dispatch.getCalls().slice(1, 4);
+
+ assert.callCount(dispatch, 4);
+ assert.calledWith(
+ second,
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: {
+ event: {
+ altKey: undefined,
+ button: undefined,
+ ctrlKey: undefined,
+ metaKey: undefined,
+ shiftKey: undefined,
+ },
+ referrer: "https://getpocket.com/recommendations",
+ url: "https://getpocket.com/explore/technology?utm_source=utmSource&utm_content=utmContent&utm_campaign=utmCampaign",
+ },
+ })
+ );
+ assert.calledWith(
+ third,
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "CARDGRID_WIDGET",
+ action_position: 2,
+ value: {
+ card_type: "topics_widget",
+ topic: "technology",
+ position_in_card: 0,
+ },
+ })
+ );
+ assert.calledWith(
+ fourth,
+ ac.ImpressionStats({
+ click: 0,
+ source: "CARDGRID_WIDGET",
+ tiles: [{ id: 1, pos: 2 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+
+ it("should dispatch click event for must reads", () => {
+ // Click must reads topic.
+ wrapper.find(SafeAnchor).at(8).simulate("click");
+
+ // First call is DiscoveryStreamLoadedContent, which is already tested.
+ const [second, third, fourth] = dispatch.getCalls().slice(1, 4);
+
+ assert.callCount(dispatch, 4);
+ assert.calledWith(
+ second,
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: {
+ event: {
+ altKey: undefined,
+ button: undefined,
+ ctrlKey: undefined,
+ metaKey: undefined,
+ shiftKey: undefined,
+ },
+ referrer: "https://getpocket.com/recommendations",
+ url: "https://getpocket.com/collections?utm_source=utmSource&utm_content=utmContent&utm_campaign=utmCampaign",
+ },
+ })
+ );
+ assert.calledWith(
+ third,
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "CARDGRID_WIDGET",
+ action_position: 2,
+ value: {
+ card_type: "topics_widget",
+ topic: "must-reads",
+ position_in_card: 8,
+ },
+ })
+ );
+ assert.calledWith(
+ fourth,
+ ac.ImpressionStats({
+ click: 0,
+ source: "CARDGRID_WIDGET",
+ tiles: [{ id: 1, pos: 2 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+
+ it("should dispatch click event for more topics", () => {
+ // Click more-topics.
+ wrapper.find(SafeAnchor).at(9).simulate("click");
+
+ // First call is DiscoveryStreamLoadedContent, which is already tested.
+ const [second, third, fourth] = dispatch.getCalls().slice(1, 4);
+
+ assert.callCount(dispatch, 4);
+ assert.calledWith(
+ second,
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: {
+ event: {
+ altKey: undefined,
+ button: undefined,
+ ctrlKey: undefined,
+ metaKey: undefined,
+ shiftKey: undefined,
+ },
+ referrer: "https://getpocket.com/recommendations",
+ url: "https://getpocket.com/?utm_source=utmSource&utm_content=utmContent&utm_campaign=utmCampaign",
+ },
+ })
+ );
+ assert.calledWith(
+ third,
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "CARDGRID_WIDGET",
+ action_position: 2,
+ value: { card_type: "topics_widget", topic: "more-topics" },
+ })
+ );
+ assert.calledWith(
+ fourth,
+ ac.ImpressionStats({
+ click: 0,
+ source: "CARDGRID_WIDGET",
+ tiles: [{ id: 1, pos: 2 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ })
+ );
+ });
+ });
+});
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..165f2a6dcf
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/FluentOrText.test.jsx
@@ -0,0 +1,68 @@
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import React from "react";
+import { shallow, mount } from "enzyme";
+
+describe("<FluentOrText>", () => {
+ it("should create span with no children", () => {
+ const wrapper = shallow(<FluentOrText />);
+
+ assert.ok(wrapper.find("span").exists());
+ });
+ 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']").exists());
+ });
+ it("should also allow string_id", () => {
+ const wrapper = shallow(<FluentOrText message={{ string_id: "fluent" }} />);
+
+ assert.ok(wrapper.find("span[data-l10n-id='fluent']").exists());
+ });
+ 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']").exists());
+ });
+ it("should set args for fluent", () => {
+ const wrapper = mount(<FluentOrText message={{ args: { num: 5 } }} />);
+ const { attributes } = wrapper.getDOMNode();
+ const args = attributes.getNamedItem("data-l10n-args").value;
+ assert.equal(JSON.parse(args).num, 5);
+ });
+ it("should also allow values", () => {
+ const wrapper = mount(<FluentOrText message={{ values: { num: 5 } }} />);
+ const { attributes } = wrapper.getDOMNode();
+ const args = attributes.getNamedItem("data-l10n-args").value;
+ assert.equal(JSON.parse(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']").exists());
+ });
+ 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/HelpText.test.jsx b/browser/components/newtab/test/unit/content-src/components/HelpText.test.jsx
new file mode 100644
index 0000000000..e2cf4f1f21
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/HelpText.test.jsx
@@ -0,0 +1,41 @@
+import { HelpText } from "content-src/aboutwelcome/components/HelpText";
+import { Localized } from "content-src/aboutwelcome/components/MSLocalized";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<HelpText>", () => {
+ it("should render text inside Localized", () => {
+ const shallowWrapper = shallow(<HelpText text="test" />);
+
+ assert.equal(shallowWrapper.find(Localized).props().text, "test");
+ });
+ it("should render the img if there is an img and a string_id", () => {
+ const shallowWrapper = shallow(
+ <HelpText
+ text={{ string_id: "test_id" }}
+ hasImg={{
+ src: "chrome://activity-stream/content/data/content/assets/cfr_fb_container.png",
+ }}
+ />
+ );
+ assert.ok(
+ shallowWrapper
+ .find(Localized)
+ .findWhere(n => n.text.string_id === "test_id")
+ );
+ assert.lengthOf(shallowWrapper.find("p.helptext"), 1);
+ assert.lengthOf(shallowWrapper.find("img[data-l10n-name='help-img']"), 1);
+ });
+ it("should render the img if there is an img and plain text", () => {
+ const shallowWrapper = shallow(
+ <HelpText
+ text={"Sample help text"}
+ hasImg={{
+ src: "chrome://activity-stream/content/data/content/assets/cfr_fb_container.png",
+ }}
+ />
+ );
+ assert.equal(shallowWrapper.find("p.helptext").text(), "Sample help text");
+ assert.lengthOf(shallowWrapper.find("img.helptext-img"), 1);
+ });
+});
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..8aa74a3a46
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx
@@ -0,0 +1,582 @@
+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 Archive from Pocket option for a saved Pocket item if CheckArchiveFromPocket", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", pocket_id: 1234 }}
+ source={"TOP_STORIES"}
+ options={["CheckArchiveFromPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-archive-pocket")
+ );
+ });
+ it("should show empty from no Pocket option for no saved Pocket item if CheckArchiveFromPocket", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "" }}
+ source={"TOP_STORIES"}
+ options={["CheckArchiveFromPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isUndefined(
+ options.find(o => o.id && o.id === "newtab-menu-archive-pocket")
+ );
+ });
+ it("should show Delete from Pocket option for a saved Pocket item if CheckDeleteFromPocket", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", pocket_id: 1234 }}
+ source={"TOP_STORIES"}
+ options={["CheckDeleteFromPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-delete-pocket")
+ );
+ });
+ it("should show empty from Pocket option for no saved Pocket item if CheckDeleteFromPocket", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "" }}
+ source={"TOP_STORIES"}
+ options={["CheckDeleteFromPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isUndefined(
+ options.find(o => o.id && o.id === "newtab-menu-archive-pocket")
+ );
+ });
+ 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",
+ sponsored_tile_id: 12345,
+ };
+ 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,
+ sponsored_tile_id: FAKE_SITE.sponsored_tile_id,
+ },
+ "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,
+ isSponsoredTopSite: undefined,
+ },
+ ],
+ 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..d46f794513
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx
@@ -0,0 +1,48 @@
+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").exists());
+ 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']").exists());
+ });
+ 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']").exists());
+ });
+ 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']").exists());
+ });
+});
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..31a5e7be4d
--- /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.sys.mjs";
+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..54a3b611cc
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Search.test.jsx
@@ -0,0 +1,179 @@
+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: { featureConfig: {} } },
+};
+
+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: "DISABLE_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: "DISABLE_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/Sections.test.jsx b/browser/components/newtab/test/unit/content-src/components/Sections.test.jsx
new file mode 100644
index 0000000000..9f4008369a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Sections.test.jsx
@@ -0,0 +1,600 @@
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.sys.mjs";
+import {
+ Section,
+ SectionIntl,
+ _Sections as Sections,
+} from "content-src/components/Sections/Sections";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+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 { 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("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",
+ },
+ });
+ 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",
+ },
+ });
+ wrapper = shallow(<Section {...FAKE_SECTION} />);
+ assert.isFalse(wrapper.find(".empty-state").exists());
+ });
+ it("no icon should be shown", () => {
+ assert.lengthOf(wrapper.find(".icon"), 0);
+ });
+ });
+
+ 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..4009909c81
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx
@@ -0,0 +1,1919 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+import { MIN_RICH_FAVICON_SIZE } from "content-src/components/TopSites/TopSitesConstants";
+import {
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "common/Reducers.sys.mjs";
+import {
+ TopSite,
+ TopSiteLink,
+ _TopSiteList as TopSiteList,
+ TopSitePlaceholder,
+} from "content-src/components/TopSites/TopSite";
+import {
+ INTERSECTION_RATIO,
+ TopSiteImpressionWrapper,
+} from "content-src/components/TopSites/TopSiteImpressionWrapper";
+import { A11yLinkButton } from "content-src/components/A11yLinkButton/A11yLinkButton";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import React from "react";
+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";
+
+const perfSvc = {
+ mark() {},
+ getMostRecentAbsMarkStartByName() {},
+};
+
+const DEFAULT_PROPS = {
+ Prefs: { values: { featureConfig: {} } },
+ 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("#_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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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 icons", () => {
+ const wrapper = shallow(<TopSiteLink link={link} title={"foo"} />);
+ assert.equal(wrapper.find(".icon-wrapper").prop("data-fallback"), "f");
+ });
+ 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.lengthOf(wrapper.find(".default-icon"), 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("#_allowDrop", () => {
+ let wrapper;
+ let event;
+ beforeEach(() => {
+ event = {
+ dataTransfer: {
+ types: ["text/topsite-index"],
+ },
+ };
+ wrapper = shallow(
+ <TopSiteLink isDraggable={true} onDragEvent={() => {}} />
+ );
+ });
+ it("should be droppable for basic case", () => {
+ const result = wrapper.instance()._allowDrop(event);
+ assert.isTrue(result);
+ });
+ it("should not be droppable for sponsored_position", () => {
+ wrapper.setProps({ link: { sponsored_position: 1 } });
+ const result = wrapper.instance()._allowDrop(event);
+ assert.isFalse(result);
+ });
+ it("should not be droppable for link.type", () => {
+ wrapper.setProps({ link: { type: "SPOC" } });
+ const result = wrapper.instance()._allowDrop(event);
+ assert.isFalse(result);
+ });
+ });
+ 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);
+ });
+ it("should prevent dragging with sponsored_position from dragstart", () => {
+ const preventDefault = sinon.stub();
+ const blur = sinon.stub();
+ wrapper.setProps({ link: { sponsored_position: 1 } });
+ wrapper.instance().onDragEvent({
+ type: "dragstart",
+ preventDefault,
+ target: { blur },
+ });
+ assert.calledOnce(preventDefault);
+ assert.calledOnce(blur);
+ assert.isUndefined(wrapper.instance().dragged);
+ });
+ it("should prevent dragging with link.shim from dragstart", () => {
+ const preventDefault = sinon.stub();
+ const blur = sinon.stub();
+ wrapper.setProps({ link: { type: "SPOC" } });
+ wrapper.instance().onDragEvent({
+ type: "dragstart",
+ preventDefault,
+ target: { blur },
+ });
+ assert.calledOnce(preventDefault);
+ assert.calledOnce(blur);
+ assert.isUndefined(wrapper.instance().dragged);
+ });
+ });
+
+ 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 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 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 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" };
+ });
+
+ // 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() {}
+ };
+ }
+
+ 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",
+ ]);
+ });
+ it("should record impressions for visible organic Top Sites", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <TopSite
+ link={link}
+ index={3}
+ dispatch={dispatch}
+ IntersectionObserver={buildIntersectionObserver([
+ {
+ isIntersecting: true,
+ intersectionRatio: INTERSECTION_RATIO,
+ },
+ ])}
+ document={{
+ visibilityState: "visible",
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ }}
+ />
+ );
+ const linkWrapper = wrapper.find(TopSiteLink).dive();
+ assert.ok(linkWrapper.exists());
+ const impressionWrapper = linkWrapper.find(TopSiteImpressionWrapper).dive();
+ assert.ok(impressionWrapper.exists());
+
+ assert.calledOnce(dispatch);
+
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.TOP_SITES_ORGANIC_IMPRESSION_STATS);
+
+ assert.propertyVal(action.data, "type", "impression");
+ assert.propertyVal(action.data, "source", "newtab");
+ assert.propertyVal(action.data, "position", 3);
+ });
+ it("should record impressions for visible sponsored Top Sites", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, {
+ sponsored_position: 2,
+ sponsored_tile_id: 12345,
+ sponsored_impression_url: "http://impression.example.com/",
+ })}
+ index={3}
+ dispatch={dispatch}
+ IntersectionObserver={buildIntersectionObserver([
+ {
+ isIntersecting: true,
+ intersectionRatio: INTERSECTION_RATIO,
+ },
+ ])}
+ document={{
+ visibilityState: "visible",
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ }}
+ />
+ );
+ const linkWrapper = wrapper.find(TopSiteLink).dive();
+ assert.ok(linkWrapper.exists());
+ const impressionWrapper = linkWrapper.find(TopSiteImpressionWrapper).dive();
+ assert.ok(impressionWrapper.exists());
+
+ assert.calledOnce(dispatch);
+
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.TOP_SITES_SPONSORED_IMPRESSION_STATS);
+
+ assert.propertyVal(action.data, "type", "impression");
+ assert.propertyVal(action.data, "tile_id", 12345);
+ assert.propertyVal(action.data, "source", "newtab");
+ assert.propertyVal(action.data, "position", 3);
+ assert.propertyVal(
+ action.data,
+ "reporting_url",
+ "http://impression.example.com/"
+ );
+ assert.propertyVal(action.data, "advertiser", "foo");
+ });
+
+ 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() {} });
+
+ let [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);
+
+ [action] = dispatch.secondCall.args;
+ assert.propertyVal(action, "type", at.OPEN_LINK);
+
+ // Organic Top Site click event.
+ [action] = dispatch.thirdCall.args;
+ assert.equal(action.type, at.TOP_SITES_ORGANIC_IMPRESSION_STATS);
+
+ assert.propertyVal(action.data, "type", "click");
+ assert.propertyVal(action.data, "source", "newtab");
+ assert.propertyVal(action.data, "position", 3);
+ });
+ 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 = {
+ id: 1,
+ iconType: "custom_screenshot",
+ type: "SPOC",
+ pos: 1,
+ label: "test advertiser",
+ };
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, siteInfo)}
+ index={0}
+ dispatch={dispatch}
+ />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ let [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");
+
+ // Pocket SPOC click event.
+ [action] = dispatch.getCall(2).args;
+ assert.equal(action.type, at.TELEMETRY_IMPRESSION_STATS);
+
+ assert.propertyVal(action.data, "click", 0);
+ assert.propertyVal(action.data, "source", "TOP_SITES");
+
+ // Topsite SPOC click event.
+ [action] = dispatch.getCall(3).args;
+ assert.equal(action.type, at.TOP_SITES_SPONSORED_IMPRESSION_STATS);
+
+ assert.propertyVal(action.data, "type", "click");
+ assert.propertyVal(action.data, "tile_id", 1);
+ assert.propertyVal(action.data, "source", "newtab");
+ assert.propertyVal(action.data, "position", 1);
+ assert.propertyVal(action.data, "advertiser", "test advertiser");
+ });
+ 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 an icon for tippyTop sites", () => {
+ wrapper.setProps({ site: { tippyTopIcon: "bar" } });
+
+ assert.equal(
+ wrapper.find(".top-site-icon").getDOMNode().style["background-image"],
+ 'url("bar")'
+ );
+ });
+
+ it("should not display a preview screenshot", () => {
+ wrapper.setProps({ previewResponse: "foo", previewUrl: "foo" });
+
+ assert.lengthOf(wrapper.find(".screenshot"), 0);
+ });
+
+ 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-shortcut-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-shortcut-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>", () => {
+ const APP = { isForStartupCache: false };
+
+ it("should render a TopSiteList element", () => {
+ const wrapper = shallow(<TopSiteList {...DEFAULT_PROPS} App={{ APP }} />);
+ 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 }} App={{ APP }} />
+ );
+ 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}
+ App={{ APP }}
+ />
+ );
+ 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}
+ App={{ APP }}
+ />
+ );
+ assert.lengthOf(wrapper.find(TopSite), 2, "topSites");
+ assert.lengthOf(
+ wrapper.find(TopSitePlaceholder),
+ TOP_SITES_MAX_SITES_PER_ROW - 2,
+ "placeholders"
+ );
+ });
+ it("should fill sponsored top sites with placeholders while rendering for startup cache", () => {
+ const rows = [
+ { url: "https://sponsored01.com", sponsored_position: 1 },
+ { url: "https://sponsored02.com", sponsored_position: 2 },
+ { url: "https://sponsored03.com", type: "SPOC" },
+ { url: "https://foo.com" },
+ { url: "https://bar.com" },
+ ];
+ const wrapper = shallow(
+ <TopSiteList
+ {...DEFAULT_PROPS}
+ TopSites={{ rows }}
+ TopSitesRows={1}
+ App={{ isForStartupCache: true }}
+ />
+ );
+ 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}
+ App={{ APP }}
+ />
+ );
+ 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} App={{ APP }} />);
+ 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 }} App={{ APP }} />
+ );
+ 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} App={{ APP }} />
+ );
+ 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} App={{ APP }} />);
+ 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}
+ App={{ APP }}
+ />
+ );
+ 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,
+ ]);
+ site2.type = "SPOC";
+ instance.setState({
+ draggedIndex: 2,
+ draggedSite: site3,
+ draggedTitle: "baz",
+ });
+ draggedSite = Object.assign({}, site3, { isPinned: true, isDragged: true });
+ assert.deepEqual(instance._makeTopSitesPreview(0), [
+ draggedSite,
+ site2,
+ site1,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ site2.type = "";
+ site2.sponsored_position = 2;
+ instance.setState({
+ draggedIndex: 2,
+ draggedSite: site3,
+ draggedTitle: "baz",
+ });
+ draggedSite = Object.assign({}, site3, { isPinned: true, isDragged: true });
+ assert.deepEqual(instance._makeTopSitesPreview(0), [
+ draggedSite,
+ site2,
+ site1,
+ 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}
+ App={{ APP }}
+ />
+ );
+ 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..22c4e8192a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx
@@ -0,0 +1,56 @@
+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/TopSites/TopSiteImpressionWrapper.test.jsx b/browser/components/newtab/test/unit/content-src/components/TopSites/TopSiteImpressionWrapper.test.jsx
new file mode 100644
index 0000000000..79cb6ec7c5
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites/TopSiteImpressionWrapper.test.jsx
@@ -0,0 +1,150 @@
+"use strict";
+
+import {
+ TopSiteImpressionWrapper,
+ INTERSECTION_RATIO,
+} from "content-src/components/TopSites/TopSiteImpressionWrapper";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<TopSiteImpressionWrapper>", () => {
+ 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 = {
+ actionType: at.TOP_SITES_SPONSORED_IMPRESSION_STATS,
+ tile: {
+ tile_id: 1,
+ position: 1,
+ reporting_url: "https://test.reporting.com",
+ advertiser: "test_advertiser",
+ },
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ document: {
+ visibilityState: "visible",
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ },
+ };
+
+ const InnerEl = () => <div>Inner Element</div>;
+
+ function renderTopSiteImpressionWrapper(props = {}) {
+ return shallow(
+ <TopSiteImpressionWrapper {...DEFAULT_PROPS} {...props}>
+ <InnerEl />
+ </TopSiteImpressionWrapper>
+ );
+ }
+
+ it("should render props.children", () => {
+ const wrapper = renderTopSiteImpressionWrapper();
+ assert.ok(wrapper.contains(<InnerEl />));
+ });
+ 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),
+ };
+ renderTopSiteImpressionWrapper(props);
+
+ assert.notCalled(dispatch);
+ });
+ it("should send 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),
+ };
+ renderTopSiteImpressionWrapper(props);
+
+ assert.calledOnce(dispatch);
+
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.TOP_SITES_SPONSORED_IMPRESSION_STATS);
+ assert.deepEqual(action.data, {
+ type: "impression",
+ ...DEFAULT_PROPS.tile,
+ });
+ });
+ 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 = renderTopSiteImpressionWrapper(props);
+
+ assert.notCalled(dispatch);
+
+ dispatch.resetHistory();
+ wrapper.instance().impressionObserver.callback(FullIntersectEntries);
+
+ // For the impression
+ assert.calledOnce(dispatch);
+
+ const [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.TOP_SITES_SPONSORED_IMPRESSION_STATS);
+ assert.deepEqual(action.data, {
+ type: "impression",
+ ...DEFAULT_PROPS.tile,
+ });
+ });
+ 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 = renderTopSiteImpressionWrapper(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 = renderTopSiteImpressionWrapper(props);
+ wrapper.unmount();
+
+ assert.calledOnce(spy);
+ });
+});
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..953fc60d79
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/addUtmParams.test.js
@@ -0,0 +1,35 @@
+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");
+ });
+ it("should not override the URL's existing utm param values", () => {
+ const url = new URL("https://foo.com/?utm_source=foo&utm_campaign=bar");
+ const params = addUtmParams(url, "foo").searchParams;
+ assert.equal(params.get("utm_source"), "foo", "utm_source");
+ assert.equal(params.get("utm_campaign"), "bar", "utm_campaign");
+ assert.equal(params.get("utm_medium"), "referral", "utm_medium");
+ });
+});
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..5a7fad7cc0
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js
@@ -0,0 +1,120 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..5ce92d2192
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/init-store.test.js
@@ -0,0 +1,207 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..233f31b6ca
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/selectLayoutRender.test.js
@@ -0,0 +1,576 @@
+import { combineReducers, createStore } from "redux";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+import { reducers } from "common/Reducers.sys.mjs";
+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 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..f355c6f0ab
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/AboutPreferences.test.js
@@ -0,0 +1,429 @@
+/* global Services */
+import {
+ AboutPreferences,
+ PREFERENCES_LOADED_EVENT,
+} from "lib/AboutPreferences.jsm";
+import {
+ actionTypes as at,
+ actionCreators as ac,
+} from "common/Actions.sys.mjs";
+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 }),
+ };
+ globals.set("NimbusFeatures", {
+ newtab: { getAllVariables: sandbox.stub() },
+ });
+ });
+ 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: "mail", pref: { feed: "feed" } }];
+
+ testRender();
+
+ assert.calledWith(
+ node.setAttribute,
+ "src",
+ "chrome://activity-stream/content/data/content/assets/glyph-mail-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..47880d00bc
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStream.test.js
@@ -0,0 +1,576 @@
+import { CONTENT_MESSAGE_TYPE } from "common/Actions.sys.mjs";
+import { ActivityStream, PREFS_CONFIG } from "lib/ActivityStream.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+import { DEFAULT_SITES } from "lib/DefaultSites.sys.mjs";
+import { AboutPreferences } from "lib/AboutPreferences.jsm";
+import { DefaultPrefs } from "lib/ActivityStreamPrefs.jsm";
+import { NewTabInit } from "lib/NewTabInit.jsm";
+import { SectionsFeed } from "lib/SectionsManager.jsm";
+import { RecommendationProvider } from "lib/RecommendationProvider.jsm";
+import { PlacesFeed } from "lib/PlacesFeed.jsm";
+import { PrefsFeed } from "lib/PrefsFeed.jsm";
+import { SystemTickFeed } from "lib/SystemTickFeed.jsm";
+import { TelemetryFeed } from "lib/TelemetryFeed.jsm";
+import { FaviconFeed } from "lib/FaviconFeed.jsm";
+import { TopSitesFeed } from "lib/TopSitesFeed.jsm";
+import { TopStoriesFeed } from "lib/TopStoriesFeed.jsm";
+import { HighlightsFeed } from "lib/HighlightsFeed.jsm";
+import { DiscoveryStreamFeed } from "lib/DiscoveryStreamFeed.jsm";
+
+import { LinksCache } from "lib/LinksCache.sys.mjs";
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+import { DownloadsManager } from "lib/DownloadsManager.jsm";
+
+describe("ActivityStream", () => {
+ let sandbox;
+ let as;
+ function FakeStore() {
+ return { init: () => {}, uninit: () => {}, feeds: { get: () => {} } };
+ }
+
+ let globals;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set({
+ Store: FakeStore,
+
+ DEFAULT_SITES,
+ AboutPreferences,
+ DefaultPrefs,
+ NewTabInit,
+ SectionsFeed,
+ RecommendationProvider,
+ PlacesFeed,
+ PrefsFeed,
+ SystemTickFeed,
+ TelemetryFeed,
+ FaviconFeed,
+ TopSitesFeed,
+ TopStoriesFeed,
+ HighlightsFeed,
+ DiscoveryStreamFeed,
+
+ LinksCache,
+ PersistentCache,
+ DownloadsManager,
+ });
+
+ as = new ActivityStream();
+ 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();
+ globals.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"
+ );
+ });
+ it("should call addObserver for the app locales", () => {
+ sandbox.stub(global.Services.obs, "addObserver");
+ as.init();
+ assert.calledWith(
+ global.Services.obs.addObserver,
+ as,
+ "intl:app-locales-changed"
+ );
+ });
+ });
+ 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 for the region", () => {
+ sandbox.stub(global.Services.obs, "removeObserver");
+ as.geo = "";
+ as.uninit();
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ as,
+ global.Region.REGION_TOPIC
+ );
+ });
+ it("should call removeObserver for the app locales", () => {
+ sandbox.stub(global.Services.obs, "removeObserver");
+ as.uninit();
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ as,
+ "intl:app-locales-changed"
+ );
+ });
+ });
+ describe("#observe", () => {
+ it("should call _updateDynamicPrefs from observe", () => {
+ sandbox.stub(as, "_updateDynamicPrefs");
+ as.observe(undefined, global.Region.REGION_TOPIC);
+ 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 RecommendationProvider feed", () => {
+ const feed = as.feeds.get("feeds.recommendationprovider")();
+ 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 getVariableStub;
+ let getBoolPrefStub;
+ let appLocaleAsBCP47Stub;
+ beforeEach(() => {
+ getVariableStub = sandbox.stub(
+ global.NimbusFeatures.pocketNewtab,
+ "getVariable"
+ );
+ 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");
+
+ getVariableStub.withArgs("regionStoriesConfig").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");
+ getVariableStub
+ .withArgs("localeListConfig")
+ .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");
+ getVariableStub.withArgs("regionStoriesConfig").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");
+ getVariableStub.withArgs("localeListConfig").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("US", "browser-region-updated");
+ });
+ });
+ });
+ 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.NimbusFeatures.pocketNewtab, "getVariable")
+ .withArgs("regionStoriesConfig")
+ .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..b6aeacead2
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js
@@ -0,0 +1,432 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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",
+];
+
+// Create an object containing details about a tab as expected within
+// the loaded tabs map in ActivityStreamMessageChannel.jsm.
+function getTabDetails(portID, url = "about:newtab", extraArgs = {}) {
+ let actor = {
+ portID,
+ sendAsyncMessage: sinon.spy(),
+ };
+ let browser = {
+ getAttribute: () => (extraArgs.preloaded ? "preloaded" : ""),
+ ownerGlobal: {},
+ };
+ let browsingContext = {
+ top: {
+ embedderElement: browser,
+ },
+ };
+
+ let data = {
+ data: {
+ actor,
+ browser,
+ browsingContext,
+ portID,
+ url,
+ },
+ target: {
+ browsingContext,
+ },
+ };
+
+ if (extraArgs.loaded) {
+ data.data.loaded = extraArgs.loaded;
+ }
+ if (extraArgs.simulated) {
+ data.data.simulated = extraArgs.simulated;
+ }
+
+ return data;
+}
+
+describe("ActivityStreamMessageChannel", () => {
+ let globals;
+ let dispatch;
+ let mm;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set("AboutNewTab", {
+ reset: globals.sandbox.spy(),
+ });
+ globals.set("AboutHomeStartupCache", { onPreloadedNewTabMessage() {} });
+ dispatch = globals.sandbox.spy();
+ mm = new ActivityStreamMessageChannel({ dispatch });
+
+ assert.ok(mm.loadedTabs, []);
+
+ let loadedTabs = new Map();
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(mm, "loadedTabs").get(() => loadedTabs);
+ });
+
+ afterEach(() => globals.restore());
+
+ describe("portID validation", () => {
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sandbox.spy(global.console, "error");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should log errors for an invalid portID", () => {
+ mm.validatePortID({});
+ mm.validatePortID({});
+ mm.validatePortID({});
+
+ assert.equal(global.console.error.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("#simulateMessagesForExistingTabs", () => {
+ beforeEach(() => {
+ sinon.stub(mm, "onActionFromContent");
+ });
+ it("should simulate init for existing ports", () => {
+ let msg1 = getTabDetails("inited", "about:monkeys", {
+ simulated: true,
+ });
+ mm.loadedTabs.set(msg1.data.browser, msg1.data);
+
+ let msg2 = getTabDetails("loaded", "about:sheep", {
+ simulated: true,
+ });
+ mm.loadedTabs.set(msg2.data.browser, msg2.data);
+
+ mm.simulateMessagesForExistingTabs();
+
+ assert.calledWith(mm.onActionFromContent.firstCall, {
+ type: at.NEW_TAB_INIT,
+ data: msg1.data,
+ });
+ assert.calledWith(mm.onActionFromContent.secondCall, {
+ type: at.NEW_TAB_INIT,
+ data: msg2.data,
+ });
+ });
+ it("should simulate load for loaded ports", () => {
+ let msg3 = getTabDetails("foo", null, {
+ preloaded: true,
+ loaded: true,
+ });
+ mm.loadedTabs.set(msg3.data.browser, msg3.data);
+
+ mm.simulateMessagesForExistingTabs();
+
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_LOAD },
+ "foo"
+ );
+ });
+ it("should set renderLayers on preloaded browsers after load", () => {
+ let msg4 = getTabDetails("foo", null, {
+ preloaded: true,
+ loaded: true,
+ });
+ msg4.data.browser.ownerGlobal = {
+ STATE_MAXIMIZED: 1,
+ STATE_MINIMIZED: 2,
+ STATE_NORMAL: 3,
+ STATE_FULLSCREEN: 4,
+ windowState: 3,
+ isFullyOccluded: false,
+ };
+ mm.loadedTabs.set(msg4.data.browser, msg4.data);
+ mm.simulateMessagesForExistingTabs();
+ assert.equal(msg4.data.browser.renderLayers, true);
+ });
+ });
+ });
+ describe("Message handling", () => {
+ describe("#getTargetById", () => {
+ it("should get an id if it exists", () => {
+ let msg = getTabDetails("foo:1");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ assert.equal(mm.getTargetById("foo:1"), msg.data.actor);
+ });
+ it("should return null if the target doesn't exist", () => {
+ let msg = getTabDetails("foo:2");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ assert.equal(mm.getTargetById("bar:3"), null);
+ });
+ });
+ describe("#getPreloadedActors", () => {
+ it("should get a preloaded actor if it exists", () => {
+ let msg = getTabDetails("foo:3", null, { preloaded: true });
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ assert.equal(mm.getPreloadedActors()[0].portID, "foo:3");
+ });
+ it("should get all the preloaded actors across windows if they exist", () => {
+ let msg = getTabDetails("foo:4a", null, { preloaded: true });
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ msg = getTabDetails("foo:4b", null, { preloaded: true });
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ assert.equal(mm.getPreloadedActors().length, 2);
+ });
+ it("should return null if there is no preloaded actor", () => {
+ let msg = getTabDetails("foo:5");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ assert.equal(mm.getPreloadedActors(), null);
+ });
+ });
+ describe("#onNewTabInit", () => {
+ it("should dispatch a NEW_TAB_INIT action", () => {
+ let msg = getTabDetails("foo", "about:monkeys");
+ sinon.stub(mm, "onActionFromContent");
+
+ mm.onNewTabInit(msg, msg.data);
+
+ assert.calledWith(mm.onActionFromContent, {
+ type: at.NEW_TAB_INIT,
+ data: msg.data,
+ });
+ });
+ });
+ describe("#onNewTabLoad", () => {
+ it("should dispatch a NEW_TAB_LOAD action", () => {
+ let msg = getTabDetails("foo", null, { preloaded: true });
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ sinon.stub(mm, "onActionFromContent");
+ mm.onNewTabLoad({ target: msg.target }, msg.data);
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_LOAD },
+ "foo"
+ );
+ });
+ });
+ describe("#onNewTabUnload", () => {
+ it("should dispatch a NEW_TAB_UNLOAD action", () => {
+ let msg = getTabDetails("foo");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ sinon.stub(mm, "onActionFromContent");
+ mm.onNewTabUnload({ target: msg.target }, msg.data);
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_UNLOAD },
+ "foo"
+ );
+ });
+ });
+ describe("#onMessage", () => {
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sandbox.spy(global.console, "error");
+ });
+ afterEach(() => sandbox.restore());
+ it("return early when tab details are not present", () => {
+ let msg = getTabDetails("foo");
+ sinon.stub(mm, "onActionFromContent");
+ mm.onMessage(msg, msg.data);
+ assert.notCalled(mm.onActionFromContent);
+ });
+ it("should report an error if the msg.data is missing", () => {
+ let msg = getTabDetails("foo");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ let tabDetails = msg.data;
+ delete msg.data;
+ mm.onMessage(msg, tabDetails);
+ assert.calledOnce(global.console.error);
+ });
+ it("should report an error if the msg.data.type is missing", () => {
+ let msg = getTabDetails("foo");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ msg.data = "foo";
+ mm.onMessage(msg, msg.data);
+ assert.calledOnce(global.console.error);
+ });
+ it("should call onActionFromContent", () => {
+ sinon.stub(mm, "onActionFromContent");
+ let msg = getTabDetails("foo");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ let action = {
+ data: { data: {}, type: "FOO" },
+ target: msg.target,
+ };
+ const expectedAction = {
+ type: action.data.type,
+ data: action.data.data,
+ _target: { browser: msg.data.browser },
+ };
+ mm.onMessage(action, msg.data);
+ assert.calledWith(mm.onActionFromContent, expectedAction, "foo");
+ });
+ });
+ });
+ describe("Sending and broadcasting", () => {
+ describe("#send", () => {
+ it("should send a message on the right port", () => {
+ let msg = getTabDetails("foo:6");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ const action = ac.AlsoToOneContent({ type: "HELLO" }, "foo:6");
+ mm.send(action);
+ assert.calledWith(
+ msg.data.actor.sendAsyncMessage,
+ DEFAULT_OPTIONS.outgoingMessageName,
+ action
+ );
+ });
+ it("should not throw if the target isn't around", () => {
+ // port is not added to the channel
+ const action = ac.AlsoToOneContent({ type: "HELLO" }, "foo:7");
+
+ assert.doesNotThrow(() => mm.send(action));
+ });
+ });
+ describe("#broadcast", () => {
+ it("should send a message on the channel", () => {
+ let msg = getTabDetails("foo:8");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ const action = ac.BroadcastToContent({ type: "HELLO" });
+ mm.broadcast(action);
+ assert.calledWith(
+ msg.data.actor.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", () => {
+ let msg = getTabDetails("foo:9", null, { preloaded: true });
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ const action = ac.AlsoToPreloaded({ type: "HELLO", data: 10 });
+ mm.sendToPreloaded(action);
+ assert.calledWith(
+ msg.data.actor.sendAsyncMessage,
+ DEFAULT_OPTIONS.outgoingMessageName,
+ action
+ );
+ });
+ it("should send the message to all the preloaded browsers if there's data and they exist", () => {
+ let msg1 = getTabDetails("foo:10a", null, { preloaded: true });
+ mm.loadedTabs.set(msg1.data.browser, msg1.data);
+
+ let msg2 = getTabDetails("foo:10b", null, { preloaded: true });
+ mm.loadedTabs.set(msg2.data.browser, msg2.data);
+
+ mm.sendToPreloaded(ac.AlsoToPreloaded({ type: "HELLO", data: 10 }));
+ assert.calledOnce(msg1.data.actor.sendAsyncMessage);
+ assert.calledOnce(msg2.data.actor.sendAsyncMessage);
+ });
+ it("should not send the message to the preloaded browser if there's no data and a preloaded browser does not exists", () => {
+ let msg = getTabDetails("foo:11");
+ mm.loadedTabs.set(msg.data.browser, msg.data);
+ const action = ac.AlsoToPreloaded({ type: "HELLO" });
+ mm.sendToPreloaded(action);
+ assert.notCalled(msg.data.actor.sendAsyncMessage);
+ });
+ });
+ });
+ describe("Handling actions", () => {
+ describe("#onActionFromContent", () => {
+ beforeEach(() => mm.onActionFromContent({ type: "FOO" }, "foo:12"));
+ 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:12", "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");
+
+ 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");
+
+ 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" });
+
+ 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" });
+
+ 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");
+
+ 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..ebc9726def
--- /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.set("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/DiscoveryStreamFeed.test.js b/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js
new file mode 100644
index 0000000000..e91b7fc549
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js
@@ -0,0 +1,3581 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.sys.mjs";
+import { combineReducers, createStore } from "redux";
+import { GlobalOverrider } from "test/unit/utils";
+import { DiscoveryStreamFeed } from "lib/DiscoveryStreamFeed.jsm";
+import { RecommendationProvider } from "lib/RecommendationProvider.jsm";
+import { reducers } from "common/Reducers.sys.mjs";
+
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+import { PersonalityProvider } from "lib/PersonalityProvider/PersonalityProvider.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 recommendationProvider;
+ let sandbox;
+ let fetchStub;
+ let clock;
+ let fakeNewTabUtils;
+ let fakePktApi;
+ 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 },
+ PersistentCache,
+ PersonalityProvider,
+ });
+
+ sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .withArgs("browser.newtabpage.activity-stream.discoverystream.enabled")
+ .returns(true);
+
+ recommendationProvider = new RecommendationProvider();
+ recommendationProvider.store = createStore(combineReducers(reducers), {});
+ feeds = {
+ "feeds.recommendationprovider": recommendationProvider,
+ };
+
+ // 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);
+
+ fakePktApi = {
+ isUserLoggedIn: () => false,
+ getRecentSavesCache: () => null,
+ getRecentSaves: () => null,
+ };
+ globals.set("pktApi", fakePktApi);
+ });
+
+ 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("#setupPocketState", () => {
+ it("should setup logged in state and recent saves with cache", async () => {
+ fakePktApi.isUserLoggedIn = () => true;
+ fakePktApi.getRecentSavesCache = () => [1, 2, 3];
+ sandbox.spy(feed.store, "dispatch");
+ await feed.setupPocketState({});
+ assert.calledTwice(feed.store.dispatch);
+ assert.calledWith(
+ feed.store.dispatch.firstCall,
+ ac.OnlyToOneContent(
+ {
+ type: at.DISCOVERY_STREAM_POCKET_STATE_SET,
+ data: { isUserLoggedIn: true },
+ },
+ {}
+ )
+ );
+ assert.calledWith(
+ feed.store.dispatch.secondCall,
+ ac.OnlyToOneContent(
+ {
+ type: at.DISCOVERY_STREAM_RECENT_SAVES,
+ data: { recentSaves: [1, 2, 3] },
+ },
+ {}
+ )
+ );
+ });
+ it("should setup logged in state and recent saves without cache", async () => {
+ fakePktApi.isUserLoggedIn = () => true;
+ fakePktApi.getRecentSaves = ({ success }) => success([1, 2, 3]);
+ sandbox.spy(feed.store, "dispatch");
+ await feed.setupPocketState({});
+ assert.calledTwice(feed.store.dispatch);
+ assert.calledWith(
+ feed.store.dispatch.firstCall,
+ ac.OnlyToOneContent(
+ {
+ type: at.DISCOVERY_STREAM_POCKET_STATE_SET,
+ data: { isUserLoggedIn: true },
+ },
+ {}
+ )
+ );
+ assert.calledWith(
+ feed.store.dispatch.secondCall,
+ ac.OnlyToOneContent(
+ {
+ type: at.DISCOVERY_STREAM_RECENT_SAVES,
+ data: { recentSaves: [1, 2, 3] },
+ },
+ {}
+ )
+ );
+ });
+ });
+
+ 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, "getCharPref").returns("");
+ 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("#parseGridPositions", () => {
+ it("should return an equivalent array for an array of non negative integers", async () => {
+ assert.deepEqual(feed.parseGridPositions([0, 2, 3]), [0, 2, 3]);
+ });
+ it("should return undefined for an array containing negative integers", async () => {
+ assert.equal(feed.parseGridPositions([-2, 2, 3]), undefined);
+ });
+ it("should return undefined for an undefined input", async () => {
+ assert.equal(feed.parseGridPositions(undefined), undefined);
+ });
+ });
+
+ 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[2].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[2].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[2].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[2].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"
+ );
+ });
+ it("should return enough stories to fill a four card layout", async () => {
+ feed.config.hardcoded_layout = true;
+
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: { fourCardLayout: 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[2].properties.items, 24);
+ });
+ it("should create a layout with spoc and widget positions", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocPositions: "1, 2",
+ widgetPositions: "3, 4",
+ },
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.deepEqual(layout[0].components[2].spocs.positions, [
+ { index: 1 },
+ { index: 2 },
+ ]);
+ assert.deepEqual(layout[0].components[2].widgets.positions, [
+ { index: 3 },
+ { index: 4 },
+ ]);
+ });
+ it("should create a layout with spoc position data", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocAdTypes: "1230",
+ spocZoneIds: "4560, 7890",
+ },
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.deepEqual(layout[0].components[2].placement.ad_types, [1230]);
+ assert.deepEqual(
+ layout[0].components[2].placement.zone_ids,
+ [4560, 7890]
+ );
+ });
+ it("should create a layout with spoc topsite position data", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocTopsitesAdTypes: "1230",
+ spocTopsitesZoneIds: "4560, 7890",
+ },
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.deepEqual(layout[0].components[0].placement.ad_types, [1230]);
+ assert.deepEqual(
+ layout[0].components[0].placement.zone_ids,
+ [4560, 7890]
+ );
+ });
+ it("should create a layout with proper spoc url with a site id", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocSiteId: "1234",
+ },
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+ const { spocs } = feed.store.getState().DiscoveryStream;
+ assert.deepEqual(
+ spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs?site=1234"
+ );
+ });
+ });
+
+ describe("#updatePlacements", () => {
+ it("should dispatch DISCOVERY_STREAM_SPOCS_PLACEMENTS", () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: true } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+ const fakeComponents = {
+ components: [
+ { placement: { name: "first" }, spocs: {} },
+ { placement: { name: "second" }, spocs: {} },
+ ],
+ };
+ 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 dispatch DISCOVERY_STREAM_SPOCS_PLACEMENTS with prefs array", () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: true, withPref: true } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+ const fakeComponents = {
+ components: [
+ { placement: { name: "withPref" }, spocs: { prefs: ["withPref"] } },
+ { placement: { name: "withoutPref1" }, spocs: {} },
+ {
+ placement: { name: "withoutPref2" },
+ spocs: { prefs: ["whatever"] },
+ },
+ { placement: { name: "withoutPref3" }, spocs: { prefs: [] } },
+ ],
+ };
+ 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: "withPref" }, { name: "withoutPref1" }] },
+ 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", () => {
+ feed.store.getState = () => ({
+ DiscoveryStream: {
+ spocs: {
+ placements: [{ name: "first" }, { name: "second" }],
+ },
+ },
+ });
+
+ let items = [];
+
+ feed.placementsForEach(item => items.push(item.name));
+
+ assert.deepEqual(items, ["first", "second"]);
+ });
+ });
+
+ 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 = {
+ Prefs: {},
+ 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("#personalizationOverride", () => {
+ it("should dispatch setPref", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.personalization.enabled": true,
+ },
+ },
+ });
+
+ feed.personalizationOverride(true);
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: "discoverystream.personalization.override",
+ value: true,
+ },
+ type: at.SET_PREF,
+ });
+ });
+ it("should dispatch CLEAR_PREF", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.personalization.enabled": true,
+ "discoverystream.personalization.override": true,
+ },
+ },
+ });
+
+ feed.personalizationOverride(false);
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: "discoverystream.personalization.override",
+ },
+ type: at.CLEAR_PREF,
+ });
+ });
+ });
+
+ describe("#loadSpocs", () => {
+ beforeEach(() => {
+ feed._prefCache = {
+ config: {
+ api_key_pref: "",
+ },
+ };
+
+ sandbox.stub(feed, "getPlacements").returns([{ name: "spocs" }]);
+ 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", score: 1 }],
+ },
+ },
+ lastUpdated: 0,
+ });
+
+ assert.deepEqual(
+ feed.store.getState().DiscoveryStream.spocs.data.spocs.items[0],
+ { id: "data", 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", score: 1 }
+ );
+ });
+ it("should call personalizationVersionOverride with feature_flags", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.stub(feed, "personalizationOverride").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.personalizationOverride);
+ });
+ it("should return expected data if normalizeSpocsItems returns no spoc data", async () => {
+ // We don't need this for just this test, we are setting placements manually.
+ feed.getPlacements.restore();
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => true,
+ });
+
+ 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" }, spocs: {} },
+ { placement: { name: "placement2" }, spocs: {} },
+ ],
+ };
+ 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 }],
+ },
+ placement2: {
+ title: "",
+ context: "",
+ items: [],
+ },
+ });
+ });
+ it("should use title and context on spoc data", async () => {
+ // We don't need this for just this test, we are setting placements manually.
+ feed.getPlacements.restore();
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => true,
+ });
+ 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" }, spocs: {} }],
+ };
+ 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 }],
+ },
+ });
+ });
+ });
+
+ 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 true from showSpocs if showSponsoredStories is false", async () => {
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => false,
+ });
+ Object.defineProperty(feed, "showSponsoredTopsites", {
+ get: () => true,
+ });
+ assert.isTrue(feed.showSpocs);
+ });
+ it("should return true from showSpocs if showSponsoredTopsites is false", async () => {
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => true,
+ });
+ Object.defineProperty(feed, "showSponsoredTopsites", {
+ get: () => false,
+ });
+ assert.isTrue(feed.showSpocs);
+ });
+ it("should return true from showSpocs if both are true", async () => {
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => true,
+ });
+ Object.defineProperty(feed, "showSponsoredTopsites", {
+ get: () => true,
+ });
+ assert.isTrue(feed.showSpocs);
+ });
+ it("should return false from showSpocs if both are false", async () => {
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => false,
+ });
+ Object.defineProperty(feed, "showSponsoredTopsites", {
+ get: () => false,
+ });
+ assert.isFalse(feed.showSpocs);
+ });
+ });
+
+ describe("#showSponsoredStories", () => {
+ it("should return false from showSponsoredStories 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.showSponsoredStories);
+ });
+ it("should return false from showSponsoredStories 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.showSponsoredStories);
+ });
+ it("should return true from showSponsoredStories if both prefs are true", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: true } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+
+ assert.isTrue(feed.showSponsoredStories);
+ });
+ });
+
+ describe("#showSponsoredTopsites", () => {
+ it("should return false from showSponsoredTopsites if user pref showSponsoredTopSites is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsoredTopSites: false } },
+ DiscoveryStream: {
+ spocs: {
+ placements: [{ name: "sponsored-topsites" }],
+ },
+ },
+ });
+ assert.isFalse(feed.showSponsoredTopsites);
+ });
+ it("should return true from showSponsoredTopsites if user pref showSponsoredTopSites is true", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsoredTopSites: true } },
+ DiscoveryStream: {
+ spocs: {
+ placements: [{ name: "sponsored-topsites" }],
+ },
+ },
+ });
+ assert.isTrue(feed.showSponsoredTopsites);
+ });
+ });
+
+ describe("#showStories", () => {
+ it("should return false from showStories if user pref is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.section.topstories": false,
+ "feeds.system.topstories": true,
+ },
+ },
+ });
+ assert.isFalse(feed.showStories);
+ });
+ it("should return false from showStories if system pref is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": false,
+ },
+ },
+ });
+ assert.isFalse(feed.showStories);
+ });
+ it("should return true from showStories if both prefs are true", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ },
+ },
+ });
+ assert.isTrue(feed.showStories);
+ });
+ });
+
+ describe("#showTopsites", () => {
+ it("should return false from showTopsites if user pref is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.topsites": false,
+ "feeds.system.topsites": true,
+ },
+ },
+ });
+ assert.isFalse(feed.showTopsites);
+ });
+ it("should return false from showTopsites if system pref is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.topsites": true,
+ "feeds.system.topsites": false,
+ },
+ },
+ });
+ assert.isFalse(feed.showTopsites);
+ });
+ it("should return true from showTopsites if both prefs are true", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "feeds.topsites": true,
+ "feeds.system.topsites": true,
+ },
+ },
+ });
+ assert.isTrue(feed.showTopsites);
+ });
+ });
+
+ describe("#clearSpocs", () => {
+ let defaultState;
+ let DiscoveryStream;
+ let Prefs;
+ beforeEach(() => {
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+ DiscoveryStream = {
+ layout: [],
+ spocs: {
+ placements: [{ name: "sponsored-topsites" }],
+ },
+ };
+ Prefs = {
+ values: {
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ "feeds.topsites": true,
+ "feeds.system.topsites": true,
+ showSponsoredTopSites: true,
+ showSponsored: true,
+ },
+ };
+ defaultState = {
+ DiscoveryStream,
+ Prefs,
+ };
+ feed.store.getState = () => defaultState;
+ });
+ 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"}'
+ );
+ });
+ it("should properly call clearSpocs when sponsored content is changed", async () => {
+ sandbox.stub(feed, "clearSpocs").returns(Promise.resolve());
+ //sandbox.stub(feed, "updatePlacements").returns();
+ sandbox.stub(feed, "loadSpocs").returns();
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored" },
+ });
+
+ assert.notCalled(feed.clearSpocs);
+
+ Prefs.values.showSponsoredTopSites = false;
+ Prefs.values.showSponsored = false;
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored" },
+ });
+
+ assert.calledOnce(feed.clearSpocs);
+ });
+ it("should call clearSpocs when top stories and top sites is turned off", async () => {
+ sandbox.stub(feed, "clearSpocs").returns(Promise.resolve());
+ Prefs.values["feeds.section.topstories"] = false;
+ Prefs.values["feeds.topsites"] = false;
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "feeds.section.topstories" },
+ });
+
+ assert.calledOnce(feed.clearSpocs);
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "feeds.topsites" },
+ });
+
+ assert.calledTwice(feed.clearSpocs);
+ });
+ });
+
+ 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 reset 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.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 .personalization 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, ["personalization", {}]);
+ });
+ });
+
+ 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 },
+ { id: 4, flight_id: 4, item_score: 0.5 },
+ { id: 3, flight_id: 3, item_score: 0.7 },
+ { id: 1, flight_id: 1, item_score: 0.9 },
+ ]);
+
+ assert.deepEqual(result, [
+ { id: 1, flight_id: 1, item_score: 0.9, score: 0.9 },
+ { id: 2, flight_id: 2, item_score: 0.8, score: 0.8 },
+ { id: 3, flight_id: 3, item_score: 0.7, score: 0.7 },
+ { id: 4, flight_id: 4, item_score: 0.5, score: 0.5 },
+ ]);
+ });
+
+ it("should sort based on priority", async () => {
+ const { data: result } = await feed.scoreItems([
+ { id: 6, flight_id: 6, priority: 2, item_score: 0.7 },
+ { id: 2, flight_id: 3, priority: 1, item_score: 0.2 },
+ { id: 4, flight_id: 4, item_score: 0.6 },
+ { id: 5, flight_id: 5, priority: 2, item_score: 0.8 },
+ { id: 3, flight_id: 3, item_score: 0.8 },
+ { id: 1, flight_id: 1, priority: 1, item_score: 0.3 },
+ ]);
+
+ assert.deepEqual(result, [
+ {
+ id: 1,
+ flight_id: 1,
+ priority: 1,
+ score: 0.3,
+ item_score: 0.3,
+ },
+ {
+ id: 2,
+ flight_id: 3,
+ priority: 1,
+ score: 0.2,
+ item_score: 0.2,
+ },
+ {
+ id: 5,
+ flight_id: 5,
+ priority: 2,
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ id: 6,
+ flight_id: 6,
+ priority: 2,
+ score: 0.7,
+ item_score: 0.7,
+ },
+ { id: 3, flight_id: 3, item_score: 0.8, score: 0.8 },
+ { id: 4, flight_id: 4, item_score: 0.6, score: 0.6 },
+ ]);
+ });
+
+ it("should add a score prop to spocs", async () => {
+ const { data: result } = await feed.scoreItems([
+ { flight_id: 1, item_score: 0.9 },
+ ]);
+
+ assert.equal(result[0].score, 0.9);
+ });
+ });
+
+ 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, "getPlacements").returns([{ name: "spocs" }]);
+ 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("#setupPrefs", () => {
+ it("should call setupPrefs", async () => {
+ sandbox.spy(feed, "setupPrefs");
+ feed.onAction({
+ type: at.INIT,
+ });
+ assert.calledOnce(feed.setupPrefs);
+ });
+ it("should dispatch to at.DISCOVERY_STREAM_PREFS_SETUP with proper data", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ globals.set("ExperimentAPI", {
+ getExperimentMetaData: () => ({
+ slug: "experimentId",
+ branch: {
+ slug: "branchId",
+ },
+ }),
+ getRolloutMetaData: () => ({}),
+ });
+ global.Services.prefs.getBoolPref
+ .withArgs("extensions.pocket.enabled")
+ .returns(true);
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ region: "CA",
+ pocketConfig: {
+ recentSavesEnabled: true,
+ hideDescriptions: false,
+ hideDescriptionsRegions: "US,CA,GB",
+ compactImages: true,
+ imageGradient: true,
+ newSponsoredLabel: true,
+ titleLines: "1",
+ descLines: "1",
+ readTime: true,
+ saveToPocketCard: false,
+ saveToPocketCardRegions: "US,CA,GB",
+ },
+ },
+ },
+ });
+ feed.setupPrefs();
+ assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
+ utmSource: "pocket-newtab",
+ utmCampaign: "experimentId",
+ utmContent: "branchId",
+ });
+ assert.deepEqual(feed.store.dispatch.secondCall.args[0].data, {
+ recentSavesEnabled: true,
+ pocketButtonEnabled: true,
+ saveToPocketCard: true,
+ hideDescriptions: true,
+ compactImages: true,
+ imageGradient: true,
+ newSponsoredLabel: true,
+ titleLines: "1",
+ descLines: "1",
+ readTime: true,
+ });
+ });
+ });
+
+ 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 () => {
+ sandbox.stub(feed, "getPlacements").returns([{ name: "spocs" }]);
+ 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 () => {
+ sandbox.stub(feed, "getPlacements").returns([{ name: "spocs" }]);
+ 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_POCKET_STATE_INIT", async () => {
+ it("should call setupPocketState", async () => {
+ sandbox.spy(feed, "setupPocketState");
+ feed.onAction({
+ type: at.DISCOVERY_STREAM_POCKET_STATE_INIT,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(feed.setupPocketState);
+ });
+ });
+
+ 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 fire onPrefChange when pocketConfig pref changes", async () => {
+ sandbox.stub(feed, "onPrefChange").returns(Promise.resolve());
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "pocketConfig", value: false },
+ });
+
+ assert.calledOnce(feed.onPrefChange);
+ });
+ it("should fire onCollectionsChanged when collections pref changes", async () => {
+ sandbox.stub(feed, "onCollectionsChanged").returns(Promise.resolve());
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.sponsored-collections.enabled" },
+ });
+
+ assert.calledOnce(feed.onCollectionsChanged);
+ });
+ 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("#onCollectionsChanged", () => {
+ it("should call loadLayout when Pocket config changes", async () => {
+ sandbox.stub(feed, "loadLayout").callsFake(dispatch => dispatch("foo"));
+ sandbox.stub(feed.store, "dispatch");
+ await feed.onCollectionsChanged();
+ assert.calledOnce(feed.loadLayout);
+ assert.calledWith(feed.store.dispatch, ac.AlsoToPreloaded("foo"));
+ });
+ });
+
+ describe("#onPrefChange", () => {
+ it("should call loadLayout when Pocket config changes", async () => {
+ sandbox.stub(feed, "loadLayout");
+ feed._prefCache.config = {
+ enabled: true,
+ };
+ await feed.onPrefChange();
+ assert.calledOnce(feed.loadLayout);
+ });
+ });
+
+ 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("#spocsCacheUpdateTime", () => {
+ it("should call setupSpocsCacheUpdateTime", () => {
+ const defaultCacheTime = 30 * 60 * 1000;
+ sandbox.spy(feed, "setupSpocsCacheUpdateTime");
+ const cacheTime = feed.spocsCacheUpdateTime;
+ assert.equal(feed._spocsCacheUpdateTime, defaultCacheTime);
+ assert.equal(cacheTime, defaultCacheTime);
+ assert.calledOnce(feed.setupSpocsCacheUpdateTime);
+ });
+ it("should return _spocsCacheUpdateTime", () => {
+ sandbox.spy(feed, "setupSpocsCacheUpdateTime");
+ const testCacheTime = 123;
+ feed._spocsCacheUpdateTime = testCacheTime;
+ const cacheTime = feed.spocsCacheUpdateTime;
+ // Ensure _spocsCacheUpdateTime was not changed.
+ assert.equal(feed._spocsCacheUpdateTime, testCacheTime);
+ assert.equal(cacheTime, testCacheTime);
+ assert.notCalled(feed.setupSpocsCacheUpdateTime);
+ });
+ });
+
+ describe("#setupSpocsCacheUpdateTime", () => {
+ it("should set _spocsCacheUpdateTime with default value", () => {
+ const defaultCacheTime = 30 * 60 * 1000;
+ feed.setupSpocsCacheUpdateTime();
+ assert.equal(feed._spocsCacheUpdateTime, defaultCacheTime);
+ });
+ it("should set _spocsCacheUpdateTime with min", () => {
+ const defaultCacheTime = 30 * 60 * 1000;
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocsCacheTimeout: 1,
+ },
+ },
+ },
+ });
+ feed.setupSpocsCacheUpdateTime();
+ assert.equal(feed._spocsCacheUpdateTime, defaultCacheTime);
+ });
+ it("should set _spocsCacheUpdateTime with max", () => {
+ const defaultCacheTime = 30 * 60 * 1000;
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocsCacheTimeout: 31,
+ },
+ },
+ },
+ });
+ feed.setupSpocsCacheUpdateTime();
+ assert.equal(feed._spocsCacheUpdateTime, defaultCacheTime);
+ });
+ it("should set _spocsCacheUpdateTime with spocsCacheTimeout", () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocsCacheTimeout: 20,
+ },
+ },
+ },
+ });
+ feed.setupSpocsCacheUpdateTime();
+ assert.equal(feed._spocsCacheUpdateTime, 20 * 60 * 1000);
+ });
+ });
+
+ 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() },
+ };
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ 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, "getPlacements").returns([{ name: "spocs" }]);
+ 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",
+ item_score: 0.7,
+ },
+ {
+ id: "second",
+ item_score: 0.6,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ "https://bar.com": {
+ data: {
+ recommendations: [
+ {
+ id: "third",
+ item_score: 0.4,
+ },
+ {
+ id: "fourth",
+ item_score: 0.6,
+ },
+ {
+ id: "fifth",
+ item_score: 0.8,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ },
+ };
+ const feedsTestResult = {
+ "https://foo.com": {
+ data: {
+ recommendations: [
+ {
+ id: "second",
+ item_score: 0.6,
+ score: 0.6,
+ },
+ {
+ id: "first",
+ item_score: 0.7,
+ score: 0.7,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ "https://bar.com": {
+ data: {
+ recommendations: [
+ {
+ id: "fifth",
+ item_score: 0.8,
+ score: 0.8,
+ },
+ {
+ id: "fourth",
+ item_score: 0.6,
+ score: 0.6,
+ },
+ {
+ id: "third",
+ item_score: 0.4,
+ score: 0.4,
+ },
+ ],
+ 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: [
+ {
+ item_score: 0.6,
+ },
+ {
+ item_score: 0.4,
+ },
+ {
+ item_score: 0.8,
+ },
+ ],
+ },
+ placement2: {
+ items: [
+ {
+ item_score: 0.6,
+ },
+ {
+ item_score: 0.8,
+ },
+ ],
+ },
+ placement3: { items: [] },
+ },
+ };
+
+ await feed.scoreSpocs(fakeSpocs);
+
+ const spocsTestResult = {
+ lastUpdated: 1234,
+ spocs: {
+ placement1: {
+ items: [
+ {
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ score: 0.6,
+ item_score: 0.6,
+ },
+ {
+ score: 0.4,
+ item_score: 0.4,
+ },
+ ],
+ },
+ placement2: {
+ items: [
+ {
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ 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: {
+ pocketConfig: {
+ recsPersonalized: true,
+ spocsPersonalized: true,
+ },
+ "discoverystream.personalization.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": 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, "loadPersonalizationScoresCache").resolves();
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ sandbox.stub(feed, "_checkExpirationPerComponent").resolves({
+ feeds: true,
+ spocs: 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("#loadPersonalizationScoresCache", () => {
+ it("should create a personalization provider from cached scores", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ recsPersonalized: true,
+ spocsPersonalized: true,
+ },
+ "discoverystream.personalization.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ },
+ },
+ });
+ const fakeCache = {
+ personalization: {
+ scores: 123,
+ _timestamp: 456,
+ },
+ };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+
+ await feed.loadPersonalizationScoresCache();
+
+ assert.equal(feed.personalizationLastUpdated, 456);
+ });
+ });
+
+ describe("#observe", () => {
+ it("should call updatePersonalizationScores on idle daily", async () => {
+ sandbox.stub(feed, "updatePersonalizationScores").returns();
+ feed.observe(null, "idle-daily");
+ assert.calledOnce(feed.updatePersonalizationScores);
+ });
+ it("should call configReset on Pocket button pref change", async () => {
+ sandbox.stub(feed, "configReset").returns();
+ feed.observe(null, "nsPref:changed", "extensions.pocket.enabled");
+ assert.calledOnce(feed.configReset);
+ });
+ });
+
+ describe("#updatePersonalizationScores", () => {
+ it("should update recommendationProvider on updatePersonalizationScores", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ recsPersonalized: true,
+ spocsPersonalized: true,
+ },
+ "discoverystream.personalization.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ },
+ },
+ });
+ sandbox.stub(feed.recommendationProvider, "init").returns();
+
+ await feed.updatePersonalizationScores();
+
+ assert.deepEqual(feed.recommendationProvider.provider.getScores(), {
+ interestConfig: undefined,
+ interestVector: undefined,
+ });
+ });
+ it("should not update recommendationProvider on updatePersonalizationScores", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ "discoverystream.personalization.enabled": false,
+ },
+ },
+ });
+ await feed.updatePersonalizationScores();
+
+ assert.isTrue(!feed.recommendationProvider.provider);
+ });
+ });
+ describe("#scoreItem", () => {
+ it("should call calculateItemRelevanceScore with recommendationProvider with initial score", async () => {
+ const item = {
+ item_score: 0.6,
+ };
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ pocketConfig: {
+ recsPersonalized: true,
+ spocsPersonalized: true,
+ },
+ "discoverystream.personalization.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ },
+ },
+ });
+ feed.recommendationProvider.calculateItemRelevanceScore = sandbox
+ .stub()
+ .returns();
+ const result = await feed.scoreItem(item, true);
+ assert.calledOnce(
+ feed.recommendationProvider.calculateItemRelevanceScore
+ );
+ assert.equal(result.score, 0.6);
+ });
+ it("should fallback to score 1 without an initial score", async () => {
+ const item = {};
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ "discoverystream.personalization.enabled": true,
+ },
+ },
+ });
+ feed.recommendationProvider.calculateItemRelevanceScore = sandbox
+ .stub()
+ .returns();
+ const result = await feed.scoreItem(item, true);
+ assert.equal(result.score, 1);
+ });
+ });
+ describe("new proxy feed", () => {
+ beforeEach(() => {
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: { regionBffConfig: "DE" },
+ },
+ },
+ });
+ sandbox.stub(global.Region, "home").get(() => "DE");
+ globals.set("NimbusFeatures", {
+ saveToPocket: {
+ getVariable: sandbox.stub(),
+ },
+ });
+ global.NimbusFeatures.saveToPocket.getVariable
+ .withArgs("bffApi")
+ .returns("bffApi");
+ global.NimbusFeatures.saveToPocket.getVariable
+ .withArgs("oAuthConsumerKeyBff")
+ .returns("oAuthConsumerKeyBff");
+ });
+ it("should return true with isBff", async () => {
+ assert.isUndefined(feed._isBff);
+ assert.isTrue(feed.isBff);
+ assert.isTrue(feed._isBff);
+ });
+ it("should update to new feed url", async () => {
+ await feed.loadLayout(feed.store.dispatch);
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.equal(
+ layout[0].components[2].feed.url,
+ "https://bffApi/desktop/v1/recommendations?locale=$locale&region=$region&count=30"
+ );
+ });
+ it("should fetch proper data from getComponentFeed", 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({
+ data: [
+ {
+ tileId: 1234,
+ url: "url",
+ title: "title",
+ excerpt: "excerpt",
+ publisher: "publisher",
+ imageUrl: "imageUrl",
+ },
+ ],
+ });
+
+ const feedData = await feed.getComponentFeed("url");
+ assert.deepEqual(feedData, {
+ lastUpdated: 0,
+ data: {
+ settings: {},
+ recommendations: [
+ {
+ id: 1234,
+ url: "url",
+ title: "title",
+ excerpt: "excerpt",
+ publisher: "publisher",
+ raw_image_src: "imageUrl",
+ },
+ ],
+ status: "success",
+ },
+ });
+ assert.equal(feed.fetchFromEndpoint.firstCall.args[0], "url");
+ assert.equal(feed.fetchFromEndpoint.firstCall.args[1].method, "GET");
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[1].headers.get("consumer_key"),
+ "oAuthConsumerKeyBff"
+ );
+ });
+ });
+});
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..0dfdff548b
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/DownloadsManager.test.js
@@ -0,0 +1,373 @@
+import { actionTypes as at } from "common/Actions.sys.mjs";
+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..6476e2a3be
--- /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.sys.mjs";
+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..e5d15a3fb0
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/FilterAdult.test.js
@@ -0,0 +1,112 @@
+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;
+ },
+ },
+ });
+ globals.set("gFilterAdultEnabled", true);
+ });
+
+ afterEach(() => {
+ hashValue = "";
+ globals.restore();
+ });
+
+ describe("filter", () => {
+ it("should default to include on unexpected urls", () => {
+ const empty = {};
+
+ const result = FilterAdult.filter([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.filter([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.filter([link]);
+
+ assert.equal(result.length, 0);
+ });
+ it("should not filter out adult urls if the preference is turned off", () => {
+ // Use a hash value that is in the adult set
+ hashValue = "+/UCpAhZhz368iGioEO8aQ==";
+ globals.set("gFilterAdultEnabled", false);
+ const link = { url: "https://some-adult-site/" };
+
+ const result = FilterAdult.filter([link]);
+
+ assert.equal(result.length, 1);
+ assert.equal(result[0], link);
+ });
+ });
+
+ describe("isAdultUrl", () => {
+ it("should default to false on unexpected urls", () => {
+ const result = FilterAdult.isAdultUrl("");
+
+ assert.equal(result, false);
+ });
+ it("should return false for non-adult urls", () => {
+ const result = FilterAdult.isAdultUrl("https://mozilla.org/");
+
+ assert.equal(result, false);
+ });
+ it("should return true for adult urls", () => {
+ // Use a hash value that is in the adult set
+ hashValue = "+/UCpAhZhz368iGioEO8aQ==";
+ const result = FilterAdult.isAdultUrl("https://some-adult-site/");
+
+ assert.equal(result, true);
+ });
+ it("should return false for adult urls when the preference is turned off", () => {
+ // Use a hash value that is in the adult set
+ hashValue = "+/UCpAhZhz368iGioEO8aQ==";
+ globals.set("gFilterAdultEnabled", false);
+ const result = FilterAdult.isAdultUrl("https://some-adult-site/");
+
+ assert.equal(result, false);
+ });
+
+ describe("test functions", () => {
+ it("should add and remove a filter in the adult list", () => {
+ // Use a hash value that is in the adult set
+ FilterAdult.addDomainToList("https://some-adult-site/");
+ let result = FilterAdult.isAdultUrl("https://some-adult-site/");
+
+ assert.equal(result, true);
+
+ FilterAdult.removeDomainFromList("https://some-adult-site/");
+ result = FilterAdult.isAdultUrl("https://some-adult-site/");
+
+ assert.equal(result, false);
+ });
+ });
+ });
+});
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..f0cd2450b7
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/HighlightsFeed.test.js
@@ -0,0 +1,822 @@
+"use strict";
+
+import { actionTypes as at } from "common/Actions.sys.mjs";
+import { Dedupe } from "common/Dedupe.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+import injector from "inject!lib/HighlightsFeed.jsm";
+import { Screenshots } from "lib/Screenshots.jsm";
+import { LinksCache } from "lib/LinksCache.sys.mjs";
+
+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 = {
+ filter: sinon.stub().returnsArg(0),
+ };
+ shortURLStub = sinon
+ .stub()
+ .callsFake(site => site.url.match(/\/([^/]+)/)[1]);
+ fakePageThumbs = {
+ addExpirationFilter: sinon.stub(),
+ removeExpirationFilter: sinon.stub(),
+ };
+
+ globals.set({
+ NewTabUtils: fakeNewTabUtils,
+ PageThumbs: fakePageThumbs,
+ gFilterAdultEnabled: false,
+ LinksCache,
+ DownloadsManager: downloadsManagerStub,
+ FilterAdult: filterAdultStub,
+ Screenshots: fakeScreenshot,
+ });
+ ({
+ 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: {
+ "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 filter out adult pages", async () => {
+ filterAdultStub.filter = sinon.stub().returns([]);
+ const highlights = await fetchHighlights();
+
+ // The stub filters out everything
+ assert.calledOnce(filterAdultStub.filter);
+ 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..8a4d33d2f2
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/LinksCache.test.js
@@ -0,0 +1,16 @@
+import { LinksCache } from "lib/LinksCache.sys.mjs";
+
+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..5357290a76
--- /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.sys.mjs";
+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..834409669f
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/NewTabInit.test.js
@@ -0,0 +1,81 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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..e645b8d398
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersistentCache.test.js
@@ -0,0 +1,142 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+
+describe("PersistentCache", () => {
+ let fakeIOUtils;
+ let fakePathUtils;
+ let cache;
+ let filename = "cache.json";
+ let consoleErrorStub;
+ let globals;
+ let sandbox;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ fakeIOUtils = {
+ writeJSON: sinon.stub().resolves(0),
+ readJSON: sinon.stub().resolves({}),
+ };
+ fakePathUtils = {
+ join: sinon.stub().returns(filename),
+ localProfileDir: "/",
+ };
+ consoleErrorStub = sandbox.stub();
+ globals.set("console", { error: consoleErrorStub });
+ globals.set("IOUtils", fakeIOUtils);
+ globals.set("PathUtils", fakePathUtils);
+
+ cache = new PersistentCache(filename);
+ });
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+
+ describe("#get", () => {
+ it("tries to read the file", async () => {
+ await cache.get("foo");
+ assert.calledOnce(fakeIOUtils.readJSON);
+ });
+ it("doesnt try to read the file if it was already loaded", async () => {
+ await cache._load();
+ fakeIOUtils.readJSON.resetHistory();
+ await cache.get("foo");
+ assert.notCalled(fakeIOUtils.readJSON);
+ });
+ it("should catch and report errors", async () => {
+ fakeIOUtils.readJSON.rejects(new SyntaxError("Failed to parse JSON"));
+ await cache._load();
+ assert.calledOnce(consoleErrorStub);
+
+ cache._cache = undefined;
+ consoleErrorStub.resetHistory();
+
+ fakeIOUtils.readJSON.rejects(
+ new DOMException("IOUtils shutting down", "AbortError")
+ );
+ await cache._load();
+ assert.calledOnce(consoleErrorStub);
+
+ cache._cache = undefined;
+ consoleErrorStub.resetHistory();
+
+ fakeIOUtils.readJSON.rejects(
+ new DOMException("File not found", "NotFoundError")
+ );
+ await cache._load();
+ assert.notCalled(consoleErrorStub);
+ });
+ it("returns data for a given cache key", async () => {
+ fakeIOUtils.readJSON.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 () => {
+ fakeIOUtils.readJSON.resolves({ foo: "bar" });
+ let value = await cache.get();
+ assert.deepEqual(value, { foo: "bar" });
+ });
+ });
+
+ describe("#set", () => {
+ it("tries to read the file on the first set", async () => {
+ await cache.set("foo", { x: 42 });
+ assert.calledOnce(fakeIOUtils.readJSON);
+ });
+ it("doesnt try to read the file if it was already loaded", async () => {
+ cache = new PersistentCache(filename, true);
+ await cache._load();
+ fakeIOUtils.readJSON.resetHistory();
+ await cache.set("foo", { x: 42 });
+ assert.notCalled(fakeIOUtils.readJSON);
+ });
+ 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 };
+
+ await cache.set(key, value);
+ assert.calledOnce(fakeIOUtils.writeJSON);
+ assert.calledWith(
+ fakeIOUtils.writeJSON,
+ filename,
+ { [[key]]: value },
+ { tmpPath: `${filename}.tmp` }
+ );
+ });
+ it("throws when failing to get file path", async () => {
+ Object.defineProperty(fakePathUtils, "localProfileDir", {
+ get() {
+ throw new Error();
+ },
+ });
+
+ 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..0751cafb4f
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js
@@ -0,0 +1,95 @@
+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..fb3abb1367
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js
@@ -0,0 +1,479 @@
+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..833a9d5a7c
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js
@@ -0,0 +1,356 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PersonalityProvider } from "lib/PersonalityProvider/PersonalityProvider.jsm";
+
+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 === "bogus://foo/") {
+ return { capabilities: { attachments: { base_url: baseURLStub } } };
+ }
+ return {};
+ },
+ });
+ globals.set("RemoteSettings", RemoteSettingsStub);
+
+ instance = new PersonalityProvider();
+ 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("#getScores", () => {
+ it("should return correct data for getScores", () => {
+ const scores = instance.getScores();
+ assert.isDefined(scores.interestConfig);
+ });
+ });
+});
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..6dd483ae70
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js
@@ -0,0 +1,456 @@
+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("#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", async () => {
+ it("should sync remote settings collection from onSync", async () => {
+ sinon.stub(instance, "deleteAttachment").resolves();
+ sinon.stub(instance, "maybeDownloadAttachment").resolves();
+
+ 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", async () => {
+ let existsStub;
+ let statStub;
+ let attachmentStub;
+ sinon.stub(instance, "_downloadAttachment").resolves();
+ const makeDirStub = globals.sandbox
+ .stub(global.IOUtils, "makeDirectory")
+ .resolves();
+
+ existsStub = globals.sandbox
+ .stub(global.IOUtils, "exists")
+ .resolves(true);
+
+ statStub = globals.sandbox
+ .stub(global.IOUtils, "stat")
+ .resolves({ size: "1" });
+
+ attachmentStub = {
+ attachment: {
+ filename: "file",
+ size: "1",
+ // This hash matches the hash generated from the empty Uint8Array returned by the IOUtils.read stub.
+ hash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ },
+ };
+
+ await instance.maybeDownloadAttachment(attachmentStub);
+ assert.calledWith(makeDirStub, "personality-provider");
+ assert.calledOnce(existsStub);
+ assert.calledOnce(statStub);
+ assert.notCalled(instance._downloadAttachment);
+
+ existsStub.resetHistory();
+ statStub.resetHistory();
+ instance._downloadAttachment.resetHistory();
+
+ attachmentStub = {
+ attachment: {
+ filename: "file",
+ size: "2",
+ },
+ };
+
+ await instance.maybeDownloadAttachment(attachmentStub);
+ assert.calledThrice(existsStub);
+ assert.calledThrice(statStub);
+ assert.calledThrice(instance._downloadAttachment);
+
+ existsStub.resetHistory();
+ statStub.resetHistory();
+ instance._downloadAttachment.resetHistory();
+
+ attachmentStub = {
+ attachment: {
+ filename: "file",
+ size: "1",
+ // Bogus hash to trigger an update.
+ hash: "1234",
+ },
+ };
+
+ await instance.maybeDownloadAttachment(attachmentStub);
+ assert.calledThrice(existsStub);
+ assert.calledThrice(statStub);
+ assert.calledThrice(instance._downloadAttachment);
+ });
+ });
+ describe("#_downloadAttachment", () => {
+ beforeEach(() => {
+ globals.set("Uint8Array", class Uint8Array {});
+ });
+ it("should write a file from _downloadAttachment", async () => {
+ globals.set(
+ "XMLHttpRequest",
+ class {
+ constructor() {
+ this.status = 200;
+ this.response = "response!";
+ }
+ open() {}
+ setRequestHeader() {}
+ send() {}
+ }
+ );
+
+ const ioutilsWriteStub = globals.sandbox
+ .stub(global.IOUtils, "write")
+ .resolves();
+
+ await instance._downloadAttachment({
+ attachment: { location: "location", filename: "filename" },
+ });
+
+ const writeArgs = ioutilsWriteStub.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", async () => {
+ globals.set(
+ "XMLHttpRequest",
+ class {
+ constructor() {
+ this.status = 0;
+ this.response = "response!";
+ }
+ open() {}
+ setRequestHeader() {}
+ send() {}
+ }
+ );
+
+ const consoleErrorStub = globals.sandbox
+ .stub(console, "error")
+ .resolves();
+
+ await instance._downloadAttachment({
+ attachment: { location: "location", filename: "filename" },
+ });
+
+ assert.calledOnce(consoleErrorStub);
+ });
+ });
+ describe("#deleteAttachment", () => {
+ it("should remove attachments when calling deleteAttachment", async () => {
+ const makeDirStub = globals.sandbox
+ .stub(global.IOUtils, "makeDirectory")
+ .resolves();
+ const removeStub = globals.sandbox
+ .stub(global.IOUtils, "remove")
+ .resolves();
+ await instance.deleteAttachment({ attachment: { filename: "filename" } });
+ assert.calledOnce(makeDirStub);
+ assert.calledTwice(removeStub);
+ assert.calledWith(removeStub.firstCall, "filename", {
+ ignoreAbsent: true,
+ });
+ assert.calledWith(removeStub.secondCall, "personality-provider", {
+ ignoreAbsent: true,
+ });
+ });
+ });
+ describe("#getAttachment", () => {
+ it("should return JSON when calling getAttachment", async () => {
+ sinon.stub(instance, "maybeDownloadAttachment").resolves();
+ const readJSONStub = globals.sandbox
+ .stub(global.IOUtils, "readJSON")
+ .resolves({});
+ const record = { attachment: { filename: "filename" } };
+ let returnValue = await instance.getAttachment(record);
+
+ assert.calledOnce(readJSONStub);
+ assert.calledWith(readJSONStub, "filename");
+ assert.calledOnce(instance.maybeDownloadAttachment);
+ assert.calledWith(instance.maybeDownloadAttachment, record);
+ assert.deepEqual(returnValue, {});
+
+ readJSONStub.restore();
+ globals.sandbox.stub(global.IOUtils, "readJSON").throws("foo");
+ const consoleErrorStub = globals.sandbox
+ .stub(console, "error")
+ .resolves();
+ returnValue = await instance.getAttachment(record);
+
+ assert.calledOnce(consoleErrorStub);
+ assert.deepEqual(returnValue, {});
+ });
+ });
+ describe("#fetchModels", () => {
+ it("should return ok true", async () => {
+ sinon.stub(instance, "getAttachment").resolves();
+ const result = await instance.fetchModels([{ key: 1234 }]);
+ assert.isTrue(result.ok);
+ assert.deepEqual(instance.models, [{ recordKey: 1234 }]);
+ });
+ it("should return ok false", async () => {
+ sinon.stub(instance, "getAttachment").resolves();
+ const result = await 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..82a1f2b77a
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js
@@ -0,0 +1,1543 @@
+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..20210ab7b1
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PlacesFeed.test.js
@@ -0,0 +1,1245 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+import injector from "inject!lib/PlacesFeed.jsm";
+
+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;
+
+const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+const POCKET_SITE_PREF = "extensions.pocket.site";
+
+describe("PlacesFeed", () => {
+ let PlacesFeed;
+ let PlacesObserver;
+ let globals;
+ let sandbox;
+ let feed;
+ let shortURLStub;
+ 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("pktApi", {
+ isUserLoggedIn: sandbox.spy(),
+ });
+ globals.set("ExperimentAPI", {
+ getExperiment: sandbox.spy(),
+ });
+ globals.set("NimbusFeatures", {
+ pocketNewtab: {
+ getVariable: sandbox.spy(),
+ },
+ });
+ 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.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.console, "error");
+ shortURLStub = sandbox
+ .stub()
+ .callsFake(site =>
+ site.url.replace(/(.com|.ca)/, "").replace("https://", "")
+ );
+
+ 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(),
+ };
+ },
+ };
+ ({ PlacesFeed } = injector({
+ "lib/ShortURL.jsm": { shortURL: shortURLStub },
+ }));
+ PlacesObserver = PlacesFeed.PlacesObserver;
+ feed = new PlacesFeed();
+ feed.store = { dispatch: sinon.spy() };
+ globals.set("AboutNewTab", {
+ activityStream: { store: { feeds: { get() {} } } },
+ });
+ });
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+
+ 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("#addToBlockedTopSitesSponsors", () => {
+ let spy;
+ beforeEach(() => {
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(TOP_SITES_BLOCKED_SPONSORS_PREF)
+ .returns(`["foo","bar"]`);
+ spy = sandbox.spy(global.Services.prefs, "setStringPref");
+ });
+
+ it("should add the blocked sponsors to the blocklist", () => {
+ feed.addToBlockedTopSitesSponsors([
+ { url: "test.com" },
+ { url: "test1.com" },
+ ]);
+
+ assert.calledOnce(spy);
+ const [, sponsors] = spy.firstCall.args;
+ assert.deepEqual(
+ new Set(["foo", "bar", "test", "test1"]),
+ new Set(JSON.parse(sponsors))
+ );
+ });
+
+ it("should not add duplicate sponsors to the blocklist", () => {
+ feed.addToBlockedTopSitesSponsors([
+ { url: "foo.com" },
+ { url: "bar.com" },
+ { url: "test.com" },
+ ]);
+
+ assert.calledOnce(spy);
+ const [, sponsors] = spy.firstCall.args;
+ assert.deepEqual(
+ new Set(["foo", "bar", "test"]),
+ new Set(JSON.parse(sponsors))
+ );
+ });
+ });
+
+ describe("#onAction", () => {
+ it("should add bookmark, history, places, blocked observers on INIT", () => {
+ feed.onAction({ type: at.INIT });
+
+ assert.calledWith(
+ global.PlacesUtils.observers.addListener,
+ [
+ "bookmark-added",
+ "bookmark-removed",
+ "history-cleared",
+ "page-removed",
+ ],
+ 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.observers.removeListener,
+ [
+ "bookmark-added",
+ "bookmark-removed",
+ "history-cleared",
+ "page-removed",
+ ],
+ 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 update the blocked top sites sponsors", () => {
+ sandbox.stub(feed, "addToBlockedTopSitesSponsors");
+ feed.onAction({
+ type: at.BLOCK_URL,
+ data: [{ url: "foo.com", pocket_id: 1234, isSponsoredTopSite: 1 }],
+ });
+ assert.calledWith(feed.addToBlockedTopSitesSponsors, [
+ { url: "foo.com" },
+ ]);
+ });
+ 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, "forceForeground", 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, "forceForeground", 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, "forceForeground", 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.console.error.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 openTrustedLinkIn with sendToPocket if not logged in", () => {
+ const openTrustedLinkIn = sinon.stub();
+ global.NimbusFeatures.pocketNewtab.getVariable = sandbox
+ .stub()
+ .returns(true);
+ global.pktApi.isUserLoggedIn = sandbox.stub().returns(false);
+ global.ExperimentAPI.getExperiment = sandbox.stub().returns({
+ slug: "slug",
+ branch: { slug: "branch-slug" },
+ });
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(POCKET_SITE_PREF)
+ .returns("getpocket.com");
+ const action = {
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+ feed.onAction(action);
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where] = openTrustedLinkIn.firstCall.args;
+ assert.equal(
+ url,
+ "https://getpocket.com/signup?utm_source=firefox_newtab_save_button&utm_campaign=slug&utm_content=branch-slug"
+ );
+ assert.equal(where, "tab");
+ });
+ 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.console.error, 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.console.error, 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.console.error, 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(),
+ handoff: 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.handoff);
+ assert.notCalled(feed.store.dispatch);
+
+ // Now type a character.
+ listeners.keydown({ key: "f" });
+ assert.calledOnce(fakeUrlBar.handoff);
+ 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: "DISABLE_SEARCH",
+ });
+ });
+ it("should properly handle handoff with text data passed in", () => {
+ const sessionId = "decafc0ffee";
+ sandbox
+ .stub(global.AboutNewTab.activityStream.store.feeds, "get")
+ .returns({
+ sessions: {
+ get: () => {
+ return { session_id: sessionId };
+ },
+ },
+ });
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.handoff);
+ assert.calledWithExactly(
+ fakeUrlBar.handoff,
+ "foo",
+ global.Services.search.defaultEngine,
+ sessionId
+ );
+ 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.handoff);
+ assert.calledWithExactly(
+ fakeUrlBar.handoff,
+ "foo",
+ global.Services.search.defaultPrivateEngine,
+ undefined
+ );
+ 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.handoff);
+ assert.calledWithExactly(
+ fakeUrlBar.handoff,
+ "foo",
+ global.Services.search.defaultEngine,
+ undefined
+ );
+ 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 handoff a newtab session id with no text passed in", () => {
+ const sessionId = "decafc0ffee";
+ sandbox
+ .stub(global.AboutNewTab.activityStream.store.feeds, "get")
+ .returns({
+ sessions: {
+ get: () => {
+ return { session_id: sessionId };
+ },
+ },
+ });
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: {},
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.setHiddenFocus);
+ assert.notCalled(fakeUrlBar.handoff);
+ assert.notCalled(feed.store.dispatch);
+
+ // Now type a character.
+ listeners.keydown({ key: "f" });
+ assert.calledOnce(fakeUrlBar.handoff);
+ assert.calledWithExactly(
+ fakeUrlBar.handoff,
+ "",
+ global.Services.search.defaultEngine,
+ sessionId
+ );
+ 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: "DISABLE_SEARCH",
+ });
+ });
+ });
+
+ 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("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 page-removed notifications happened at once", async () => {
+ await feed.placesObserver.handlePlacesEvent([
+ { type: "page-removed", url: "foo.com", isRemovedFromStore: true },
+ ]);
+ await feed.placesObserver.handlePlacesEvent([
+ { type: "page-removed", url: "foo1.com", isRemovedFromStore: true },
+ ]);
+ await feed.placesObserver.handlePlacesEvent([
+ { type: "page-removed", url: "foo2.com", isRemovedFromStore: true },
+ ]);
+
+ 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("#page-removed", () => {
+ it("should dispatch a PLACES_LINKS_DELETED action with the right url", async () => {
+ const args = [
+ {
+ type: "page-removed",
+ url: "foo.com",
+ isRemovedFromStore: true,
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+ assert.calledWith(dispatch, {
+ type: at.PLACES_LINKS_DELETED,
+ data: { urls: ["foo.com"] },
+ });
+ });
+ });
+
+ 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_BOOKMARKS_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_BOOKMARKS_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_BOOKMARKS_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_BOOKMARKS_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_BOOKMARKS_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_BOOKMARKS_REMOVED,
+ data: { urls: ["foo.com"] },
+ });
+ });
+ });
+ });
+});
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..581222b3ee
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PrefsFeed.test.js
@@ -0,0 +1,357 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+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 }],
+ ["qux", { value: 1, skipBroadcast: true, alsoToPreloaded: 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(),
+ },
+ };
+ sinon.spy(feed, "_setPref");
+ 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.NimbusFeatures.newtab, "getAllVariables").returns({
+ 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 an empty object if no experiment is returned", () => {
+ sandbox.stub(global.NimbusFeatures.newtab, "getAllVariables").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, {});
+ });
+ 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 a PREF_CHANGED actions when onPocketExperimentUpdated is called", () => {
+ sandbox
+ .stub(global.NimbusFeatures.pocketNewtab, "getAllVariables")
+ .returns({
+ prefsButtonIcon: "icon-new",
+ });
+ feed.onPocketExperimentUpdated();
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "pocketConfig",
+ value: {
+ prefsButtonIcon: "icon-new",
+ },
+ },
+ })
+ );
+ });
+ it("should not send a PREF_CHANGED actions when onPocketExperimentUpdated is called during startup", () => {
+ sandbox
+ .stub(global.NimbusFeatures.pocketNewtab, "getAllVariables")
+ .returns({
+ prefsButtonIcon: "icon-new",
+ });
+ feed.onPocketExperimentUpdated({}, "feature-experiment-loaded");
+ assert.notCalled(feed.store.dispatch);
+ feed.onPocketExperimentUpdated({}, "feature-rollout-loaded");
+ assert.notCalled(feed.store.dispatch);
+ });
+ it("should send a PREF_CHANGED actions when onExperimentUpdated is called", () => {
+ sandbox.stub(global.NimbusFeatures.newtab, "getAllVariables").returns({
+ prefsButtonIcon: "icon-new",
+ });
+ feed.onExperimentUpdated();
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "featureConfig",
+ value: {
+ prefsButtonIcon: "icon-new",
+ },
+ },
+ })
+ );
+ });
+
+ it("should remove all events on removeListeners", () => {
+ feed.geo = "";
+ sandbox.spy(global.NimbusFeatures.pocketNewtab, "offUpdate");
+ sandbox.spy(global.NimbusFeatures.newtab, "offUpdate");
+ feed.removeListeners();
+ assert.calledWith(
+ global.NimbusFeatures.pocketNewtab.offUpdate,
+ feed.onPocketExperimentUpdated
+ );
+ assert.calledWith(
+ global.NimbusFeatures.newtab.offUpdate,
+ feed.onExperimentUpdated
+ );
+ assert.calledWith(
+ ServicesStub.obs.removeObserver,
+ feed,
+ global.Region.REGION_TOPIC
+ );
+ });
+
+ 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 } },
+ })
+ );
+ });
+ it("should send AlsoToPreloaded pref update if config for pref has skipBroadcast: true and alsoToPreloaded: true", async () => {
+ feed.onPrefChanged("qux", {
+ value: 2,
+ skipBroadcast: true,
+ alsoToPreloaded: true,
+ });
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.AlsoToPreloaded({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "qux",
+ value: { value: 2, skipBroadcast: true, alsoToPreloaded: true },
+ },
+ })
+ );
+ });
+ describe("#observe", () => {
+ it("should call dispatch from observe", () => {
+ feed.observe(undefined, global.Region.REGION_TOPIC);
+ assert.calledOnce(feed.store.dispatch);
+ });
+ });
+ describe("#_setStringPref", () => {
+ it("should call _setPref and getStringPref from _setStringPref", () => {
+ feed._setStringPref({}, "fake.pref", "default");
+ assert.calledOnce(feed._setPref);
+ assert.calledWith(
+ feed._setPref,
+ { "fake.pref": undefined },
+ "fake.pref",
+ "default"
+ );
+ assert.calledOnce(ServicesStub.prefs.getStringPref);
+ assert.calledWith(
+ ServicesStub.prefs.getStringPref,
+ "browser.newtabpage.activity-stream.fake.pref",
+ "default"
+ );
+ });
+ });
+ describe("#_setBoolPref", () => {
+ it("should call _setPref and getBoolPref from _setBoolPref", () => {
+ feed._setBoolPref({}, "fake.pref", false);
+ assert.calledOnce(feed._setPref);
+ assert.calledWith(
+ feed._setPref,
+ { "fake.pref": undefined },
+ "fake.pref",
+ false
+ );
+ assert.calledOnce(ServicesStub.prefs.getBoolPref);
+ assert.calledWith(
+ ServicesStub.prefs.getBoolPref,
+ "browser.newtabpage.activity-stream.fake.pref",
+ false
+ );
+ });
+ });
+ describe("#_setIntPref", () => {
+ it("should call _setPref and getIntPref from _setIntPref", () => {
+ feed._setIntPref({}, "fake.pref", 1);
+ assert.calledOnce(feed._setPref);
+ assert.calledWith(
+ feed._setPref,
+ { "fake.pref": undefined },
+ "fake.pref",
+ 1
+ );
+ assert.calledOnce(ServicesStub.prefs.getIntPref);
+ assert.calledWith(
+ ServicesStub.prefs.getIntPref,
+ "browser.newtabpage.activity-stream.fake.pref",
+ 1
+ );
+ });
+ });
+ describe("#_setPref", () => {
+ it("should set pref value with _setPref", () => {
+ const getPrefFunctionSpy = sinon.spy();
+ const values = {};
+ feed._setPref(values, "fake.pref", "default", getPrefFunctionSpy);
+ assert.deepEqual(values, { "fake.pref": undefined });
+ assert.calledOnce(getPrefFunctionSpy);
+ assert.calledWith(
+ getPrefFunctionSpy,
+ "browser.newtabpage.activity-stream.fake.pref",
+ "default"
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/RecommendationProvider.test.js b/browser/components/newtab/test/unit/lib/RecommendationProvider.test.js
new file mode 100644
index 0000000000..3ddbf182c3
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/RecommendationProvider.test.js
@@ -0,0 +1,162 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { RecommendationProvider } from "lib/RecommendationProvider.jsm";
+import { combineReducers, createStore } from "redux";
+import { reducers } from "common/Reducers.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+
+import { PersonalityProvider } from "lib/PersonalityProvider/PersonalityProvider.jsm";
+
+const PREF_PERSONALIZATION_ENABLED = "discoverystream.personalization.enabled";
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+describe("RecommendationProvider", () => {
+ let feed;
+ let sandbox;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set({
+ PersonalityProvider,
+ });
+
+ sandbox = sinon.createSandbox();
+ feed = new RecommendationProvider();
+ feed.store = createStore(combineReducers(reducers), {});
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("#setProvider", () => {
+ it("should setup proper provider with modelKeys", async () => {
+ feed.setProvider();
+
+ assert.equal(feed.provider.modelKeys, undefined);
+
+ feed.provider = null;
+ feed._modelKeys = "1234";
+
+ feed.setProvider();
+
+ assert.equal(feed.provider.modelKeys, "1234");
+ feed._modelKeys = "12345";
+
+ // Calling it again should not rebuild the provider.
+ feed.setProvider();
+ assert.equal(feed.provider.modelKeys, "1234");
+ });
+ });
+
+ describe("#init", () => {
+ it("should init affinityProvider then refreshContent", async () => {
+ feed.provider = {
+ init: sandbox.stub().resolves(),
+ };
+ await feed.init();
+ assert.calledOnce(feed.provider.init);
+ });
+ });
+
+ describe("#getScores", () => {
+ it("should call affinityProvider.getScores", () => {
+ feed.provider = {
+ getScores: sandbox.stub().resolves(),
+ };
+ feed.getScores();
+ assert.calledOnce(feed.provider.getScores);
+ });
+ });
+
+ describe("#calculateItemRelevanceScore", () => {
+ it("should use personalized score with provider", async () => {
+ const item = {};
+ feed.provider = {
+ calculateItemRelevanceScore: async () => 0.5,
+ };
+ await feed.calculateItemRelevanceScore(item);
+ assert.equal(item.score, 0.5);
+ });
+ });
+
+ describe("#teardown", () => {
+ it("should call provider.teardown ", () => {
+ feed.provider = {
+ teardown: sandbox.stub().resolves(),
+ };
+ feed.teardown();
+ assert.calledOnce(feed.provider.teardown);
+ });
+ });
+
+ describe("#resetState", () => {
+ it("should null affinityProviderV2 and affinityProvider", () => {
+ feed._modelKeys = {};
+ feed.provider = {};
+
+ feed.resetState();
+
+ assert.equal(feed._modelKeys, null);
+ assert.equal(feed.provider, null);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_CHANGE", () => {
+ it("should call teardown, resetState, and setVersion", async () => {
+ sandbox.spy(feed, "teardown");
+ sandbox.spy(feed, "resetState");
+ feed.onAction({
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ });
+ assert.calledOnce(feed.teardown);
+ assert.calledOnce(feed.resetState);
+ });
+ });
+
+ describe("#onAction: PREF_CHANGED", () => {
+ beforeEach(() => {
+ sandbox.spy(feed.store, "dispatch");
+ });
+ 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_TOGGLE", () => {
+ it("should fire SET_PREF with enabled", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [PREF_PERSONALIZATION_ENABLED]: false,
+ },
+ },
+ });
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_TOGGLE,
+ });
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.SetPref(PREF_PERSONALIZATION_ENABLED, true)
+ );
+ });
+ });
+});
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..dc0be33180
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SectionsManager.test.js
@@ -0,0 +1,897 @@
+"use strict";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ CONTENT_MESSAGE_TYPE,
+ MAIN_MESSAGE_TYPE,
+ PRELOAD_MESSAGE_TYPE,
+} from "common/Actions.sys.mjs";
+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,
+ NimbusFeatures: {
+ newtab: { getAllVariables: sandbox.stub() },
+ pocketNewtab: { getAllVariables: sandbox.stub() },
+ },
+ });
+ // 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.console, "error");
+ SectionsManager._storage.get = sandbox.stub().returns(Promise.resolve());
+ await SectionsManager.addBuiltInSection(
+ "feeds.section.topstories",
+ undefined
+ );
+
+ assert.notCalled(console.error);
+ });
+ it("should report an error if options is malformed", async () => {
+ globals.sandbox.spy(global.console, "error");
+ SectionsManager._storage.get = sandbox.stub().returns(Promise.resolve());
+ await SectionsManager.addBuiltInSection(
+ "feeds.section.topstories",
+ "invalid"
+ );
+
+ assert.calledOnce(console.error);
+ });
+ it("should not throw if the indexedDB operation fails", async () => {
+ globals.sandbox.spy(global.console, "error");
+ 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(console.error);
+ });
+ });
+ 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.console, "error");
+ SectionsManager.updateSection(
+ "highlights",
+ { rows: [{ url: "foo", type: "badtype" }] },
+ false
+ );
+ const highlights = SectionsManager.sections.get("highlights").rows;
+ assert.calledOnce(console.error);
+ 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;
+ let globals;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ SectionsManager.sections.clear();
+ SectionsManager.initialized = false;
+ globals = new GlobalOverrider();
+ globals.set("NimbusFeatures", {
+ newtab: { getAllVariables: sandbox.stub() },
+ pocketNewtab: { getAllVariables: sandbox.stub() },
+ });
+ 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();
+ globals.restore();
+ });
+ 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..eeeef3bf51
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/Store.test.js
@@ -0,0 +1,305 @@
+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.getMessageChannel());
+ assert.equal(store.getMessageChannel().dispatch, store.dispatch);
+ assert.equal(store.getMessageChannel(), store._messageChannel);
+ });
+ 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());
+ });
+ 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.getMessageChannel().simulateMessagesForExistingTabs
+ );
+ });
+ it("should dispatch INIT before LOAD", async () => {
+ const init = { type: "INIT" };
+ const load = { type: "TAB_LOAD" };
+ sandbox.stub(store, "dispatch");
+ store
+ .getMessageChannel()
+ .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);
+ });
+ });
+ 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..4dd5febdb2
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js
@@ -0,0 +1,76 @@
+import { SYSTEM_TICK_INTERVAL, SystemTickFeed } from "lib/SystemTickFeed.jsm";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("System Tick Feed", () => {
+ let globals;
+ let instance;
+ let clock;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ clock = sinon.useFakeTimers();
+
+ instance = new SystemTickFeed();
+ instance.store = {
+ getState() {
+ return {};
+ },
+ dispatch() {},
+ };
+ });
+ afterEach(() => {
+ globals.restore();
+ clock.restore();
+ });
+ it("should create a SystemTickFeed", () => {
+ assert.instanceOf(instance, SystemTickFeed);
+ });
+ it("should fire SYSTEM_TICK events at configured interval", () => {
+ globals.set("ChromeUtils", {
+ idleDispatch: f => f(),
+ });
+ 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();
+ });
+ it("should not fire SYSTEM_TICK events while the user is away", () => {
+ let expectation = sinon.mock(instance.store).expects("dispatch").never();
+
+ instance.onAction({ type: at.INIT });
+ instance._idleService = { idleTime: SYSTEM_TICK_INTERVAL + 1 };
+ clock.tick(SYSTEM_TICK_INTERVAL * 3);
+ expectation.verify();
+ instance.onAction({ type: at.UNINIT });
+ });
+ it("should fire SYSTEM_TICK immediately when the user is active again", () => {
+ globals.set("ChromeUtils", {
+ idleDispatch: f => f(),
+ });
+ let expectation = sinon
+ .mock(instance.store)
+ .expects("dispatch")
+ .once()
+ .withExactArgs({ type: at.SYSTEM_TICK });
+
+ instance.onAction({ type: at.INIT });
+ instance._idleService = { idleTime: SYSTEM_TICK_INTERVAL + 1 };
+ clock.tick(SYSTEM_TICK_INTERVAL * 3);
+ instance.observe();
+ expectation.verify();
+ instance.onAction({ type: at.UNINIT });
+ });
+});
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..1606f98e94
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TelemetryFeed.test.js
@@ -0,0 +1,2606 @@
+/* global Services */
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.sys.mjs";
+import {
+ ASRouterEventPing,
+ BasePing,
+ ImpressionStatsPing,
+ SessionPing,
+ UserEventPing,
+} from "test/schemas/pings";
+import { FAKE_GLOBAL_PREFS, 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.sys.mjs";
+
+const FAKE_UUID = "{foo-123-foo}";
+const FAKE_ROUTER_MESSAGE_PROVIDER = [{ id: "cfr", enabled: true }];
+const FAKE_TELEMETRY_ID = "foo123";
+
+// eslint-disable-next-line max-statements
+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() {}
+ }
+
+ // Reset the global prefs before importing the `TelemetryFeed` module, to
+ // avoid a coverage miss caused by preference pollution when this test and
+ // `ActivityStream.test.js` are run together.
+ //
+ // The `TelemetryFeed` module defines a lazy `contextId` getter, which the
+ // `XPCOMUtils.defineLazyGetter` mock (defined in `unit-entry.js`) executes
+ // immediately, as soon as the module is imported.
+ //
+ // If this test runs first, there's no coverage miss: this test will load
+ // the `TelemetryFeed` module and run the lazy `contextId` getter, which will
+ // generate a fake context ID and store it in `FAKE_GLOBAL_PREFS`, covering
+ // all branches in the module. When `ActivityStream.test.js` runs, it'll load
+ // `TelemetryFeed` and run the lazy getter a second time, which will use the
+ // existing fake context ID from `FAKE_GLOBAL_PREFS` instead of generating a
+ // new one.
+ //
+ // But, if `ActivityStream.test.js` runs first, then loading `TelemetryFeed` a
+ // second time as part of this test will use the existing fake context ID from
+ // `FAKE_GLOBAL_PREFS`, missing coverage for the branch to generate a new
+ // context ID.
+ FAKE_GLOBAL_PREFS.clear();
+
+ const {
+ TelemetryFeed,
+ USER_PREFS_ENCODING,
+ PREF_IMPRESSION_ID,
+ TELEMETRY_PREF,
+ EVENTS_TELEMETRY_PREF,
+ STRUCTURED_INGESTION_ENDPOINT_PREF,
+ } = injector({
+ "lib/UTEventReporting.sys.mjs": { 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.console, "error");
+ globals.set("AboutNewTab", {
+ newTabURLOverridden: false,
+ newTabURL: "",
+ });
+ globals.set("pktApi", {
+ isUserLoggedIn: () => true,
+ });
+ 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();
+ FAKE_GLOBAL_PREFS.clear();
+ 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", () => {
+ FAKE_GLOBAL_PREFS.set(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(() => {
+ FAKE_GLOBAL_PREFS.set(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(() => {
+ FAKE_GLOBAL_PREFS.set(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 two scalars for deletion-request", () => {
+ sandbox.spy(Services.telemetry, "scalarSet");
+
+ instance.init();
+
+ assert.calledTwice(Services.telemetry.scalarSet);
+
+ // impression_id
+ let [type, value] = Services.telemetry.scalarSet.firstCall.args;
+ assert.equal(type, "deletion.request.impression_id");
+ assert.equal(value, instance._impressionId);
+
+ // context_id
+ [type, value] = Services.telemetry.scalarSet.secondCall.args;
+ assert.equal(type, "deletion.request.context_id");
+ assert.equal(value, FAKE_UUID);
+ });
+ describe("#_beginObservingNewtabPingPrefs", () => {
+ it("should record initial metrics from newtab prefs", () => {
+ FAKE_GLOBAL_PREFS.set(
+ "browser.newtabpage.activity-stream.feeds.topsites",
+ true
+ );
+ FAKE_GLOBAL_PREFS.set(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ 3
+ );
+ FAKE_GLOBAL_PREFS.set(
+ "browser.topsites.blockedSponsors",
+ '["mozilla"]'
+ );
+
+ sandbox.spy(Glean.topsites.enabled, "set");
+ sandbox.spy(Glean.topsites.rows, "set");
+ sandbox.spy(Glean.newtab.blockedSponsors, "set");
+
+ instance = new TelemetryFeed();
+ instance.init();
+
+ assert.calledOnce(Glean.topsites.enabled.set);
+ assert.calledWith(Glean.topsites.enabled.set, true);
+ assert.calledOnce(Glean.topsites.rows.set);
+ assert.calledWith(Glean.topsites.rows.set, 3);
+ assert.calledOnce(Glean.newtab.blockedSponsors.set);
+ assert.calledWith(Glean.newtab.blockedSponsors.set, ["mozilla"]);
+ });
+
+ it("should not record blocked sponsor metrics when bad json string is passed", () => {
+ FAKE_GLOBAL_PREFS.set("browser.topsites.blockedSponsors", "BAD[JSON]");
+
+ sandbox.spy(Glean.newtab.blockedSponsors, "set");
+
+ instance = new TelemetryFeed();
+ instance.init();
+
+ assert.notCalled(Glean.newtab.blockedSponsors.set);
+ });
+
+ it("should record new metrics for newtab pref changes", () => {
+ FAKE_GLOBAL_PREFS.set(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ 3
+ );
+ FAKE_GLOBAL_PREFS.set("browser.topsites.blockedSponsors", "[]");
+ sandbox.spy(Glean.topsites.rows, "set");
+ sandbox.spy(Glean.newtab.blockedSponsors, "set");
+
+ instance = new TelemetryFeed();
+ instance.init();
+
+ Services.prefs.setIntPref(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ 2
+ );
+
+ Services.prefs.setStringPref(
+ "browser.topsites.blockedSponsors",
+ '["mozilla"]'
+ );
+
+ assert.calledTwice(Glean.topsites.rows.set);
+ assert.calledWith(Glean.topsites.rows.set.firstCall, 3);
+ assert.calledWith(Glean.topsites.rows.set.secondCall, 2);
+ assert.calledWith(Glean.newtab.blockedSponsors.set.firstCall, []);
+ assert.calledWith(Glean.newtab.blockedSponsors.set.secondCall, [
+ "mozilla",
+ ]);
+ });
+ it("should ignore changes to other prefs", () => {
+ FAKE_GLOBAL_PREFS.set("some.other.pref", 123);
+ FAKE_GLOBAL_PREFS.set(
+ "browser.newtabpage.activity-stream.impressionId",
+ "{foo-123-foo}"
+ );
+
+ instance = new TelemetryFeed();
+ instance.init();
+
+ Services.prefs.setIntPref("some.other.pref", 456);
+ Services.prefs.setCharPref(
+ "browser.newtabpage.activity-stream.impressionId",
+ "{foo-456-foo}"
+ );
+ });
+ });
+ });
+ 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(Services.uuid, "generateUUID");
+
+ const session = instance.addSession("foo");
+
+ assert.calledOnce(Services.uuid.generateUUID);
+ assert.equal(
+ session.session_id,
+ Services.uuid.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", () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, true);
+ FAKE_GLOBAL_PREFS.set(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(() => {
+ for (const pref of Object.keys(USER_PREFS_ENCODING)) {
+ FAKE_GLOBAL_PREFS.set(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");
+ });
+ it("should use impression_id and bucket_id in Private Browsing", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ is_private: true,
+ 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 Private Browsing", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ is_private: true,
+ 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("#applyToastNotificationPolicy", () => {
+ it("should set client_id and set pingType", async () => {
+ const { ping, pingType } = await instance.applyToastNotificationPolicy(
+ {}
+ );
+
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.equal(pingType, "toast_notification");
+ });
+ });
+ describe("#applySpotlightPolicy", () => {
+ it("should set client_id and set pingType", async () => {
+ let pingData = { action: "foo" };
+ const { ping, pingType } = await instance.applySpotlightPolicy(pingData);
+
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.equal(pingType, "spotlight");
+ assert.notProperty(ping, "action");
+ });
+ });
+ 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.console.error);
+ 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 applySpotlightPolicy if action equals to spotlight_user_event", async () => {
+ const data = {
+ action: "spotlight_user_event",
+ event: "CLICK",
+ message_id: "SPOTLIGHT_MESSAGE_93",
+ };
+ sandbox.stub(instance, "applySpotlightPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applySpotlightPolicy);
+ });
+ it("should call applyToastNotificationPolicy if action equals to toast_notification_user_event", async () => {
+ const data = {
+ action: "toast_notification_user_event",
+ event: "IMPRESSION",
+ message_id: "TEST_TOAST_NOTIFICATION1",
+ };
+ sandbox.stub(instance, "applyToastNotificationPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyToastNotificationPolicy);
+ });
+ 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", () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, 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", () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, 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 () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, true);
+ FAKE_GLOBAL_PREFS.set(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 () => {
+ FAKE_GLOBAL_PREFS.set(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);
+ });
+ it("should record a Glean newtab.opened event with the correct visit_id when visibility event received", () => {
+ const session_id = "decafc0ffee";
+ const page = "about:newtab";
+ const session = { page, perf: {}, session_id };
+ const data = { visibility_event_rcvd_ts: 444455 };
+ sandbox.stub(instance.sessions, "get").returns(session);
+
+ sandbox.spy(Glean.newtab.opened, "record");
+ instance.saveSessionPerfData("port123", data);
+
+ assert.calledOnce(Glean.newtab.opened.record);
+ assert.deepEqual(Glean.newtab.opened.record.firstCall.args[0], {
+ newtab_visit_id: session_id,
+ source: page,
+ });
+ });
+ });
+ 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(() => {
+ FAKE_GLOBAL_PREFS.clear();
+ });
+ 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", () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, true);
+ FAKE_GLOBAL_PREFS.set(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);
+ });
+ it("should send an event on a DISCOVERY_STREAM_USER_EVENT action", () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, true);
+ FAKE_GLOBAL_PREFS.set(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.DISCOVERY_STREAM_USER_EVENT };
+
+ instance.onAction(action);
+
+ assert.calledWith(eventCreator, {
+ ...action,
+ data: {
+ value: {
+ pocket_logged_in_status: true,
+ },
+ },
+ });
+ 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`, () => {
+ FAKE_GLOBAL_PREFS.set(TELEMETRY_PREF, true);
+ FAKE_GLOBAL_PREFS.set(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
+ );
+ });
+ it("should call .handleTopSitesSponsoredImpressionStats on a TOP_SITES_SPONSORED_IMPRESSION_STATS action", () => {
+ const session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ const data = { type: "impression", tile_id: 42, position: 1 };
+ const action = { type: at.TOP_SITES_SPONSORED_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleTopSitesSponsoredImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ assert.calledOnce(instance.handleTopSitesSponsoredImpressionStats);
+ assert.deepEqual(
+ instance.handleTopSitesSponsoredImpressionStats.firstCall.args[0].data,
+ data
+ );
+ });
+ });
+ it("should call .handleTopSitesOrganicImpressionStats on a TOP_SITES_ORGANIC_IMPRESSION_STATS action", () => {
+ const session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ const data = { type: "impression", position: 1 };
+ const action = { type: at.TOP_SITES_ORGANIC_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleTopSitesOrganicImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ assert.calledOnce(instance.handleTopSitesOrganicImpressionStats);
+ assert.deepEqual(
+ instance.handleTopSitesOrganicImpressionStats.firstCall.args[0].data,
+ 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]};
+ sandbox.spy(Glean.newtab.newtabCategory, "set");
+ sandbox.spy(Glean.newtab.homepageCategory, "set");
+ });
+ 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);
+ assert.calledOnce(Glean.newtab.homepageCategory.set);
+ assert.calledWith(Glean.newtab.homepageCategory.set, "other");
+ });
+ 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);
+ assert.calledOnce(Glean.newtab.newtabCategory.set);
+ assert.calledWith(Glean.newtab.newtabCategory.set, "other");
+ });
+ 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);
+ assert.calledOnce(Glean.newtab.newtabCategory.set);
+ assert.calledOnce(Glean.newtab.homepageCategory.set);
+ assert.calledWith(Glean.newtab.newtabCategory.set, "enabled");
+ assert.calledWith(Glean.newtab.homepageCategory.set, "enabled");
+ });
+ 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);
+ assert.calledOnce(Glean.newtab.newtabCategory.set);
+ assert.calledOnce(Glean.newtab.homepageCategory.set);
+ assert.equal(Glean.newtab.newtabCategory.set.args[0], "extension");
+ assert.equal(Glean.newtab.homepageCategory.set.args[0], "extension");
+ });
+ it("instruments when newtab is disabled", async () => {
+ instance._prefs.set(TELEMETRY_PREF, true);
+ fakePrefs["browser.newtabpage.enabled"] = false;
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(Glean.newtab.newtabCategory.set);
+ assert.calledWith(Glean.newtab.newtabCategory.set, "disabled");
+ });
+ it("instruments when homepage is disabled", async () => {
+ instance._prefs.set(TELEMETRY_PREF, true);
+ fakeHomePage.overridden = true;
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(Glean.newtab.homepageCategory.set);
+ assert.calledWith(Glean.newtab.homepageCategory.set, "disabled");
+ });
+ it("should send a 'newtab' ping", async () => {
+ instance._prefs.set(TELEMETRY_PREF, true);
+ sandbox.spy(GleanPings.newtab, "submit");
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(GleanPings.newtab.submit);
+ assert.calledWithExactly(GleanPings.newtab.submit, "component_init");
+ });
+ });
+ 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 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ assert.equal(Object.keys(session.impressionSets).length, 1);
+ assert.deepEqual(session.impressionSets.foo, {
+ tiles: [{ id: 1, pos: 0 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ // Add another ping with the same source
+ instance.handleDiscoveryStreamImpressionStats("new_session", {
+ source: "foo",
+ tiles: [{ id: 2, pos: 1 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ assert.deepEqual(session.impressionSets.foo, {
+ tiles: [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ // Add another ping with a different source
+ instance.handleDiscoveryStreamImpressionStats("new_session", {
+ source: "bar",
+ tiles: [{ id: 3, pos: 2 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ assert.equal(Object.keys(session.impressionSets).length, 2);
+ assert.deepEqual(session.impressionSets.foo, {
+ tiles: [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+ assert.deepEqual(session.impressionSets.bar, {
+ tiles: [{ id: 3, pos: 2 }],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+ });
+ it("should instrument pocket impressions", () => {
+ const session_id = "1337cafe";
+ const pos1 = 1;
+ const pos2 = 4;
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.impression, "record");
+
+ instance.handleDiscoveryStreamImpressionStats("_", {
+ source: "foo",
+ tiles: [
+ { id: 1, pos: pos1, type: "organic" },
+ { id: 2, pos: pos2, type: "spoc" },
+ ],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ assert.calledTwice(Glean.pocket.impression.record);
+ assert.deepEqual(Glean.pocket.impression.record.firstCall.args[0], {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: pos1,
+ });
+ assert.deepEqual(Glean.pocket.impression.record.secondCall.args[0], {
+ newtab_visit_id: session_id,
+ is_sponsored: true,
+ position: pos2,
+ });
+ });
+ });
+ 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);
+ FAKE_GLOBAL_PREFS.set(STRUCTURED_INGESTION_ENDPOINT_PREF, fakeEndpoint);
+ sandbox.stub(Services.uuid, "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 call submitGleanPingForPing on known pingTypes when telemetry is enabled", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "IMPRESSION",
+ message_id: "12345",
+ };
+ instance = new TelemetryFeed();
+ instance._prefs.set(TELEMETRY_PREF, true);
+ sandbox.spy(
+ global.AboutWelcomeTelemetry.prototype,
+ "submitGleanPingForPing"
+ );
+
+ await instance.handleASRouterUserEvent({ data });
+
+ assert.calledOnce(
+ global.AboutWelcomeTelemetry.prototype.submitGleanPingForPing
+ );
+ });
+ it("should console.error and not submit pings 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.console.error);
+ assert.notCalled(instance.sendStructuredIngestionEvent);
+ });
+ });
+ describe("#isInCFRCohort", () => {
+ it("should return false if there is no CFR experiment registered", () => {
+ 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"
+ );
+ });
+ });
+ describe("#handleTopSitesSponsoredImpressionStats", () => {
+ it("should call sendStructuredIngestionEvent on an impression event", async () => {
+ const data = {
+ type: "impression",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+ sandbox.spy(Services.telemetry, "keyedScalarAdd");
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+
+ // Scalar should be added
+ assert.calledOnce(Services.telemetry.keyedScalarAdd);
+ assert.calledWith(
+ Services.telemetry.keyedScalarAdd,
+ "contextual.services.topsites.impression",
+ "newtab_1",
+ 1
+ );
+
+ assert.calledOnce(instance.sendStructuredIngestionEvent);
+
+ const { args } = instance.sendStructuredIngestionEvent.firstCall;
+ // payload
+ assert.deepEqual(args[0], {
+ context_id: FAKE_UUID,
+ tile_id: 42,
+ source: "newtab",
+ position: 1,
+ reporting_url: "https://test.reporting.net/",
+ });
+ // namespace
+ assert.equal(args[1], "contextual-services");
+ // docType
+ assert.equal(args[2], "topsites-impression");
+ // version
+ assert.equal(args[3], "1");
+ });
+ it("should call sendStructuredIngestionEvent on a click event", async () => {
+ const data = {
+ type: "click",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+ sandbox.spy(Services.telemetry, "keyedScalarAdd");
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+
+ // Scalar should be added
+ assert.calledOnce(Services.telemetry.keyedScalarAdd);
+ assert.calledWith(
+ Services.telemetry.keyedScalarAdd,
+ "contextual.services.topsites.click",
+ "newtab_1",
+ 1
+ );
+
+ assert.calledOnce(instance.sendStructuredIngestionEvent);
+
+ const { args } = instance.sendStructuredIngestionEvent.firstCall;
+ // payload
+ assert.deepEqual(args[0], {
+ context_id: FAKE_UUID,
+ tile_id: 42,
+ source: "newtab",
+ position: 1,
+ reporting_url: "https://test.reporting.net/",
+ });
+ // namespace
+ assert.equal(args[1], "contextual-services");
+ // docType
+ assert.equal(args[2], "topsites-click");
+ // version
+ assert.equal(args[3], "1");
+ });
+ it("should record a Glean topsites.impression event on an impression event", async () => {
+ const data = {
+ type: "impression",
+ tile_id: 42,
+ source: "newtab",
+ position: 1,
+ reporting_url: "https://test.reporting.net/",
+ advertiser: "adnoid ads",
+ };
+ instance = new TelemetryFeed();
+ const session_id = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.topsites.impression, "record");
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+
+ // Event should be recorded
+ assert.calledOnce(Glean.topsites.impression.record);
+ assert.calledWith(Glean.topsites.impression.record, {
+ advertiser_name: "adnoid ads",
+ tile_id: "42",
+ newtab_visit_id: session_id,
+ is_sponsored: true,
+ position: 1,
+ });
+ });
+ it("should record a Glean topsites.click event on a click event", async () => {
+ const data = {
+ type: "click",
+ advertiser: "test advertiser",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ instance = new TelemetryFeed();
+ const session_id = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.topsites.click, "record");
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+
+ // Event should be recorded
+ assert.calledOnce(Glean.topsites.click.record);
+ assert.calledWith(Glean.topsites.click.record, {
+ advertiser_name: "test advertiser",
+ tile_id: "42",
+ newtab_visit_id: session_id,
+ is_sponsored: true,
+ position: 0,
+ });
+ });
+ it("should console.error on unknown pingTypes", async () => {
+ const data = { type: "unknown_type" };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+
+ assert.calledOnce(global.console.error);
+ assert.notCalled(instance.sendStructuredIngestionEvent);
+ });
+ });
+ describe("#handleTopSitesOrganicImpressionStats", () => {
+ it("should record a Glean topsites.impression event on an impression event", async () => {
+ const data = {
+ type: "impression",
+ source: "newtab",
+ position: 0,
+ };
+ instance = new TelemetryFeed();
+ const session_id = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.topsites.impression, "record");
+
+ await instance.handleTopSitesOrganicImpressionStats({ data });
+
+ assert.calledOnce(Glean.topsites.impression.record);
+ assert.calledWith(Glean.topsites.impression.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: 0,
+ });
+ });
+ it("should record a Glean topsites.click event on a click event", async () => {
+ const data = {
+ type: "click",
+ source: "newtab",
+ position: 0,
+ };
+ instance = new TelemetryFeed();
+ const session_id = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.topsites.click, "record");
+
+ await instance.handleTopSitesOrganicImpressionStats({ data });
+
+ assert.calledOnce(Glean.topsites.click.record);
+ assert.calledWith(Glean.topsites.click.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: 0,
+ });
+ });
+ });
+ describe("#handleDiscoveryStreamUserEvent", () => {
+ it("correctly handles action with no `data`", () => {
+ const action = ac.DiscoveryStreamUserEvent();
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+ sandbox.spy(Glean.pocket.click, "record");
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.notCalled(Glean.pocket.topicClick.record);
+ assert.notCalled(Glean.pocket.click.record);
+ assert.notCalled(Glean.pocket.save.record);
+ });
+ it("correctly handles CLICK data with no value", () => {
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.topicClick.record);
+ assert.calledWith(Glean.pocket.topicClick.record, {
+ newtab_visit_id: session_id,
+ topic: undefined,
+ });
+ });
+ it("correctly handles non-POPULAR_TOPICS CLICK data with no value", () => {
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+ sandbox.spy(Glean.pocket.click, "record");
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.notCalled(Glean.pocket.topicClick.record);
+ assert.notCalled(Glean.pocket.click.record);
+ assert.notCalled(Glean.pocket.save.record);
+ });
+ it("correctly handles CLICK data with non-POPULAR_TOPICS source", () => {
+ const topic = "atopic";
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ value: {
+ card_type: "topics_widget",
+ topic,
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.topicClick.record);
+ assert.calledWith(Glean.pocket.topicClick.record, {
+ newtab_visit_id: session_id,
+ topic,
+ });
+ });
+ it("doesn't instrument a CLICK without a card_type", () => {
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ value: {
+ card_type: "not spoc, organic, or topics_widget",
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+ sandbox.spy(Glean.pocket.click, "record");
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.notCalled(Glean.pocket.topicClick.record);
+ assert.notCalled(Glean.pocket.click.record);
+ assert.notCalled(Glean.pocket.save.record);
+ });
+ it("instruments a popular topic click", () => {
+ const topic = "entertainment";
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ value: {
+ card_type: "topics_widget",
+ topic,
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.topicClick, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.topicClick.record);
+ assert.calledWith(Glean.pocket.topicClick.record, {
+ newtab_visit_id: session_id,
+ topic,
+ });
+ });
+ it("instruments an organic top stories click", () => {
+ const action_position = 42;
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ action_position,
+ value: {
+ card_type: "organic",
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.click, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.click.record);
+ assert.calledWith(Glean.pocket.click.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: action_position,
+ });
+ });
+ it("instruments a sponsored top stories click", () => {
+ const action_position = 42;
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ action_position,
+ value: {
+ card_type: "spoc",
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.click, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.click.record);
+ assert.calledWith(Glean.pocket.click.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: true,
+ position: action_position,
+ });
+ });
+ it("instruments a save of an organic top story", () => {
+ const action_position = 42;
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position,
+ value: {
+ card_type: "organic",
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.save.record);
+ assert.calledWith(Glean.pocket.save.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: action_position,
+ });
+ });
+ it("instruments a save of a sponsored top story", () => {
+ const action_position = 42;
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position,
+ value: {
+ card_type: "spoc",
+ },
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.save.record);
+ assert.calledWith(Glean.pocket.save.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: true,
+ position: action_position,
+ });
+ });
+ it("instruments a save of a sponsored top story, without `value`", () => {
+ const action_position = 42;
+ const action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position,
+ });
+ instance = new TelemetryFeed();
+ const session_id = "c0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id });
+ sandbox.spy(Glean.pocket.save, "record");
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ assert.calledOnce(Glean.pocket.save.record);
+ assert.calledWith(Glean.pocket.save.record, {
+ newtab_visit_id: session_id,
+ is_sponsored: false,
+ position: action_position,
+ });
+ });
+ });
+});
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..661a6b7b83
--- /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.sys.mjs";
+
+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..12e70557f6
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js
@@ -0,0 +1,649 @@
+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..36fcc0cbe3
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js
@@ -0,0 +1,934 @@
+import { _ToolbarPanelHub } from "lib/ToolbarPanelHub.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
+import { PanelTestProvider } from "lib/PanelTestProvider.sys.mjs";
+
+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.equal(fakeElementById.hidden, false);
+ });
+ it("should hide appmenu button on _hideAppmenuButton()", () => {
+ instance._hideAppmenuButton(fakeWindow);
+ assert.equal(fakeElementById.hidden, true);
+ });
+ it("should not do anything if the window is closed", () => {
+ instance._hideAppmenuButton(fakeWindow, true);
+ assert.notCalled(global.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.equal(fakeElementById.hidden, false);
+ });
+ it("should hide toolbar button on _hideToolbarButton()", () => {
+ instance._hideToolbarButton(fakeWindow);
+ assert.equal(fakeElementById.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()).find(
+ m => m.template === "whatsnew_panel_message"
+ );
+ 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);
+ });
+ it("should exit gracefully if called before a browser exists", () => {
+ instance.forceShowMessage(null, messages);
+ assert.neverCalledWith(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.console, "error");
+
+ await fakeInsert();
+
+ eventListeners.mouseup();
+
+ assert.calledOnce(stub);
+ assert.calledOnce(global.console.error);
+ 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..a173c16cde
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TopSitesFeed.test.js
@@ -0,0 +1,3020 @@
+"use strict";
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { FAKE_GLOBAL_PREFS, FakePrefs, GlobalOverrider } from "test/unit/utils";
+import {
+ insertPinned,
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "common/Reducers.sys.mjs";
+import { getDefaultOptions } from "lib/ActivityStreamStorage.jsm";
+import injector from "inject!lib/TopSitesFeed.jsm";
+import { Screenshots } from "lib/Screenshots.jsm";
+import { LinksCache } from "lib/LinksCache.sys.mjs";
+
+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";
+const SHOW_SPONSORED_PREF = "showSponsoredTopSites";
+const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+const REMOTE_SETTING_DEFAULTS_PREF = "browser.topsites.useRemoteSetting";
+const CONTILE_CACHE_PREF = "browser.topsites.contile.cachedTiles";
+const CONTILE_CACHE_VALID_FOR_PREF = "browser.topsites.contile.cacheValidFor";
+const CONTILE_CACHE_LAST_FETCH_PREF = "browser.topsites.contile.lastFetch";
+
+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;
+ let fetchStub;
+ let fakeNimbusFeatures;
+ let fakeSampling;
+
+ 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 = {
+ filter: sinon.stub().returnsArg(0),
+ };
+ shortURLStub = sinon
+ .stub()
+ .callsFake(site =>
+ site.url.replace(/(.com|.ca)/, "").replace("https://", "")
+ );
+ const fakeDedupe = function () {};
+ fakePageThumbs = {
+ addExpirationFilter: sinon.stub(),
+ removeExpirationFilter: sinon.stub(),
+ };
+ fakeNimbusFeatures = {
+ newtab: {
+ getVariable: sinon.stub(),
+ onUpdate: sinon.stub(),
+ offUpdate: sinon.stub(),
+ },
+ pocketNewtab: {
+ getVariable: sinon.stub(),
+ },
+ };
+ fakeSampling = {
+ ratioSample: sinon.stub(),
+ };
+ globals.set({
+ PageThumbs: fakePageThumbs,
+ NewTabUtils: fakeNewTabUtils,
+ gFilterAdultEnabled: false,
+ NimbusFeatures: fakeNimbusFeatures,
+ LinksCache,
+ FilterAdult: filterAdultStub,
+ Screenshots: fakeScreenshot,
+ Sampling: fakeSampling,
+ });
+ sandbox.spy(global.XPCOMUtils, "defineLazyGetter");
+ FAKE_GLOBAL_PREFS.set("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.sys.mjs": {
+ 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: { 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 log, contextId, and _currentSearchHostname", () => {
+ assert.calledThrice(global.XPCOMUtils.defineLazyGetter);
+
+ let spyCall = global.XPCOMUtils.defineLazyGetter.getCall(0);
+ assert.ok(spyCall.calledWith(sinon.match.any, "log", sinon.match.func));
+
+ spyCall = global.XPCOMUtils.defineLazyGetter.getCall(1);
+ assert.ok(
+ spyCall.calledWith(sinon.match.any, "contextId", sinon.match.func)
+ );
+
+ spyCall = global.XPCOMUtils.defineLazyGetter.getCall(2);
+ assert.ok(
+ spyCall.calledWith(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 filter out non-pinned adult sites", async () => {
+ filterAdultStub.filter = sinon.stub().returns([]);
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+
+ const result = await feed.getLinksWithDefaults();
+
+ // The stub filters out everything
+ assert.calledOnce(filterAdultStub.filter);
+ 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("discoverystream", () => {
+ let makeStreamData = index => ({
+ layout: [
+ {
+ components: [
+ {
+ placement: {
+ name: "sponsored-topsites",
+ },
+ spocs: {
+ positions: [{ index }],
+ },
+ },
+ ],
+ },
+ ],
+ spocs: {
+ data: {
+ "sponsored-topsites": {
+ items: [{ title: "test spoc", url: "https://test-spoc.com" }],
+ },
+ },
+ },
+ });
+ it("should add a sponsored topsite from discoverystream to all the valid indices", async () => {
+ for (let i = 0; i < FAKE_LINKS.length; i++) {
+ feed.store.state.DiscoveryStream = makeStreamData(i);
+ const result = await feed.getLinksWithDefaults();
+ const link = result[i];
+
+ assert.equal(link.type, "SPOC");
+ assert.equal(link.title, "test spoc");
+ assert.equal(link.sponsored_position, i + 1);
+ assert.equal(link.hostname, "test-spoc");
+ assert.equal(link.url, "https://test-spoc.com");
+ }
+ });
+ });
+ });
+ 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");
+ });
+ it("should call onUpdate to set up Nimbus update listener", async () => {
+ await feed.init();
+
+ assert.calledOnce(fakeNimbusFeatures.newtab.onUpdate);
+ });
+ });
+ 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.console, "error");
+
+ try {
+ await feed.refresh({ broadcast: false });
+ } catch (e) {
+ assert.fails();
+ }
+
+ assert.calledOnce(console.error);
+ });
+ });
+ 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_LINKS_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);
+ });
+ it("should refresh from Contile on SHOW_SPONSORED_PREF if Contile is enabled", () => {
+ sandbox.spy(feed._contile, "refresh");
+ const prefChangeAction = {
+ type: at.PREF_CHANGED,
+ data: { name: SHOW_SPONSORED_PREF },
+ };
+ fakeNimbusFeatures.newtab.getVariable.returns(true);
+ feed.onAction(prefChangeAction);
+
+ assert.calledOnce(feed._contile.refresh);
+ });
+ it("should not refresh from Contile on SHOW_SPONSORED_PREF if Contile is disabled", () => {
+ sandbox.spy(feed._contile, "refresh");
+ const prefChangeAction = {
+ type: at.PREF_CHANGED,
+ data: { name: SHOW_SPONSORED_PREF },
+ };
+ fakeNimbusFeatures.newtab.getVariable.returns(false);
+ feed.onAction(prefChangeAction);
+
+ assert.notCalled(feed._contile.refresh);
+ });
+ it("should reset Contile cache prefs when SHOW_SPONSORED_PREF is false", () => {
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, "[]");
+ Services.prefs.setIntPref(CONTILE_CACHE_LAST_FETCH_PREF, 15 * 60 * 1000);
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_PREF, Date.now());
+
+ sandbox.spy(feed._contile, "refresh");
+ const prefChangeAction = {
+ type: at.PREF_CHANGED,
+ data: { name: SHOW_SPONSORED_PREF, value: false },
+ };
+ fakeNimbusFeatures.newtab.getVariable.returns(true);
+ feed.onAction(prefChangeAction);
+
+ assert.calledOnce(feed._contile.refresh);
+
+ // cached pref values should have reset
+ assert.isUndefined(Services.prefs.getStringPref(CONTILE_CACHE_PREF));
+ assert.isUndefined(
+ Services.prefs.getIntPref(CONTILE_CACHE_LAST_FETCH_PREF)
+ );
+ assert.isUndefined(
+ Services.prefs.getIntPref(CONTILE_CACHE_VALID_FOR_PREF)
+ );
+ });
+ });
+ 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");
+ });
+ });
+
+ describe("#ContileIntegration", () => {
+ let getStringPrefStub;
+ let getIntPrefStub;
+ beforeEach(() => {
+ // Turn on sponsored TopSites for testing
+ feed.store.state.Prefs.values[SHOW_SPONSORED_PREF] = true;
+ fetchStub = sandbox.stub();
+ globals.set("fetch", fetchStub);
+
+ getStringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+ getStringPrefStub
+ .withArgs(TOP_SITES_BLOCKED_SPONSORS_PREF)
+ .returns(`["foo","bar"]`);
+
+ getIntPrefStub = sandbox.stub(global.Services.prefs, "getIntPref");
+
+ fakeNimbusFeatures.newtab.getVariable.returns(true);
+ sandbox.spy(global.Services.prefs, "setStringPref");
+ sandbox.spy(global.Services.prefs, "setIntPref");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should fetch sites from Contile", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://www.test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ assert.equal(feed._contile.sites.length, 2);
+ });
+
+ it("should fetch SOV (Share-of-Voice) settings from Contile", async () => {
+ const sov = {
+ name: "SOV-20230518215316",
+ allocations: [
+ {
+ position: 1,
+ allocation: [
+ {
+ partner: "foo",
+ percentage: 100,
+ },
+ {
+ partner: "bar",
+ percentage: 0,
+ },
+ ],
+ },
+ {
+ position: 2,
+ allocation: [
+ {
+ partner: "foo",
+ percentage: 80,
+ },
+ {
+ partner: "bar",
+ percentage: 20,
+ },
+ ],
+ },
+ ],
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ sov: btoa(JSON.stringify(sov)),
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://www.test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ assert.deepEqual(feed._contile.sov, sov);
+ assert.equal(feed._contile.sites.length, 2);
+ });
+
+ it("should not fetch from Contile if it's not enabled", async () => {
+ fakeNimbusFeatures.newtab.getVariable.reset();
+ fakeNimbusFeatures.newtab.getVariable.returns(false);
+ const fetched = await feed._contile._fetchSites();
+
+ assert.notCalled(fetchStub);
+ assert.ok(!fetched);
+ assert.equal(feed._contile.sites.length, 0);
+ });
+
+ it("should still return two tiles when Contile provides more than 2 tiles and filtering results in more than 2 tiles", async () => {
+ fakeNimbusFeatures.newtab.getVariable.reset();
+ fakeNimbusFeatures.newtab.getVariable.onCall(0).returns(true);
+ fakeNimbusFeatures.newtab.getVariable.onCall(1).returns(true);
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://foo.com",
+ image_url: "images/foo-com.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://bar.com",
+ image_url: "images/bar-com.png",
+ click_url: "https://www.bar-click.com",
+ impression_url: "https://www.bar-impression.com",
+ name: "bar",
+ },
+ {
+ url: "https://test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ {
+ url: "https://test2.com",
+ image_url: "images/test2-com.png",
+ click_url: "https://www.test2-click.com",
+ impression_url: "https://www.test2-impression.com",
+ name: "test2",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ // Both "foo" and "bar" should be filtered
+ assert.equal(feed._contile.sites.length, 2);
+ assert.equal(feed._contile.sites[0].url, "https://www.test.com");
+ assert.equal(feed._contile.sites[1].url, "https://test1.com");
+ });
+
+ it("should still return two tiles with replacement if the Nimbus variable was unset", async () => {
+ fakeNimbusFeatures.newtab.getVariable.reset();
+ fakeNimbusFeatures.newtab.getVariable.onCall(0).returns(true);
+ fakeNimbusFeatures.newtab.getVariable.onCall(1).returns(undefined);
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://foo.com",
+ image_url: "images/foo-com.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ assert.equal(feed._contile.sites.length, 2);
+ assert.equal(feed._contile.sites[0].url, "https://www.test.com");
+ assert.equal(feed._contile.sites[1].url, "https://test1.com");
+ });
+
+ it("should filter the blocked sponsors", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://foo.com",
+ image_url: "images/foo-com.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://bar.com",
+ image_url: "images/bar-com.png",
+ click_url: "https://www.bar-click.com",
+ impression_url: "https://www.bar-impression.com",
+ name: "bar",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ // Both "foo" and "bar" should be filtered
+ assert.equal(feed._contile.sites.length, 1);
+ assert.equal(feed._contile.sites[0].url, "https://www.test.com");
+ });
+
+ it("should return false when Contile returns with error status and no values are stored in cache prefs", async () => {
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(!fetched);
+ assert.ok(!feed._contile.sites.length);
+ });
+
+ it("should return false when Contile returns with error status and cached tiles are expried", async () => {
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_VALID_FOR_PREF)
+ .returns(1000 * 60 * 15);
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_LAST_FETCH_PREF)
+ .returns(Date.now() - 1000 * 60 * 30);
+
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(!fetched);
+ assert.ok(!feed._contile.sites.length);
+ });
+
+ it("should handle invalid payload properly from Contile", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ unknown: [],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(!fetched);
+ assert.ok(!feed._contile.sites.length);
+ });
+
+ it("should handle empty payload properly from Contile", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ assert.ok(!feed._contile.sites.length);
+ });
+
+ it("should handle no content properly from Contile", async () => {
+ fetchStub.resolves({ ok: true, status: 204 });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(!fetched);
+ assert.ok(!feed._contile.sites.length);
+ });
+
+ it("should set Caching Prefs after a sucessful request", async () => {
+ const tiles = [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://www.test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ];
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles,
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ assert.ok(fetched);
+ assert.calledOnce(Services.prefs.setStringPref);
+ assert.calledTwice(Services.prefs.setIntPref);
+
+ assert.calledWith(
+ Services.prefs.setStringPref,
+ CONTILE_CACHE_PREF,
+ JSON.stringify(tiles)
+ );
+ assert.calledWith(
+ Services.prefs.setIntPref,
+ CONTILE_CACHE_VALID_FOR_PREF,
+ 11322
+ );
+ });
+
+ it("should return cached valid tiles when Contile returns error status", async () => {
+ const tiles = [
+ {
+ url: "https://www.test-cached.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://www.test1-cached.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ];
+
+ getStringPrefStub
+ .withArgs(CONTILE_CACHE_PREF)
+ .returns(JSON.stringify(tiles));
+
+ // valid for 15 mins
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_VALID_FOR_PREF)
+ .returns(1000 * 60 * 15);
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_LAST_FETCH_PREF)
+ .returns(Date.now());
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ assert.ok(fetched);
+ assert.equal(feed._contile.sites.length, 2);
+ assert.equal(feed._contile.sites[0].url, "https://www.test-cached.com");
+ assert.equal(feed._contile.sites[1].url, "https://www.test1-cached.com");
+ });
+
+ it("should not be successful when contile returns an error and no valid tiles are cached", async () => {
+ getStringPrefStub.withArgs(CONTILE_CACHE_PREF).returns("[]");
+
+ getIntPrefStub.withArgs(CONTILE_CACHE_VALID_FOR_PREF).returns(0);
+ getIntPrefStub.withArgs(CONTILE_CACHE_LAST_FETCH_PREF).returns(0);
+
+ fetchStub.resolves({
+ status: 500,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ assert.ok(!fetched);
+ });
+
+ it("should return cached valid tiles filtering blocked tiles when Contile returns error status", async () => {
+ const tiles = [
+ {
+ url: "https://foo.com",
+ image_url: "images/foo-com.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.test1-cached.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ];
+ getStringPrefStub
+ .withArgs(CONTILE_CACHE_PREF)
+ .returns(JSON.stringify(tiles));
+
+ // valid for 15 mins
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_VALID_FOR_PREF)
+ .returns(1000 * 60 * 15);
+ getIntPrefStub
+ .withArgs(CONTILE_CACHE_LAST_FETCH_PREF)
+ .returns(Date.now());
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ assert.ok(fetched);
+ assert.equal(feed._contile.sites.length, 1);
+ assert.equal(feed._contile.sites[0].url, "https://www.test1-cached.com");
+ });
+
+ it("should still return 3 tiles when nimbus variable overrides max num of sponsored contile tiles", async () => {
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(3);
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ {
+ url: "https://test2.com",
+ image_url: "images/test2-com.png",
+ click_url: "https://www.test2-click.com",
+ impression_url: "https://www.test2-impression.com",
+ name: "test2",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+
+ assert.ok(fetched);
+ assert.equal(feed._contile.sites.length, 3);
+ assert.equal(feed._contile.sites[0].url, "https://www.test.com");
+ assert.equal(feed._contile.sites[1].url, "https://test1.com");
+ assert.equal(feed._contile.sites[2].url, "https://test2.com");
+ });
+ });
+
+ describe("#_mergeSponsoredLinks", () => {
+ let fakeSponsoredLinks;
+ let sov;
+ beforeEach(() => {
+ fakeSponsoredLinks = {
+ amp: [
+ {
+ url: "https://www.test.com",
+ image_url: "images/test-com.png",
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ partner: "amp",
+ sponsored_position: 1,
+ },
+ {
+ url: "https://www.test1.com",
+ image_url: "images/test1-com.png",
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ partner: "amp",
+ sponsored_position: 2,
+ },
+ {
+ url: "https://www.test2.com",
+ image_url: "images/test2-com.png",
+ click_url: "https://www.test2-click.com",
+ impression_url: "https://www.test2-impression.com",
+ name: "test2",
+ partner: "amp",
+ sponsored_position: 2,
+ },
+ ],
+ "moz-sales": [
+ {
+ url: "https://foo.com",
+ image_url: "images/foo-com.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ partner: "moz-sales",
+ pos: 2,
+ },
+ ],
+ };
+
+ sov = {
+ name: "SOV-20230518215316",
+ allocations: [
+ {
+ position: 1,
+ allocation: [
+ {
+ partner: "amp",
+ percentage: 100,
+ },
+ {
+ partner: "moz-sales",
+ percentage: 0,
+ },
+ ],
+ },
+ {
+ position: 2,
+ allocation: [
+ {
+ partner: "amp",
+ percentage: 80,
+ },
+ {
+ partner: "moz-sales",
+ percentage: 20,
+ },
+ ],
+ },
+ ],
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should join sponsored links if the sov object is absent", async () => {
+ sandbox.stub(feed._contile, "sov").get(() => null);
+
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.deepEqual(sponsored, Object.values(fakeSponsoredLinks).flat());
+ });
+
+ it("should join sponosred links if the SOV Nimbus variable is disabled", async () => {
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(false);
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.deepEqual(sponsored, Object.values(fakeSponsoredLinks).flat());
+ });
+
+ it("should pick sponsored links based on sov configurations", async () => {
+ sandbox.stub(feed._contile, "sov").get(() => sov);
+ fakeNimbusFeatures.pocketNewtab.getVariable.reset();
+ fakeNimbusFeatures.pocketNewtab.getVariable.onCall(0).returns(true);
+ fakeNimbusFeatures.pocketNewtab.getVariable.onCall(1).returns(undefined);
+ global.Sampling.ratioSample.onCall(0).resolves(0);
+ global.Sampling.ratioSample.onCall(1).resolves(1);
+
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.equal(sponsored.length, 2);
+ assert.equal(sponsored[0].partner, "amp");
+ assert.equal(sponsored[0].sponsored_position, 1);
+ assert.equal(sponsored[1].partner, "moz-sales");
+ assert.equal(sponsored[1].sponsored_position, 2);
+ assert.equal(sponsored[1].pos, 1);
+ });
+
+ it("should add remaining contile tiles when nimbus var contile max num sponsored is present", async () => {
+ sandbox.stub(feed._contile, "sov").get(() => sov);
+ fakeNimbusFeatures.pocketNewtab.getVariable.reset();
+ fakeNimbusFeatures.pocketNewtab.getVariable.onCall(0).returns(true);
+ fakeNimbusFeatures.pocketNewtab.getVariable.onCall(1).returns(3);
+ global.Sampling.ratioSample.resolves(0);
+
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.equal(sponsored.length, 3);
+ });
+
+ it("should fall back to other partners if the chosen partner does not have any links", async () => {
+ sandbox.stub(feed._contile, "sov").get(() => sov);
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(true);
+ global.Sampling.ratioSample.onCall(0).resolves(0);
+ global.Sampling.ratioSample.onCall(1).resolves(0);
+
+ fakeSponsoredLinks.amp = [];
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.equal(sponsored.length, 1);
+ assert.equal(sponsored[0].partner, "moz-sales");
+ assert.equal(sponsored[0].sponsored_position, 1);
+ assert.equal(sponsored[0].pos, 0);
+ });
+
+ it("should return an empty array if none of the partners have links", async () => {
+ sandbox.stub(feed._contile, "sov").get(() => sov);
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(true);
+ global.Sampling.ratioSample.onCall(0).resolves(0);
+ global.Sampling.ratioSample.onCall(1).resolves(0);
+
+ fakeSponsoredLinks.amp = [];
+ fakeSponsoredLinks["moz-sales"] = [];
+ const sponsored = await feed._mergeSponsoredLinks(fakeSponsoredLinks);
+
+ assert.equal(sponsored.length, 0);
+ });
+ });
+
+ describe("#_readDefaults", () => {
+ beforeEach(() => {
+ // Turn on sponsored TopSites for testing
+ feed.store.state.Prefs.values[SHOW_SPONSORED_PREF] = true;
+ fetchStub = sandbox.stub();
+ globals.set("fetch", fetchStub);
+ fetchStub.resolves({ ok: true, status: 204 });
+ sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .withArgs(REMOTE_SETTING_DEFAULTS_PREF)
+ .returns(true);
+
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(TOP_SITES_BLOCKED_SPONSORS_PREF)
+ .returns(`["foo","bar"]`);
+ sandbox.stub(global.Services.prefs, "prefIsLocked").returns(false);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should filter all blocked sponsored tiles from RemoteSettings when Contile is disabled", async () => {
+ sandbox.stub(feed, "_getRemoteConfig").resolves([
+ { url: "https://foo.com", title: "foo", sponsored_position: 1 },
+ { url: "https://bar.com", title: "bar", sponsored_position: 2 },
+ { url: "https://test.com", title: "test", sponsored_position: 3 },
+ ]);
+ fakeNimbusFeatures.newtab.getVariable.returns(false);
+ await feed._readDefaults();
+
+ assert.equal(DEFAULT_TOP_SITES.length, 1);
+ assert.equal(DEFAULT_TOP_SITES[0].label, "test");
+ });
+
+ it("should also filter all blocked sponsored tiles from RemoteSettings when Contile is enabled", async () => {
+ sandbox.stub(feed, "_getRemoteConfig").resolves([
+ { url: "https://foo.com", title: "foo", sponsored_position: 1 },
+ { url: "https://bar.com", title: "bar", sponsored_position: 2 },
+ { url: "https://test.com", title: "test", sponsored_position: 3 },
+ ]);
+ fakeNimbusFeatures.newtab.getVariable.returns(true);
+
+ await feed._readDefaults();
+
+ assert.equal(DEFAULT_TOP_SITES.length, 1);
+ assert.equal(DEFAULT_TOP_SITES[0].label, "test");
+ });
+
+ it("should not filter non-sponsored tiles from RemoteSettings", async () => {
+ sandbox.stub(feed, "_getRemoteConfig").resolves([
+ { url: "https://foo.com", title: "foo", sponsored_position: 1 },
+ { url: "https://bar.com", title: "bar", sponsored_position: 2 },
+ { url: "https://foo.com", title: "foo" },
+ ]);
+
+ await feed._readDefaults();
+
+ assert.equal(DEFAULT_TOP_SITES.length, 1);
+ assert.equal(DEFAULT_TOP_SITES[0].label, "foo");
+ });
+
+ it("should take the image from Contile if it's a hi-res one", async () => {
+ fakeNimbusFeatures.newtab.getVariable.returns(true);
+ sandbox.stub(feed, "_getRemoteConfig").resolves([]);
+
+ sandbox.stub(feed._contile, "sites").get(() => [
+ {
+ url: "https://test.com",
+ image_url: "https://images.test.com/test-com.png",
+ image_size: 192,
+ click_url: "https://www.test-click.com",
+ impression_url: "https://www.test-impression.com",
+ name: "test",
+ },
+ {
+ url: "https://test1.com",
+ image_url: "https://images.test1.com/test1-com.png",
+ image_size: 32,
+ click_url: "https://www.test1-click.com",
+ impression_url: "https://www.test1-impression.com",
+ name: "test1",
+ },
+ ]);
+
+ await feed._readDefaults();
+
+ const [site1, site2] = DEFAULT_TOP_SITES;
+ assert.propertyVal(
+ site1,
+ "favicon",
+ "https://images.test.com/test-com.png"
+ );
+ assert.propertyVal(site1, "faviconSize", 192);
+
+ // Should not be taken as it's not hi-res
+ assert.isUndefined(site2.favicon);
+ assert.isUndefined(site2.faviconSize);
+ });
+ });
+
+ describe("#_nimbusChangeListener", () => {
+ it("should refresh on Nimbus feature updates reasons", () => {
+ sandbox.spy(feed._contile, "refresh");
+ feed._nimbusChangeListener(null, "experiment-updated");
+
+ assert.calledOnce(feed._contile.refresh);
+ });
+
+ it("should not refresh on Nimbus feature loaded reasons", () => {
+ sandbox.spy(feed._contile, "refresh");
+ feed._nimbusChangeListener(null, "feature-experiment-loaded");
+ feed._nimbusChangeListener(null, "feature-rollout-loaded");
+
+ assert.notCalled(feed._contile.refresh);
+ });
+ });
+
+ describe("#_maybeCapSponsoredLinks", () => {
+ let sponsoredLinks;
+
+ beforeEach(() => {
+ sponsoredLinks = [
+ {
+ url: "https://www.test.com",
+ name: "test",
+ sponsored_position: 1,
+ },
+ {
+ url: "https://www.test1.com",
+ name: "test1",
+ sponsored_position: 2,
+ },
+ {
+ url: "https://www.test2.com",
+ name: "test2",
+ sponsored_position: 3,
+ },
+ ];
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should fall back to the default if the Nimbus variable is unspecified", () => {
+ feed._maybeCapSponsoredLinks(sponsoredLinks);
+
+ assert.equal(sponsoredLinks.length, 2);
+ });
+ it("should cap the links if specified by the Nimbus variable", () => {
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(1);
+
+ feed._maybeCapSponsoredLinks(sponsoredLinks);
+
+ assert.equal(sponsoredLinks.length, 1);
+ });
+ it("should leave all the links if the Nimbus variable is equal to what we have", () => {
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(3);
+
+ feed._maybeCapSponsoredLinks(sponsoredLinks);
+
+ assert.equal(sponsoredLinks.length, 3);
+ });
+ it("should ignore caps if they are more than what we have", () => {
+ fakeNimbusFeatures.pocketNewtab.getVariable.returns(10);
+
+ feed._maybeCapSponsoredLinks(sponsoredLinks);
+
+ assert.equal(sponsoredLinks.length, 3);
+ });
+ });
+});
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..f6560d7ab2
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js
@@ -0,0 +1,1903 @@
+import { FAKE_GLOBAL_PREFS, FakePrefs, GlobalOverrider } from "test/unit/utils";
+import { actionTypes as at } from "common/Actions.sys.mjs";
+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 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(() => {
+ FAKE_GLOBAL_PREFS.set("apiKeyPref", "test-api-key");
+ FAKE_GLOBAL_PREFS.set(
+ "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 }]]),
+ };
+
+ ({
+ TopStoriesFeed,
+ STORIES_UPDATE_TIME,
+ TOPICS_UPDATE_TIME,
+ SECTION_ID,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ REC_IMPRESSION_TRACKING_PREF,
+ DEFAULT_RECS_EXPIRE_TIME,
+ } = injector({
+ "lib/ActivityStreamPrefs.jsm": { Prefs: FakePrefs },
+ "lib/ShortURL.jsm": { shortURL: shortURLStub },
+ "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.console, "error");
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ api_key_pref: "invalid",
+ stories_endpoint: "https://invalid.com/?apiKey=$apiKey",
+ },
+ });
+ instance.init();
+
+ assert.calledWith(
+ console.error,
+ "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.console, "error");
+ 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(console.error);
+ });
+ 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: {},
+ spocs: [{ id: "spoc1" }],
+ };
+
+ instance.show_spocs = 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",
+ 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",
+ 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.console, "error");
+
+ 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(console.error);
+ });
+ 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.console, "error");
+
+ 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(console.error);
+ });
+ });
+ describe("#personalization", () => {
+ it("should sort stories", async () => {
+ const response = {
+ recommendations: [{ id: "1" }, { id: "2" }],
+ settings: {},
+ };
+
+ 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 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", () => {
+ let items = [
+ { guid: "g1" },
+ { guid: "g2" },
+ { guid: "g3" },
+ { guid: "g4" },
+ { guid: "g5" },
+ { guid: "g6" },
+ ];
+
+ // 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 record top story impressions", async () => {
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+
+ 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.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 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);
+ });
+ });
+ 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.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,
+ 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,
+ 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,
+ 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,
+ 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] });
+ let expectedPrefValueCallTwo = JSON.stringify({ 2: 0, 3: 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
+ );
+ assert.calledWith(
+ instance._prefs.set.secondCall,
+ REC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValueCallTwo
+ );
+
+ clock.tick(1);
+ instance._prefs.get = pref => expectedPrefValue;
+ let expectedPrefValueCallThree = JSON.stringify({ 5: [0, 1] });
+ let expectedPrefValueCallFour = JSON.stringify({ 2: 1, 3: 1, 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.thirdCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValueCallThree
+ );
+ assert.calledWith(
+ instance._prefs.set.getCall(3),
+ REC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValueCallFour
+ );
+
+ clock.tick(1);
+ instance._prefs.get = pref => expectedPrefValueCallThree;
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 4 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.getCall(4),
+ SPOC_IMPRESSION_TRACKING_PREF,
+ JSON.stringify({ 5: [0, 1], 6: [2] })
+ );
+ assert.calledWith(
+ instance._prefs.set.getCall(5),
+ REC_IMPRESSION_TRACKING_PREF,
+ JSON.stringify({ 2: 2, 3: 2, 5: [0, 1] })
+ );
+ });
+ 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.thirdCall,
+ 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.getCall(4),
+ 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,
+ 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,
+ 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 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" }]);
+ });
+ });
+ 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",
+ 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,
+ referrer: "referrer",
+ score: 1,
+ spoc_meta: {},
+ title: undefined,
+ type: "trending",
+ url: undefined,
+ },
+ ],
+ topics: [{}],
+ },
+ true
+ );
+ });
+ });
+ 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..6255568438
--- /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.sys.mjs";
+
+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/unit-entry.js b/browser/components/newtab/test/unit/unit-entry.js
new file mode 100644
index 0000000000..803390a386
--- /dev/null
+++ b/browser/components/newtab/test/unit/unit-entry.js
@@ -0,0 +1,684 @@
+import {
+ EventEmitter,
+ FakePrefs,
+ FakensIPrefService,
+ GlobalOverrider,
+ FakeConsoleAPI,
+ FakeLogger,
+} 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";
+import FxMSCommonSchema from "../../content-src/asrouter/schemas/FxMSCommon.schema.json";
+
+enzyme.configure({ adapter: new Adapter() });
+
+// Cause React warnings to make tests that trigger them fail
+const origConsoleError = console.error;
+console.error = function (msg, ...args) {
+ 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);
+chai.tv4.addSchema("file:///FxMSCommon.schema.json", FxMSCommonSchema);
+
+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,
+ };
+ }
+}
+
+// Detect plain object passed to lazy getter APIs, and set its prototype to
+// global object, and return the global object for further modification.
+// Returns the object if it's not plain object.
+//
+// This is a workaround to make the existing testharness and testcase keep
+// working even after lazy getters are moved to plain `lazy` object.
+const cachedPlainObject = new Set();
+function updateGlobalOrObject(object) {
+ // Given this function modifies the prototype, and the following
+ // condition doesn't meet on the second call, cache the result.
+ if (cachedPlainObject.has(object)) {
+ return global;
+ }
+
+ if (Object.getPrototypeOf(object).constructor.name !== "Object") {
+ return object;
+ }
+
+ cachedPlainObject.add(object);
+ Object.setPrototypeOf(object, global);
+ return global;
+}
+
+const TEST_GLOBAL = {
+ JSWindowActorParent,
+ JSWindowActorChild,
+ AboutReaderParent: {
+ addMessageListener: (messageName, listener) => {},
+ removeMessageListener: (messageName, listener) => {},
+ },
+ AboutWelcomeTelemetry: class {
+ submitGleanPingForPing() {}
+ },
+ AddonManager: {
+ getActiveAddons() {
+ return Promise.resolve({ addons: [], fullData: false });
+ },
+ },
+ AppConstants: {
+ MOZILLA_OFFICIAL: true,
+ MOZ_APP_VERSION: "69.0a1",
+ isChinaRepack() {
+ return false;
+ },
+ isPlatformAndVersionAtMost() {
+ return false;
+ },
+ platform: "win",
+ },
+ ASRouterPreferences: {
+ console: new FakeConsoleAPI({
+ maxLogLevel: "off", // set this to "debug" or "all" to get more ASRouter logging in tests
+ prefix: "ASRouter",
+ }),
+ },
+ AWScreenUtils: {
+ evaluateTargetingAndRemoveScreens() {
+ return true;
+ },
+ async removeScreens() {
+ return true;
+ },
+ evaluateScreenTargeting() {
+ return true;
+ },
+ },
+ BrowserUtils: {
+ sendToDeviceEmailsSupported() {
+ return true;
+ },
+ },
+ UpdateUtils: { getUpdateChannel() {} },
+ BasePromiseWorker: class {
+ constructor() {
+ this.ExceptionHandlers = [];
+ }
+ post() {}
+ },
+ browserSearchRegion: "US",
+ BrowserWindowTracker: { getTopWindow() {} },
+ ChromeUtils: {
+ defineModuleGetter: updateGlobalOrObject,
+ defineESModuleGetters: updateGlobalOrObject,
+ generateQI() {
+ return {};
+ },
+ import() {
+ return global;
+ },
+ importESModule() {
+ 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,
+ },
+ ConsoleAPI: FakeConsoleAPI,
+ // 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/widget/useridleservice;1": {
+ getService() {
+ return {
+ idleTime: 0,
+ addIdleObserver() {},
+ removeIdleObserver() {},
+ };
+ },
+ },
+ "@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,
+ },
+ nsICookieBannerService: {
+ MODE_DISABLED: 0,
+ MODE_REJECT: 1,
+ MODE_REJECT_OR_ACCEPT: 2,
+ MODE_UNSET: 3,
+ },
+ },
+ Cu: {
+ importGlobalProperties() {},
+ now: () => window.performance.now(),
+ cloneInto: o => JSON.parse(JSON.stringify(o)),
+ },
+ console: {
+ ...console,
+ error() {},
+ },
+ dump() {},
+ EveryWindow: {
+ registerCallback: (id, init, uninit) => {},
+ unregisterCallback: id => {},
+ },
+ setTimeout: window.setTimeout.bind(window),
+ clearTimeout: window.clearTimeout.bind(window),
+ fetch() {},
+ // eslint-disable-next-line object-shorthand
+ Image: function () {}, // NB: This is a function/constructor
+ IOUtils: {
+ writeJSON() {
+ return Promise.resolve(0);
+ },
+ readJSON() {
+ return Promise.resolve({});
+ },
+ read() {
+ return Promise.resolve(new Uint8Array());
+ },
+ makeDirectory() {
+ return Promise.resolve(0);
+ },
+ write() {
+ return Promise.resolve(0);
+ },
+ exists() {
+ return Promise.resolve(0);
+ },
+ remove() {
+ return Promise.resolve(0);
+ },
+ stat() {
+ return Promise.resolve(0);
+ },
+ },
+ 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: "/",
+ },
+ },
+ },
+ PathUtils: {
+ join(...parts) {
+ return parts[parts.length - 1];
+ },
+ joinRelative(...parts) {
+ return parts[parts.length - 1];
+ },
+ getProfileDir() {
+ return Promise.resolve("/");
+ },
+ getLocalProfileDir() {
+ return Promise.resolve("/");
+ },
+ },
+ 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,
+ permanentPrivateBrowsing: 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-updated",
+ },
+ Services: {
+ dirsvc: {
+ get: () => ({ parent: { parent: { path: "appPath" } } }),
+ },
+ env: {
+ set: () => undefined,
+ },
+ 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: () => {},
+ keyedScalarAdd: () => {},
+ },
+ uuid: {
+ generateUUID() {
+ return "{foo-123-foo}";
+ },
+ },
+ console: { logStringMessage: () => {} },
+ prefs: new FakensIPrefService(),
+ 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) {
+ updateGlobalOrObject(object)[name] = f();
+ },
+ defineLazyGlobalGetters: updateGlobalOrObject,
+ defineLazyModuleGetter: updateGlobalOrObject,
+ defineLazyModuleGetters: updateGlobalOrObject,
+ defineLazyServiceGetter: updateGlobalOrObject,
+ defineLazyServiceGetters: updateGlobalOrObject,
+ defineLazyPreferenceGetter(object, name) {
+ updateGlobalOrObject(object)[name] = "";
+ },
+ generateQI() {
+ return {};
+ },
+ },
+ EventEmitter,
+ ShellService: {
+ doesAppNeedPin: () => false,
+ 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 } }))
+ );
+ }
+ async formatValue(stringId) {
+ return Promise.resolve(stringId);
+ }
+ },
+ FxAccountsConfig: {
+ promiseConnectAccountURI(id) {
+ return Promise.resolve(id);
+ },
+ },
+ FX_MONITOR_OAUTH_CLIENT_ID: "fake_client_id",
+ ExperimentAPI: {
+ getExperiment() {},
+ getExperimentMetaData() {},
+ getRolloutMetaData() {},
+ },
+ NimbusFeatures: {
+ glean: {
+ getVariable() {},
+ },
+ newtab: {
+ getVariable() {},
+ getAllVariables() {},
+ onUpdate() {},
+ offUpdate() {},
+ },
+ pocketNewtab: {
+ getVariable() {},
+ getAllVariables() {},
+ onUpdate() {},
+ offUpdate() {},
+ },
+ cookieBannerHandling: {
+ getVariable() {},
+ },
+ },
+ 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() {},
+ },
+ Logger: FakeLogger,
+ getFxAccountsSingleton() {},
+ AboutNewTab: {},
+ Glean: {
+ newtab: {
+ opened: {
+ record() {},
+ },
+ closed: {
+ record() {},
+ },
+ locale: {
+ set() {},
+ },
+ newtabCategory: {
+ set() {},
+ },
+ homepageCategory: {
+ set() {},
+ },
+ blockedSponsors: {
+ set() {},
+ },
+ },
+ newtabSearch: {
+ enabled: {
+ set() {},
+ },
+ },
+ pocket: {
+ enabled: {
+ set() {},
+ },
+ impression: {
+ record() {},
+ },
+ isSignedIn: {
+ set() {},
+ },
+ sponsoredStoriesEnabled: {
+ set() {},
+ },
+ click: {
+ record() {},
+ },
+ save: {
+ record() {},
+ },
+ topicClick: {
+ record() {},
+ },
+ },
+ topsites: {
+ enabled: {
+ set() {},
+ },
+ sponsoredEnabled: {
+ set() {},
+ },
+ impression: {
+ record() {},
+ },
+ click: {
+ record() {},
+ },
+ rows: {
+ set() {},
+ },
+ },
+ },
+ GleanPings: {
+ newtab: {
+ submit() {},
+ },
+ },
+ Utils: {
+ SERVER_URL: "bogus://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..22069b8635
--- /dev/null
+++ b/browser/components/newtab/test/unit/utils.js
@@ -0,0 +1,406 @@
+/**
+ * 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;
+ });
+ }
+}
+
+/**
+ * A map of mocked preference names and values, used by `FakensIPrefBranch`,
+ * `FakensIPrefService`, and `FakePrefs`.
+ *
+ * Tests should add entries to this map for any preferences they'd like to set,
+ * and remove any entries during teardown for preferences that shouldn't be
+ * shared between tests.
+ */
+export const FAKE_GLOBAL_PREFS = new Map();
+
+/**
+ * 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 {
+ PREF_INVALID = "invalid";
+ PREF_INT = "integer";
+ PREF_BOOL = "boolean";
+ PREF_STRING = "string";
+
+ constructor(args) {
+ if (args) {
+ if ("initHook" in args) {
+ args.initHook.call(this);
+ }
+ if (args.defaultBranch) {
+ this.prefs = new Map();
+ } else {
+ this.prefs = FAKE_GLOBAL_PREFS;
+ }
+ } else {
+ this.prefs = FAKE_GLOBAL_PREFS;
+ }
+ this._prefBranch = {};
+ this.observers = new Map();
+ }
+ addObserver(prefix, callback) {
+ this.observers.set(prefix, callback);
+ }
+ removeObserver(prefix, callback) {
+ this.observers.delete(prefix, callback);
+ }
+ setStringPref(prefName, value) {
+ this.set(prefName, value);
+ }
+ getStringPref(prefName, defaultValue) {
+ return this.get(prefName, defaultValue);
+ }
+ setBoolPref(prefName, value) {
+ this.set(prefName, value);
+ }
+ getBoolPref(prefName) {
+ return this.get(prefName);
+ }
+ setIntPref(prefName, value) {
+ this.set(prefName, value);
+ }
+ getIntPref(prefName) {
+ return this.get(prefName);
+ }
+ setCharPref(prefName, value) {
+ this.set(prefName, value);
+ }
+ getCharPref(prefName) {
+ return this.get(prefName);
+ }
+ clearUserPref(prefName) {
+ this.prefs.delete(prefName);
+ }
+ get(prefName, defaultValue) {
+ let value = this.prefs.get(prefName);
+ return typeof value === "undefined" ? defaultValue : value;
+ }
+ getPrefType(prefName) {
+ let value = this.prefs.get(prefName);
+ switch (typeof value) {
+ case "number":
+ return this.PREF_INT;
+
+ case "boolean":
+ return this.PREF_BOOL;
+
+ case "string":
+ return this.PREF_STRING;
+
+ default:
+ return this.PREF_INVALID;
+ }
+ }
+ set(prefName, value) {
+ this.prefs.set(prefName, value);
+
+ // Trigger all observers for prefixes of the changed pref name. This matches
+ // the semantics of `nsIPrefBranch`.
+ let observerPrefixes = [...this.observers.keys()].filter(prefix =>
+ prefName.startsWith(prefix)
+ );
+ for (let observerPrefix of observerPrefixes) {
+ this.observers.get(observerPrefix)("", "", prefName);
+ }
+ }
+ getChildList(prefix) {
+ return [...this.prefs.keys()].filter(prefName =>
+ prefName.startsWith(prefix)
+ );
+ }
+ prefHasUserValue(prefName) {
+ return this.prefs.has(prefName);
+ }
+ prefIsLocked(prefName) {
+ return false;
+ }
+}
+
+/**
+ * A fake `Services.prefs` implementation that extends `FakensIPrefBranch`
+ * with methods specific to `nsIPrefService`.
+ */
+export class FakensIPrefService extends FakensIPrefBranch {
+ getBranch() {}
+ getDefaultBranch(prefix) {
+ return {
+ setBoolPref() {},
+ setIntPref() {},
+ setStringPref() {},
+ clearUserPref() {},
+ };
+ }
+}
+
+/**
+ * Very simple fake for the most basic semantics of Preferences.sys.mjs.
+ * Extends FakensIPrefBranch.
+ */
+export class FakePrefs extends FakensIPrefBranch {
+ observe(prefName, callback) {
+ super.addObserver(prefName, callback);
+ }
+ ignore(prefName, callback) {
+ super.removeObserver(prefName, callback);
+ }
+ observeBranch(listener) {}
+ ignoreBranch(listener) {}
+ set(prefName, value) {
+ this.prefs.set(prefName, value);
+
+ // Trigger observers for just the changed pref name, not any of its
+ // prefixes. This matches the semantics of `Preferences.sys.mjs`.
+ if (this.observers.has(prefName)) {
+ this.observers.get(prefName)(value);
+ }
+ }
+}
+
+/**
+ * Slimmed down version of toolkit/modules/EventEmitter.sys.mjs
+ */
+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;
+}
+
+export class FakeConsoleAPI {
+ static LOG_LEVELS = {
+ all: Number.MIN_VALUE,
+ debug: 2,
+ log: 3,
+ info: 3,
+ clear: 3,
+ trace: 3,
+ timeEnd: 3,
+ time: 3,
+ assert: 3,
+ group: 3,
+ groupEnd: 3,
+ profile: 3,
+ profileEnd: 3,
+ dir: 3,
+ dirxml: 3,
+ warn: 4,
+ error: 5,
+ off: Number.MAX_VALUE,
+ };
+
+ constructor({ prefix = "", maxLogLevel = "all" } = {}) {
+ this.prefix = prefix;
+ this.prefixStr = prefix ? `${prefix}: ` : "";
+ this.maxLogLevel = maxLogLevel;
+
+ for (const level of Object.keys(FakeConsoleAPI.LOG_LEVELS)) {
+ // eslint-disable-next-line no-console
+ if (typeof console[level] === "function") {
+ this[level] = this.shouldLog(level)
+ ? this._log.bind(this, level)
+ : () => {};
+ }
+ }
+ }
+ shouldLog(level) {
+ return (
+ FakeConsoleAPI.LOG_LEVELS[this.maxLogLevel] <=
+ FakeConsoleAPI.LOG_LEVELS[level]
+ );
+ }
+ _log(level, ...args) {
+ console[level](this.prefixStr, ...args); // eslint-disable-line no-console
+ }
+}
+
+export class FakeLogger extends FakeConsoleAPI {
+ constructor() {
+ super({
+ // Don't use a prefix because the first instance gets cached and reused by
+ // other consumers that would otherwise pass their own identifying prefix.
+ maxLogLevel: "off", // Change this to "debug" or "all" to get more logging in tests
+ });
+ }
+}
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..4193fa635d
--- /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://global/skin/icons/pocket.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..49463fe0a8
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/head.js
@@ -0,0 +1,105 @@
+/* Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* eslint-disable no-unused-vars */
+
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const lazy = {};
+ChromeUtils.defineESModuleGetters(lazy, {
+ JsonSchema: "resource://gre/modules/JsonSchema.sys.mjs",
+});
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+function assertValidates(validator, obj, msg) {
+ const result = validator.validate(obj);
+ Assert.ok(
+ result.valid && result.errors.length === 0,
+ `${msg} - errors = ${JSON.stringify(result.errors, undefined, 2)}`
+ );
+}
+
+async function fetchSchema(uri) {
+ try {
+ return fetch(uri, { credentials: "omit" }).then(rsp => rsp.json());
+ } catch (e) {
+ throw new Error(`Could not fetch ${uri}`);
+ }
+}
+
+async function schemaValidatorFor(uri, { common = false } = {}) {
+ const schema = await fetchSchema(uri);
+ const validator = new lazy.JsonSchema.Validator(schema);
+
+ if (common) {
+ const commonSchema = await fetchSchema(
+ "resource://testing-common/FxMSCommon.schema.json"
+ );
+ validator.addSchema(commonSchema);
+ }
+
+ return validator;
+}
+
+async function makeValidators() {
+ const experimentValidator = await schemaValidatorFor(
+ "resource://activity-stream/schemas/MessagingExperiment.schema.json"
+ );
+
+ const messageValidators = {
+ cfr_doorhanger: await schemaValidatorFor(
+ "resource://testing-common/ExtensionDoorhanger.schema.json",
+ { common: true }
+ ),
+ cfr_urlbar_chiclet: await schemaValidatorFor(
+ "resource://testing-common/CFRUrlbarChiclet.schema.json",
+ { common: true }
+ ),
+ infobar: await schemaValidatorFor(
+ "resource://testing-common/InfoBar.schema.json",
+ { common: true }
+ ),
+ pb_newtab: await schemaValidatorFor(
+ "resource://testing-common/NewtabPromoMessage.schema.json",
+ { common: true }
+ ),
+ protections_panel: await schemaValidatorFor(
+ "resource://testing-common/ProtectionsPanelMessage.schema.json",
+ { common: true }
+ ),
+ spotlight: await schemaValidatorFor(
+ "resource://testing-common/Spotlight.schema.json",
+ { common: true }
+ ),
+ toast_notification: await schemaValidatorFor(
+ "resource://testing-common/ToastNotification.schema.json",
+ { common: true }
+ ),
+ toolbar_badge: await schemaValidatorFor(
+ "resource://testing-common/ToolbarBadgeMessage.schema.json",
+ { common: true }
+ ),
+ update_action: await schemaValidatorFor(
+ "resource://testing-common/UpdateAction.schema.json",
+ { common: true }
+ ),
+ whatsnew_panel_message: await schemaValidatorFor(
+ "resource://testing-common/WhatsNewMessage.schema.json",
+ { common: true }
+ ),
+ feature_callout: await schemaValidatorFor(
+ // For now, Feature Callout and Spotlight share a common schema
+ "resource://testing-common/Spotlight.schema.json",
+ { common: true }
+ ),
+ };
+
+ messageValidators.milestone_message = messageValidators.cfr_doorhanger;
+
+ return { experimentValidator, messageValidators };
+}
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..f2b473144b
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js
@@ -0,0 +1,98 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AttributionCode } = ChromeUtils.importESModule(
+ "resource:///modules/AttributionCode.sys.mjs"
+);
+const { ASRouterTargeting } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+const { MacAttribution } = ChromeUtils.importESModule(
+ "resource:///modules/MacAttribution.sys.mjs"
+);
+const { EnterprisePolicyTesting } = ChromeUtils.importESModule(
+ "resource://testing-common/EnterprisePolicyTesting.sys.mjs"
+);
+
+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();
+});
+
+add_task(async function check_enterprise_targeting() {
+ const messages = [
+ {
+ id: "foo1",
+ targeting: "hasActiveEnterprisePolicies",
+ },
+ {
+ id: "foo2",
+ targeting: "!hasActiveEnterprisePolicies",
+ },
+ ];
+
+ equal(
+ await ASRouterTargeting.findMatchingMessage({ messages }),
+ messages[1],
+ "should select the message for policies turned off"
+ );
+
+ await EnterprisePolicyTesting.setupPolicyEngineWithJson({
+ policies: {
+ DisableFirefoxStudies: {
+ Value: true,
+ },
+ },
+ });
+
+ equal(
+ await ASRouterTargeting.findMatchingMessage({ messages }),
+ messages[0],
+ "should select the message for policies turned on"
+ );
+});
diff --git a/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_snapshot.js b/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_snapshot.js
new file mode 100644
index 0000000000..cb5a13baf5
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_snapshot.js
@@ -0,0 +1,138 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { ASRouterTargeting } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+
+add_task(async function should_ignore_rejections() {
+ let target = {
+ get foo() {
+ return new Promise(resolve => resolve(1));
+ },
+
+ get bar() {
+ return new Promise((resolve, reject) => reject(new Error("unspecified")));
+ },
+ };
+
+ let snapshot = await ASRouterTargeting.getEnvironmentSnapshot(target);
+ Assert.deepEqual(snapshot, { environment: { foo: 1 }, version: 1 });
+});
+
+add_task(async function nested_objects() {
+ const target = {
+ get foo() {
+ return Promise.resolve("foo");
+ },
+ get bar() {
+ return Promise.reject(new Error("bar"));
+ },
+ baz: {
+ get qux() {
+ return Promise.resolve("qux");
+ },
+ get quux() {
+ return Promise.reject(new Error("quux"));
+ },
+ get corge() {
+ return {
+ get grault() {
+ return Promise.resolve("grault");
+ },
+ get garply() {
+ return Promise.reject(new Error("garply"));
+ },
+ };
+ },
+ },
+ };
+
+ const snapshot = await ASRouterTargeting.getEnvironmentSnapshot(target);
+ Assert.deepEqual(
+ snapshot,
+ {
+ environment: {
+ foo: "foo",
+ baz: {
+ qux: "qux",
+ corge: {
+ grault: "grault",
+ },
+ },
+ },
+ version: 1,
+ },
+ "getEnvironmentSnapshot should resolve nested promises"
+ );
+});
+
+add_task(async function arrays() {
+ const target = {
+ foo: [1, 2, 3],
+ bar: [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)],
+ baz: Promise.resolve([1, 2, 3]),
+ qux: Promise.resolve([
+ Promise.resolve(1),
+ Promise.resolve(2),
+ Promise.resolve(3),
+ ]),
+ quux: Promise.resolve({
+ corge: [Promise.resolve(1), 2, 3],
+ }),
+ };
+
+ const snapshot = await ASRouterTargeting.getEnvironmentSnapshot(target);
+ Assert.deepEqual(
+ snapshot,
+ {
+ environment: {
+ foo: [1, 2, 3],
+ bar: [1, 2, 3],
+ baz: [1, 2, 3],
+ qux: [1, 2, 3],
+ quux: { corge: [1, 2, 3] },
+ },
+ version: 1,
+ },
+ "getEnvironmentSnapshot should resolve arrays correctly"
+ );
+});
+
+/*
+ * NB: This test is last because it manipulates shutdown phases.
+ *
+ * Adding tests after this one will result in failures.
+ */
+add_task(async function should_ignore_rejections() {
+ // The order that `ASRouterTargeting.getEnvironmentSnapshot`
+ // enumerates the target object matters here, but it's guaranteed to
+ // be consistent by the `for ... in` ordering: see
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#description.
+ let target = {
+ get foo() {
+ return new Promise(resolve => resolve(1));
+ },
+
+ get bar() {
+ return new Promise(resolve => {
+ // Pretend that we're about to shut down.
+ Services.startup.advanceShutdownPhase(
+ Services.startup.SHUTDOWN_PHASE_APPSHUTDOWN
+ );
+ resolve(2);
+ });
+ },
+
+ get baz() {
+ return new Promise(resolve => resolve(3));
+ },
+ };
+
+ let snapshot = await ASRouterTargeting.getEnvironmentSnapshot(target);
+ // `baz` is dropped since we're shutting down by the time it's processed.
+ Assert.deepEqual(snapshot, { environment: { foo: 1, bar: 2 }, version: 1 });
+});
diff --git a/browser/components/newtab/test/xpcshell/test_ASRouter_getTargetingParameters.js b/browser/components/newtab/test/xpcshell/test_ASRouter_getTargetingParameters.js
new file mode 100644
index 0000000000..fb3b037660
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_ASRouter_getTargetingParameters.js
@@ -0,0 +1,73 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+add_task(async function nested_objects() {
+ const target = {
+ get foo() {
+ return Promise.resolve("foo");
+ },
+ baz: {
+ get qux() {
+ return Promise.resolve("qux");
+ },
+ get corge() {
+ return {
+ get grault() {
+ return Promise.resolve("grault");
+ },
+ };
+ },
+ },
+ };
+
+ const params = await ASRouter.getTargetingParameters(target);
+ Assert.deepEqual(
+ params,
+ {
+ foo: "foo",
+ baz: {
+ qux: "qux",
+ corge: {
+ grault: "grault",
+ },
+ },
+ },
+ "getTargetingParameters should resolve nested promises"
+ );
+});
+
+add_task(async function arrays() {
+ const target = {
+ foo: [1, 2, 3],
+ bar: [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)],
+ baz: Promise.resolve([1, 2, 3]),
+ qux: Promise.resolve([
+ Promise.resolve(1),
+ Promise.resolve(2),
+ Promise.resolve(3),
+ ]),
+ quux: Promise.resolve({
+ corge: [Promise.resolve(1), 2, 3],
+ }),
+ };
+
+ const params = await ASRouter.getTargetingParameters(target);
+ Assert.deepEqual(
+ params,
+ {
+ foo: [1, 2, 3],
+ bar: [1, 2, 3],
+ baz: [1, 2, 3],
+ qux: [1, 2, 3],
+ quux: { corge: [1, 2, 3] },
+ },
+ "getEnvironmentSnapshot should resolve arrays correctly"
+ );
+});
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..0cbb81351b
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js
@@ -0,0 +1,251 @@
+/* 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.importESModule(
+ "resource://testing-common/AddonTestUtils.sys.mjs"
+);
+const { SearchTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/SearchTestUtils.sys.mjs"
+);
+const { TestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/TestUtils.sys.mjs"
+);
+
+SearchTestUtils.init(this);
+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.defineESModuleGetters(this, {
+ BasePromiseWorker: "resource://gre/modules/PromiseWorker.sys.mjs",
+});
+
+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_setup(async function () {
+ 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.
+ await SearchTestUtils.installSearchExtension(
+ {
+ name: "Test engine",
+ keyword: "@testengine",
+ search_url_get_params: "s={searchTerms}",
+ },
+ { setAsDefault: true }
+ );
+
+ // 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() {
+ Services.prefs.setBoolPref(
+ "security.allow_parent_unrestricted_js_loads",
+ true
+ );
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref("security.allow_parent_unrestricted_js_loads");
+ });
+
+ 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..9b31a2add1
--- /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.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+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..2b2c55b47b
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js
@@ -0,0 +1,69 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AboutWelcomeDefaults } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeDefaults.jsm"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+const { AttributionCode } = ChromeUtils.importESModule(
+ "resource:///modules/AttributionCode.sys.mjs"
+);
+const { AddonRepository } = ChromeUtils.importESModule(
+ "resource://gre/modules/addons/AddonRepository.sys.mjs"
+);
+
+const TEST_ATTRIBUTION_DATA = {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: "rta:iridium%40particlecore.github.io",
+};
+
+add_task(async function test_handleAddonInfoNotFound() {
+ let sandbox = sinon.createSandbox();
+ const stub = sandbox.stub(AttributionCode, "getAttrDataAsync").resolves(null);
+ let result = await AboutWelcomeDefaults.getAttributionContent();
+ equal(stub.callCount, 1, "Call was made");
+ equal(result, null, "No data is returned");
+
+ sandbox.restore();
+});
+
+add_task(async function test_UAAttribution() {
+ let sandbox = sinon.createSandbox();
+ const stub = sandbox
+ .stub(AttributionCode, "getAttrDataAsync")
+ .resolves({ ua: "test" });
+ let result = await AboutWelcomeDefaults.getAttributionContent();
+ equal(stub.callCount, 1, "Call was made");
+ equal(result.template, undefined, "Template was not returned");
+ equal(result.ua, "test", "UA was returned");
+
+ sandbox.restore();
+});
+
+add_task(async function test_formatAttributionData() {
+ let sandbox = sinon.createSandbox();
+ const TEST_ADDON_INFO = {
+ sourceURI: { scheme: "https", spec: "https://test.xpi" },
+ name: "Test Add-on",
+ icons: { 64: "http://test.svg" },
+ };
+ sandbox
+ .stub(AttributionCode, "getAttrDataAsync")
+ .resolves(TEST_ATTRIBUTION_DATA);
+ sandbox.stub(AddonRepository, "getAddonsByIDs").resolves([TEST_ADDON_INFO]);
+ let result = await AboutWelcomeDefaults.getAttributionContent(
+ TEST_ATTRIBUTION_DATA
+ );
+ equal(AddonRepository.getAddonsByIDs.callCount, 1, "Retrieve addon content");
+ equal(result.template, "return_to_amo", "RTAMO template returned");
+ equal(result.name, TEST_ADDON_INFO.name, "AddonInfo returned");
+
+ sandbox.restore();
+});
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..5ecc20f804
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js
@@ -0,0 +1,101 @@
+/* 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.importESModule(
+ "resource:///modules/AttributionCode.sys.mjs"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+const TELEMETRY_PREF = "browser.newtabpage.activity-stream.telemetry";
+
+add_setup(function setup() {
+ do_get_profile();
+ Services.fog.initializeFOG();
+});
+
+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" });
+
+ let pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(Glean.messagingSystem.event.testGetValue(), "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"
+ );
+
+ ok(pingSubmitted, "Glean ping was submitted");
+});
+
+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/test_AboutWelcomeTelemetry_glean.js b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry_glean.js
new file mode 100644
index 0000000000..a49a6f9382
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry_glean.js
@@ -0,0 +1,143 @@
+/* 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 TELEMETRY_PREF = "browser.newtabpage.activity-stream.telemetry";
+
+add_setup(function setup() {
+ do_get_profile();
+ Services.fog.initializeFOG();
+});
+
+// We recognize two kinds of unexpected data that might reach
+// `submitGleanPingForPing`: unknown keys, and keys with unexpectedly-complex
+// data (ie, non-scalar).
+// We report the keys in special metrics to aid in system health monitoring.
+add_task(function test_weird_data() {
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(TELEMETRY_PREF);
+ });
+ Services.prefs.setBoolPref(TELEMETRY_PREF, true);
+
+ const AWTelemetry = new AboutWelcomeTelemetry();
+
+ const unknownKey = "some_unknown_key";
+ const camelUnknownKey = AWTelemetry._snakeToCamelCase(unknownKey);
+
+ let pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.unknownKeys[camelUnknownKey].testGetValue(),
+ 1,
+ "caught the unknown key"
+ );
+ // TODO(bug 1600008): Also check the for-testing overall count.
+ Assert.equal(Glean.messagingSystem.unknownKeyCount.testGetValue(), 1);
+ });
+ AWTelemetry.submitGleanPingForPing({
+ [unknownKey]: "value doesn't matter",
+ });
+
+ Assert.ok(pingSubmitted, "Ping with unknown keys was submitted");
+
+ const invalidNestedDataKey = "event";
+ pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.invalidNestedData[
+ invalidNestedDataKey
+ ].testGetValue("messaging-system"),
+ 1,
+ "caught the invalid nested data"
+ );
+ });
+ AWTelemetry.submitGleanPingForPing({
+ [invalidNestedDataKey]: { this_should: "not be", complex: "data" },
+ });
+
+ Assert.ok(pingSubmitted, "Ping with invalid nested data submitted");
+});
+
+// `event_context` is weird. It's an object, but it might have been stringified
+// before being provided for recording.
+add_task(function test_event_context() {
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(TELEMETRY_PREF);
+ });
+ Services.prefs.setBoolPref(TELEMETRY_PREF, true);
+
+ const AWTelemetry = new AboutWelcomeTelemetry();
+
+ const eventContext = {
+ reason: "reason",
+ page: "page",
+ source: "source",
+ something_else: "not specifically handled",
+ };
+ const stringifiedEC = JSON.stringify(eventContext);
+
+ let pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.eventReason.testGetValue(),
+ eventContext.reason,
+ "event_context.reason also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventPage.testGetValue(),
+ eventContext.page,
+ "event_context.page also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventSource.testGetValue(),
+ eventContext.source,
+ "event_context.source also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventContext.testGetValue(),
+ stringifiedEC,
+ "whole event_context added as text."
+ );
+ });
+ AWTelemetry.submitGleanPingForPing({
+ event_context: eventContext,
+ });
+ Assert.ok(pingSubmitted, "Ping with object event_context submitted");
+
+ pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.eventReason.testGetValue(),
+ eventContext.reason,
+ "event_context.reason also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventPage.testGetValue(),
+ eventContext.page,
+ "event_context.page also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventSource.testGetValue(),
+ eventContext.source,
+ "event_context.source also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventContext.testGetValue(),
+ stringifiedEC,
+ "whole event_context added as text."
+ );
+ });
+ AWTelemetry.submitGleanPingForPing({
+ event_context: stringifiedEC,
+ });
+ Assert.ok(pingSubmitted, "Ping with string event_context submitted");
+});
diff --git a/browser/components/newtab/test/xpcshell/test_CFRMessageProvider.js b/browser/components/newtab/test/xpcshell/test_CFRMessageProvider.js
new file mode 100644
index 0000000000..acdd4a2e2b
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_CFRMessageProvider.js
@@ -0,0 +1,32 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+
+add_task(async function test_cfrMessages() {
+ const { experimentValidator, messageValidators } = await makeValidators();
+
+ const messages = await CFRMessageProvider.getMessages();
+ for (const message of messages) {
+ const validator = messageValidators[message.template];
+ Assert.ok(
+ typeof validator !== "undefined",
+ typeof validator !== "undefined"
+ ? `Schema validator found for ${message.template}.`
+ : `No schema validator found for template ${message.template}. Please update this test to add one.`
+ );
+
+ assertValidates(
+ validator,
+ message,
+ `Message ${message.id} validates as template ${message.template}`
+ );
+ assertValidates(
+ experimentValidator,
+ message,
+ `Message ${message.id} validates as MessagingExperiment`
+ );
+ }
+});
diff --git a/browser/components/newtab/test/xpcshell/test_InflightAssetsMessageProvider.js b/browser/components/newtab/test/xpcshell/test_InflightAssetsMessageProvider.js
new file mode 100644
index 0000000000..ad1bd1dbff
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_InflightAssetsMessageProvider.js
@@ -0,0 +1,41 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { InflightAssetsMessageProvider } = ChromeUtils.import(
+ "resource://testing-common/InflightAssetsMessageProvider.jsm"
+);
+
+const MESSAGE_VALIDATORS = {};
+let EXPERIMENT_VALIDATOR;
+
+add_setup(async function setup() {
+ const validators = await makeValidators();
+
+ EXPERIMENT_VALIDATOR = validators.experimentValidator;
+ Object.assign(MESSAGE_VALIDATORS, validators.messageValidators);
+});
+
+add_task(function test_InflightAssetsMessageProvider() {
+ const messages = InflightAssetsMessageProvider.getMessages();
+
+ for (const message of messages) {
+ const validator = MESSAGE_VALIDATORS[message.template];
+ Assert.ok(
+ typeof validator !== "undefined",
+ typeof validator !== "undefined"
+ ? `Schema validator found for ${message.template}`
+ : `No schema validator found for template ${message.template}. Please update this test to add one.`
+ );
+
+ assertValidates(
+ validator,
+ message,
+ `Message ${message.id} validates as ${message.template} template`
+ );
+ assertValidates(
+ EXPERIMENT_VALIDATOR,
+ message,
+ `Message ${message.id} validates as a MessagingExperiment`
+ );
+ }
+});
diff --git a/browser/components/newtab/test/xpcshell/test_OnboardingMessageProvider.js b/browser/components/newtab/test/xpcshell/test_OnboardingMessageProvider.js
new file mode 100644
index 0000000000..0ad7a6cbee
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_OnboardingMessageProvider.js
@@ -0,0 +1,229 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+
+function getOnboardingScreenById(screens, screenId) {
+ return screens.find(screen => {
+ return screen?.id === screenId;
+ });
+}
+
+add_task(
+ async function test_OnboardingMessageProvider_getUpgradeMessage_no_pin() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin").resolves(true);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+ // If Firefox is not pinned, the screen should have "pin" content
+ equal(
+ message.content.screens[0].id,
+ "UPGRADE_PIN_FIREFOX",
+ "Screen has pin screen id"
+ );
+ equal(
+ message.content.screens[0].content.primary_button.action.type,
+ "PIN_FIREFOX_TO_TASKBAR",
+ "Primary button has pin action type"
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_OnboardingMessageProvider_getUpgradeMessage_pin_no_default() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin").resolves(false);
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(true);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+ // If Firefox is pinned, but not the default, the screen should have "make default" content
+ equal(
+ message.content.screens[0].id,
+ "UPGRADE_ONLY_DEFAULT",
+ "Screen has make default screen id"
+ );
+ equal(
+ message.content.screens[0].content.primary_button.action.type,
+ "SET_DEFAULT_BROWSER",
+ "Primary button has make default action"
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_OnboardingMessageProvider_getUpgradeMessage_pin_and_default() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin").resolves(false);
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(false);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+ // If Firefox is pinned and the default, the screen should have "get started" content
+ equal(
+ message.content.screens[0].id,
+ "UPGRADE_GET_STARTED",
+ "Screen has get started screen id"
+ );
+ ok(
+ !message.content.screens[0].content.primary_button.action.type,
+ "Primary button has no action type"
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_OnboardingMessageProvider_getNoImport_default() {
+ let sandbox = sinon.createSandbox();
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(false);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+
+ // No import screen is shown when user has Firefox both pinned and default
+ Assert.notEqual(
+ message.content.screens[1]?.id,
+ "UPGRADE_IMPORT_SETTINGS",
+ "Screen has no import screen id"
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_OnboardingMessageProvider_getImport_nodefault() {
+ Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", true);
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref("browser.shell.checkDefaultBrowser");
+ });
+
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedDefault").resolves(true);
+ sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin").resolves(false);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+
+ // Import screen is shown when user doesn't have Firefox pinned and default
+ Assert.equal(
+ message.content.screens[1]?.id,
+ "UPGRADE_IMPORT_SETTINGS",
+ "Screen has import screen id"
+ );
+ sandbox.restore();
+});
+
+add_task(
+ async function test_OnboardingMessageProvider_getPinPrivateWindow_noPrivatePin() {
+ Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", true);
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref("browser.shell.checkDefaultBrowser");
+ });
+ let sandbox = sinon.createSandbox();
+ // User needs default to ensure Pin Private window shows as third screen after import
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(true);
+
+ let pinStub = sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin");
+ pinStub.resolves(false);
+ pinStub.withArgs(true).resolves(true);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+
+ // Pin Private screen is shown when user doesn't have Firefox private pinned but has Firefox pinned
+ Assert.ok(
+ getOnboardingScreenById(
+ message.content.screens,
+ "UPGRADE_PIN_PRIVATE_WINDOW"
+ )
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_OnboardingMessageProvider_getNoPinPrivateWindow_noPin() {
+ Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", true);
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref("browser.shell.checkDefaultBrowser");
+ });
+ let sandbox = sinon.createSandbox();
+ // User needs default to ensure Pin Private window shows as third screen after import
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(true);
+
+ let pinStub = sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin");
+ pinStub.resolves(true);
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+
+ // Pin Private screen is not shown when user doesn't have Firefox pinned
+ Assert.ok(
+ !getOnboardingScreenById(
+ message.content.screens,
+ "UPGRADE_PIN_PRIVATE_WINDOW"
+ )
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_schemaValidation() {
+ const { experimentValidator, messageValidators } = await makeValidators();
+
+ const messages = await OnboardingMessageProvider.getMessages();
+ for (const message of messages) {
+ const validator = messageValidators[message.template];
+
+ Assert.ok(
+ typeof validator !== "undefined",
+ typeof validator !== "undefined"
+ ? `Schema validator found for ${message.template}.`
+ : `No schema validator found for template ${message.template}. Please update this test to add one.`
+ );
+ assertValidates(
+ validator,
+ message,
+ `Message ${message.id} validates as template ${message.template}`
+ );
+ assertValidates(
+ experimentValidator,
+ message,
+ `Message ${message.id} validates as MessagingExperiment`
+ );
+ }
+});
+
+add_task(
+ async function test_OnboardingMessageProvider_getPinPrivateWindow_pinPBMPrefDisabled() {
+ Services.prefs.setBoolPref(
+ "browser.startup.upgradeDialog.pinPBM.disabled",
+ true
+ );
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(
+ "browser.startup.upgradeDialog.pinPBM.disabled"
+ );
+ });
+ let sandbox = sinon.createSandbox();
+ // User needs default to ensure Pin Private window shows as third screen after import
+ sandbox
+ .stub(OnboardingMessageProvider, "_doesAppNeedDefault")
+ .resolves(true);
+
+ let pinStub = sandbox.stub(OnboardingMessageProvider, "_doesAppNeedPin");
+ pinStub.resolves(true);
+
+ const message = await OnboardingMessageProvider.getUpgradeMessage();
+ // Pin Private screen is not shown when pref is turned on
+ Assert.ok(
+ !getOnboardingScreenById(
+ message.content.screens,
+ "UPGRADE_PIN_PRIVATE_WINDOW"
+ )
+ );
+ sandbox.restore();
+ }
+);
diff --git a/browser/components/newtab/test/xpcshell/test_PanelTestProvider.js b/browser/components/newtab/test/xpcshell/test_PanelTestProvider.js
new file mode 100644
index 0000000000..d5c5c19f0c
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_PanelTestProvider.js
@@ -0,0 +1,83 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
+);
+
+const MESSAGE_VALIDATORS = {};
+let EXPERIMENT_VALIDATOR;
+
+add_setup(async function setup() {
+ const validators = await makeValidators();
+
+ EXPERIMENT_VALIDATOR = validators.experimentValidator;
+ Object.assign(MESSAGE_VALIDATORS, validators.messageValidators);
+});
+
+add_task(async function test_PanelTestProvider() {
+ const messages = await PanelTestProvider.getMessages();
+
+ const EXPECTED_MESSAGE_COUNTS = {
+ cfr_doorhanger: 1,
+ milestone_message: 0,
+ update_action: 1,
+ whatsnew_panel_message: 7,
+ spotlight: 2,
+ pb_newtab: 2,
+ toast_notification: 2,
+ };
+
+ const EXPECTED_TOTAL_MESSAGE_COUNT = Object.values(
+ EXPECTED_MESSAGE_COUNTS
+ ).reduce((a, b) => a + b, 0);
+
+ Assert.strictEqual(
+ messages.length,
+ EXPECTED_TOTAL_MESSAGE_COUNT,
+ "PanelTestProvider should have the correct number of messages"
+ );
+
+ const messageCounts = Object.assign(
+ {},
+ ...Object.keys(EXPECTED_MESSAGE_COUNTS).map(key => ({ [key]: 0 }))
+ );
+
+ for (const message of messages) {
+ const validator = MESSAGE_VALIDATORS[message.template];
+ Assert.ok(
+ typeof validator !== "undefined",
+ typeof validator !== "undefined"
+ ? `Schema validator found for ${message.template}`
+ : `No schema validator found for template ${message.template}. Please update this test to add one.`
+ );
+ assertValidates(
+ validator,
+ message,
+ `Message ${message.id} validates as ${message.template} template`
+ );
+ assertValidates(
+ EXPERIMENT_VALIDATOR,
+ message,
+ `Message ${message.id} validates as MessagingExperiment`
+ );
+
+ messageCounts[message.template]++;
+ }
+
+ for (const [template, count] of Object.entries(messageCounts)) {
+ Assert.equal(
+ count,
+ EXPECTED_MESSAGE_COUNTS[template],
+ `Expected ${EXPECTED_MESSAGE_COUNTS[template]} ${template} messages`
+ );
+ }
+});
+
+add_task(async function test_emptyMessage() {
+ info(
+ "Testing blank FxMS messages validate with the Messaging Experiment schema"
+ );
+
+ assertValidates(EXPERIMENT_VALIDATOR, {}, "Empty message should validate");
+});
diff --git a/browser/components/newtab/test/xpcshell/test_reach_experiments.js b/browser/components/newtab/test/xpcshell/test_reach_experiments.js
new file mode 100644
index 0000000000..240bda3594
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_reach_experiments.js
@@ -0,0 +1,97 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { ObjectUtils } = ChromeUtils.import(
+ "resource://gre/modules/ObjectUtils.jsm"
+);
+
+const MESSAGES = [
+ {
+ trigger: { id: "defaultBrowserCheck" },
+ targeting:
+ "source == 'startup' && !isMajorUpgrade && !activeNotifications && totalBookmarksCount == 5",
+ },
+ {
+ groups: ["eco"],
+ trigger: {
+ id: "defaultBrowserCheck",
+ },
+ targeting:
+ "source == 'startup' && !isMajorUpgrade && !activeNotifications && totalBookmarksCount == 5",
+ },
+];
+
+let EXPERIMENT_VALIDATOR;
+
+add_setup(async function setup() {
+ EXPERIMENT_VALIDATOR = await schemaValidatorFor(
+ "resource://activity-stream/schemas/MessagingExperiment.schema.json"
+ );
+});
+
+add_task(function test_reach_experiments_validation() {
+ for (const [index, message] of MESSAGES.entries()) {
+ assertValidates(
+ EXPERIMENT_VALIDATOR,
+ message,
+ `Message ${index} validates as a MessagingExperiment`
+ );
+ }
+});
+
+function depError(has, missing) {
+ return {
+ instanceLocation: "#",
+ keyword: "dependentRequired",
+ keywordLocation: "#/oneOf/1/allOf/0/$ref/dependantRequired",
+ error: `Instance has "${has}" but does not have "${missing}".`,
+ };
+}
+
+function assertContains(haystack, needle) {
+ Assert.ok(
+ haystack.find(item => ObjectUtils.deepEqual(item, needle)) !== null
+ );
+}
+
+add_task(function test_reach_experiment_dependentRequired() {
+ info(
+ "Testing that if id is present then content and template are not required"
+ );
+
+ {
+ const message = {
+ ...MESSAGES[0],
+ id: "message-id",
+ };
+
+ const result = EXPERIMENT_VALIDATOR.validate(message);
+ Assert.ok(result.valid, "message should validate");
+ }
+
+ info("Testing that if content is present then id and template are required");
+ {
+ const message = {
+ ...MESSAGES[0],
+ content: {},
+ };
+
+ const result = EXPERIMENT_VALIDATOR.validate(message);
+ Assert.ok(!result.valid, "message should not validate");
+ assertContains(result.errors, depError("content", "id"));
+ assertContains(result.errors, depError("content", "template"));
+ }
+
+ info("Testing that if template is present then id and content are required");
+ {
+ const message = {
+ ...MESSAGES[0],
+ template: "cfr",
+ };
+
+ const result = EXPERIMENT_VALIDATOR.validate(message);
+ Assert.ok(!result.valid, "message should not validate");
+ assertContains(result.errors, depError("template", "content"));
+ assertContains(result.errors, depError("template", "id"));
+ }
+});
diff --git a/browser/components/newtab/test/xpcshell/test_remoteExperiments.js b/browser/components/newtab/test/xpcshell/test_remoteExperiments.js
new file mode 100644
index 0000000000..6964d34023
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_remoteExperiments.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { CFRMessageProvider } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/CFRMessageProvider.sys.mjs"
+);
+
+add_task(async function test_multiMessageTreatment() {
+ const { experimentValidator } = await makeValidators();
+ // Use the entire list of messages as if it was a single treatment branch's
+ // feature value.
+ let messages = await CFRMessageProvider.getMessages();
+ let featureValue = { template: "multi", messages };
+ assertValidates(
+ experimentValidator,
+ featureValue,
+ `Multi-message treatment validates as MessagingExperiment`
+ );
+ for (const message of messages) {
+ assertValidates(
+ experimentValidator,
+ message,
+ `Message ${message.id} validates as MessagingExperiment`
+ );
+ }
+
+ // Add an invalid message to the list and make sure it fails validation.
+ messages.push({
+ id: "INVALID_MESSAGE",
+ template: "cfr_doorhanger",
+ });
+ const result = experimentValidator.validate(featureValue);
+ Assert.ok(
+ !(result.valid && result.errors.length === 0),
+ "Multi-message treatment with invalid message fails validation"
+ );
+});
diff --git a/browser/components/newtab/test/xpcshell/topstories.json b/browser/components/newtab/test/xpcshell/topstories.json
new file mode 100644
index 0000000000..7d65fcb0e1
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/topstories.json
@@ -0,0 +1,53 @@
+{
+ "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..807214219e
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/xpcshell.ini
@@ -0,0 +1,32 @@
+[DEFAULT]
+head = head.js
+firefox-appdir = browser
+skip-if = toolkit == 'android' # bug 1730213
+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
+skip-if =
+ socketprocess_networking # Bug 1759035
+
+[test_AboutNewTab.js]
+[test_AboutWelcomeAttribution.js]
+[test_ASRouterTargeting_attribution.js]
+skip-if =
+ toolkit != "cocoa" # osx specific tests
+ os == "mac" && bits == 64 # See bug 1784121
+[test_ASRouter_getTargetingParameters.js]
+[test_ASRouterTargeting_snapshot.js]
+[test_AboutWelcomeTelemetry.js]
+[test_CFRMessageProvider.js]
+[test_InflightAssetsMessageProvider.js]
+[test_OnboardingMessageProvider.js]
+[test_PanelTestProvider.js]
+[test_reach_experiments.js]
+[test_remoteExperiments.js]
+[test_AboutWelcomeTelemetry_glean.js]
diff --git a/browser/components/newtab/tools/babel-jsm-to-commonjs.js b/browser/components/newtab/tools/babel-jsm-to-commonjs.js
new file mode 100644
index 0000000000..0bf652da72
--- /dev/null
+++ b/browser/components/newtab/tools/babel-jsm-to-commonjs.js
@@ -0,0 +1,287 @@
+// The MIT License
+
+// Copyright (c) Kate Hudson <k88hudson@gmail.com>
+
+// 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.
+
+"use strict";
+
+const DEFAULT_OPTIONS = {
+ // Only Cu.imports matching the following pattern will be rewritten as import statements.
+ basePath: /^resource:\/\//,
+
+ // Should the import path be rewritten to exclude the basePath?
+ // e.g. if the basePath is "resource://}, "resource://foo.jsm" becomes "foo.jsm"
+ replace: false,
+};
+
+module.exports = function plugin(babel) {
+ const t = babel.types;
+ let exportItems = [];
+
+ // module.exports = {foo, bar, baz};
+ function createModuleExports(exportedIdentifiers) {
+ const left = t.memberExpression(
+ t.identifier("module"),
+ t.identifier("exports")
+ );
+ const right = t.objectExpression(
+ exportedIdentifiers.map(item => {
+ return t.objectProperty(
+ t.identifier(item),
+ t.identifier(item),
+ false,
+ true
+ );
+ // return typeof item === "string" ? t.objectProperty(item, item) : t.objectProperty(item[0], item[1]);
+ })
+ );
+ return t.expressionStatement(t.assignmentExpression("=", left, right));
+ }
+
+ function replaceExports(nodes) {
+ nodes.forEach(path => {
+ if (
+ path.isVariableDeclaration() &&
+ path.get("declarations")[0] &&
+ path.get("declarations")[0].node.id.name === "EXPORTED_SYMBOLS"
+ ) {
+ exportItems = path
+ .get("declarations")[0]
+ .get("init.elements")
+ .map(e => e.node.value);
+ path.remove();
+ } else if (
+ path.isExpressionStatement() &&
+ path.get("expression").isAssignmentExpression() &&
+ path.get("expression.left.object").isThisExpression() &&
+ path.get("expression.left.property").isIdentifier()
+ ) {
+ const left = path.node.expression.left.property;
+ const { right } = path.node.expression;
+ if (left.name === "EXPORTED_SYMBOLS") {
+ // const names = right.elements.map(el => el.value);
+ // path.replaceWith(createModuleExports(names));
+ exportItems = right.elements.map(el => el.value);
+ path.remove();
+ } else {
+ const decl = t.variableDeclaration("var", [
+ t.variableDeclarator(left, right),
+ ]);
+ if (left.name === right.name) {
+ path.remove();
+ } else {
+ path.replaceWith(decl);
+ }
+ }
+ }
+ });
+ }
+
+ function checkForDeclarations(nodes, id, initFinalResults = []) {
+ const results = [];
+ let finalResults = [...initFinalResults];
+ nodes.forEach(parentPath => {
+ if (!parentPath.isVariableDeclaration()) return;
+ parentPath.traverse({
+ VariableDeclarator(path) {
+ if (!path.get("id").isIdentifier()) return;
+ const init = path.get("init");
+ if (init.isIdentifier() && init.node.name === id) {
+ results.push(path.node.id.name);
+ }
+ },
+ });
+ });
+ if (results.length) {
+ finalResults.push(...results);
+ results.forEach(name => {
+ finalResults = checkForDeclarations(nodes, name, finalResults);
+ });
+ return finalResults;
+ }
+ return finalResults;
+ }
+
+ function checkForUtilsDeclarations(nodes, ids) {
+ const results = [];
+ nodes.forEach(parentPath => {
+ if (!parentPath.isVariableDeclaration()) return;
+ parentPath.traverse({
+ VariableDeclarator(path) {
+ const id = path.get("id");
+ const init = path.get("init");
+
+ // const {utils} = Components;
+ if (
+ id.isObjectPattern() &&
+ init.isIdentifier() &&
+ ids.includes(init.node.name)
+ ) {
+ id.node.properties.forEach(prop => {
+ if (prop.key.name === "utils") {
+ results.push(prop.value.name);
+ }
+ });
+ }
+
+ // const foo = Components.utils;
+ else if (
+ id.isIdentifier() &&
+ init.isMemberExpression() &&
+ init.get("object").isIdentifier() &&
+ ids.includes(init.get("object").node.name) &&
+ init.get("property").isIdentifier() &&
+ init.get("property").node.name === "utils"
+ ) {
+ results.push(id.node.name);
+ }
+ },
+ });
+ });
+ return results;
+ }
+
+ function replaceImports(
+ nodes,
+ ComponentNames,
+ CuNames,
+ basePath,
+ replacePath,
+ removeOtherImports
+ ) {
+ nodes.forEach(p => {
+ if (!p.isVariableDeclaration()) return;
+ p.traverse({
+ CallExpression(path) {
+ if (
+ t.isStringLiteral(path.node.arguments[0]) &&
+ // path.node.arguments[0].value.match(basePath) &&
+ t.isObjectPattern(path.parentPath.node.id) &&
+ // Check if actually Components.utils.import
+ path.get("callee").isMemberExpression() &&
+ (path.get("callee.property").node.name === "import" ||
+ path.get("callee.property").node.name === "importESModule")
+ ) {
+ const callee = path.get("callee");
+ if (callee.get("object").isMemberExpression()) {
+ if (
+ !ComponentNames.includes(
+ callee.get("object.object").node.name
+ ) ||
+ callee.get("object.property").node.name !== "utils"
+ ) {
+ return;
+ }
+ } else {
+ const objectName = callee.get("object").node.name;
+ if (
+ objectName !== "ChromeUtils" &&
+ !CuNames.includes(objectName)
+ ) {
+ return;
+ }
+ }
+ let filePath = path.node.arguments[0].value;
+
+ if (
+ !removeOtherImports ||
+ (replacePath && filePath.match(basePath))
+ ) {
+ if (replacePath) filePath = filePath.replace(basePath, "");
+ const requireStatement = t.callExpression(
+ t.identifier("require"),
+ [t.stringLiteral(filePath)]
+ );
+ path.replaceWith(requireStatement);
+ } else if (removeOtherImports) {
+ path.parentPath.parentPath.remove();
+ }
+ }
+ },
+ });
+ });
+ }
+
+ function replaceModuleGetters(paths, basePath, replacePath) {
+ paths.forEach(path => {
+ if (
+ path.isExpressionStatement() &&
+ path.get("expression").isCallExpression() &&
+ ["XPCOMUtils", "ChromeUtils"].includes(
+ path.get("expression.callee.object.name").node
+ ) &&
+ ["defineLazyModuleGetter", "defineModuleGetter"].includes(
+ path.get("expression.callee.property.name").node
+ )
+ ) {
+ const argPaths = path.get("expression.arguments");
+ const idName = argPaths[1].node.value;
+ let filePath = argPaths[2].node.value;
+
+ if (!filePath.match(basePath)) return;
+
+ if (replacePath) filePath = filePath.replace(basePath, "");
+ const requireStatement = t.callExpression(t.identifier("require"), [
+ t.stringLiteral(filePath),
+ ]);
+ const varDecl = t.variableDeclaration("var", [
+ t.variableDeclarator(
+ t.objectPattern([
+ t.objectProperty(
+ t.identifier(idName),
+ t.identifier(idName),
+ false,
+ true
+ ),
+ ]),
+ requireStatement
+ ),
+ ]);
+ path.replaceWith(varDecl);
+ }
+ });
+ }
+
+ return {
+ visitor: {
+ Program(path, state) {
+ const opts = Object.assign({}, DEFAULT_OPTIONS, state.opts);
+ const topLevelNodes = path.get("body");
+ const ids = checkForDeclarations(topLevelNodes, "Components", [
+ "Components",
+ ]);
+ const utils = checkForUtilsDeclarations(topLevelNodes, ids);
+ replaceImports(
+ topLevelNodes,
+ ids,
+ utils,
+ opts.basePath,
+ opts.replace,
+ opts.removeOtherImports
+ );
+ replaceModuleGetters(topLevelNodes, opts.basePath, opts.replace);
+ replaceExports(topLevelNodes);
+ if (exportItems.length) {
+ path.pushContainer("body", createModuleExports(exportItems));
+ }
+ },
+ },
+ };
+};
diff --git a/browser/components/newtab/tools/resourceUriPlugin.js b/browser/components/newtab/tools/resourceUriPlugin.js
new file mode 100644
index 0000000000..4de7c0ddf1
--- /dev/null
+++ b/browser/components/newtab/tools/resourceUriPlugin.js
@@ -0,0 +1,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/. */
+
+const path = require("path");
+
+// This plugin supports finding files for resource:/activity-stream/ uris,
+// translating the uri into a path relative to the browser/components/newtab/
+// directory where the file may be found.
+
+module.exports = {
+ ResourceUriPlugin: class ResourceUriPlugin {
+ #resourcePathRegEx;
+
+ constructor({ resourcePathRegEx }) {
+ this.#resourcePathRegEx = resourcePathRegEx;
+ }
+
+ apply(compiler) {
+ compiler.hooks.compilation.tap(
+ "ResourceUriPlugin",
+ (compilation, { normalModuleFactory }) => {
+ normalModuleFactory.hooks.resolveForScheme
+ .for("resource")
+ .tap("ResourceUriPlugin", resourceData => {
+ const url = new URL(resourceData.resource);
+ if (!url.href.match(this.#resourcePathRegEx)) {
+ return true;
+ }
+ const pathname = path.join(__dirname, "..", url.pathname);
+ resourceData.path = pathname;
+ resourceData.query = url.search;
+ resourceData.fragment = url.hash;
+ resourceData.resource = pathname + url.search + url.hash;
+ return true;
+ });
+ }
+ );
+ }
+ },
+};
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..55bc8dfbe9
--- /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..c4e142e45f
--- /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("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRedux={},e.React,e.ReactDOM)}(this,(function(e,t,r){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t);function u(){}function a(){}a.resetWarningCache=u;!function(){function e(e,t,r,n,o,u){if("SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==u){var a=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 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:a,resetWarningCache:u};r.PropTypes=r}();var c=o.default.createContext(null);var i=function(e){e()},f=function(){return i};var s={notify:function(){},get:function(){return[]}};function p(e,t){var r,n=s;function o(){a.onStateChange&&a.onStateChange()}function u(){r||(r=t?t.addNestedSub(o):e.subscribe(o),n=function(){var e=f(),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)}}}}())}var a={addNestedSub:function(e){return u(),n.subscribe(e)},notifyNestedSubs:function(){n.notify()},handleChangeWrapper:o,isSubscribed:function(){return!!r},trySubscribe:u,tryUnsubscribe:function(){r&&(r(),r=void 0,n.clear(),n=s)},getListeners:function(){return n}};return a}var l="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?t.useLayoutEffect:t.useEffect;function d(){return d=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},d.apply(this,arguments)}function y(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 v={exports:{}},m={},b="function"==typeof Symbol&&Symbol.for,S=b?Symbol.for("react.element"):60103,h=b?Symbol.for("react.portal"):60106,P=b?Symbol.for("react.fragment"):60107,g=b?Symbol.for("react.strict_mode"):60108,O=b?Symbol.for("react.profiler"):60114,w=b?Symbol.for("react.provider"):60109,C=b?Symbol.for("react.context"):60110,x=b?Symbol.for("react.async_mode"):60111,$=b?Symbol.for("react.concurrent_mode"):60111,M=b?Symbol.for("react.forward_ref"):60112,E=b?Symbol.for("react.suspense"):60113,T=b?Symbol.for("react.suspense_list"):60120,R=b?Symbol.for("react.memo"):60115,j=b?Symbol.for("react.lazy"):60116,N=b?Symbol.for("react.block"):60121,_=b?Symbol.for("react.fundamental"):60117,D=b?Symbol.for("react.responder"):60118,q=b?Symbol.for("react.scope"):60119;function F(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case S:switch(e=e.type){case x:case $:case P:case O:case g:case E:return e;default:switch(e=e&&e.$$typeof){case C:case M:case j:case R:case w:return e;default:return t}}case h:return t}}}function k(e){return F(e)===$}m.AsyncMode=x,m.ConcurrentMode=$,m.ContextConsumer=C,m.ContextProvider=w,m.Element=S,m.ForwardRef=M,m.Fragment=P,m.Lazy=j,m.Memo=R,m.Portal=h,m.Profiler=O,m.StrictMode=g,m.Suspense=E,m.isAsyncMode=function(e){return k(e)||F(e)===x},m.isConcurrentMode=k,m.isContextConsumer=function(e){return F(e)===C},m.isContextProvider=function(e){return F(e)===w},m.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===S},m.isForwardRef=function(e){return F(e)===M},m.isFragment=function(e){return F(e)===P},m.isLazy=function(e){return F(e)===j},m.isMemo=function(e){return F(e)===R},m.isPortal=function(e){return F(e)===h},m.isProfiler=function(e){return F(e)===O},m.isStrictMode=function(e){return F(e)===g},m.isSuspense=function(e){return F(e)===E},m.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===P||e===$||e===O||e===g||e===E||e===T||"object"==typeof e&&null!==e&&(e.$$typeof===j||e.$$typeof===R||e.$$typeof===w||e.$$typeof===C||e.$$typeof===M||e.$$typeof===_||e.$$typeof===D||e.$$typeof===q||e.$$typeof===N)},m.typeOf=F,v.exports=m;var H=v.exports,U={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},A={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},L={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},W={};function z(e){return H.isMemo(e)?L:W[e.$$typeof]||U}W[H.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},W[H.Memo]=L;var I=Object.defineProperty,V=Object.getOwnPropertyNames,K=Object.getOwnPropertySymbols,B=Object.getOwnPropertyDescriptor,Y=Object.getPrototypeOf,G=Object.prototype;var J=function e(t,r,n){if("string"!=typeof r){if(G){var o=Y(r);o&&o!==G&&e(t,o,n)}var u=V(r);K&&(u=u.concat(K(r)));for(var a=z(t),c=z(r),i=0;u.length>i;++i){var f=u[i];if(!(A[f]||n&&n[f]||c&&c[f]||a&&a[f])){var s=B(r,f);try{I(t,f,s)}catch(e){}}}}return t},Q={exports:{}},X={},Z=60103,ee=60106,te=60107,re=60108,ne=60114,oe=60109,ue=60110,ae=60112,ce=60113,ie=60120,fe=60115,se=60116,pe=60121,le=60122,de=60117,ye=60129,ve=60131;if("function"==typeof Symbol&&Symbol.for){var me=Symbol.for;Z=me("react.element"),ee=me("react.portal"),te=me("react.fragment"),re=me("react.strict_mode"),ne=me("react.profiler"),oe=me("react.provider"),ue=me("react.context"),ae=me("react.forward_ref"),ce=me("react.suspense"),ie=me("react.suspense_list"),fe=me("react.memo"),se=me("react.lazy"),pe=me("react.block"),le=me("react.server.block"),de=me("react.fundamental"),ye=me("react.debug_trace_mode"),ve=me("react.legacy_hidden")}function be(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case Z:switch(e=e.type){case te:case ne:case re:case ce:case ie:return e;default:switch(e=e&&e.$$typeof){case ue:case ae:case se:case fe:case oe:return e;default:return t}}case ee:return t}}}var Se=oe,he=Z,Pe=ae,ge=te,Oe=se,we=fe,Ce=ee,xe=ne,$e=re,Me=ce;X.ContextConsumer=ue,X.ContextProvider=Se,X.Element=he,X.ForwardRef=Pe,X.Fragment=ge,X.Lazy=Oe,X.Memo=we,X.Portal=Ce,X.Profiler=xe,X.StrictMode=$e,X.Suspense=Me,X.isAsyncMode=function(){return!1},X.isConcurrentMode=function(){return!1},X.isContextConsumer=function(e){return be(e)===ue},X.isContextProvider=function(e){return be(e)===oe},X.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===Z},X.isForwardRef=function(e){return be(e)===ae},X.isFragment=function(e){return be(e)===te},X.isLazy=function(e){return be(e)===se},X.isMemo=function(e){return be(e)===fe},X.isPortal=function(e){return be(e)===ee},X.isProfiler=function(e){return be(e)===ne},X.isStrictMode=function(e){return be(e)===re},X.isSuspense=function(e){return be(e)===ce},X.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===te||e===ne||e===ye||e===re||e===ce||e===ie||e===ve||"object"==typeof e&&null!==e&&(e.$$typeof===se||e.$$typeof===fe||e.$$typeof===oe||e.$$typeof===ue||e.$$typeof===ae||e.$$typeof===de||e.$$typeof===pe||e[0]===le)},X.typeOf=be,Q.exports=X;var Ee=["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef","forwardRef","context"],Te=["reactReduxForwardedRef"],Re=[],je=[null,null];function Ne(e,t){return[t.payload,e[1]+1]}function _e(e,t,r){l((function(){return e.apply(void 0,t)}),r)}function De(e,t,r,n,o,u,a){e.current=n,t.current=o,r.current=!1,u.current&&(u.current=null,a())}function qe(e,t,r,n,o,u,a,c,i,f){if(e){var s=!1,p=null,l=function(){if(!s){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||i():(u.current=e,c.current=e,a.current=!0,f({type:"STORE_UPDATED",payload:{error:r}}))}};r.onStateChange=l,r.trySubscribe(),l();return function(){if(s=!0,r.tryUnsubscribe(),r.onStateChange=null,p)throw p}}}var Fe=function(){return[null,0]};function ke(e,r){void 0===r&&(r={});var n=r,u=n.getDisplayName,a=void 0===u?function(e){return"ConnectAdvanced("+e+")"}:u,i=n.methodName,f=void 0===i?"connectAdvanced":i,s=n.renderCountProp,l=void 0===s?void 0:s,v=n.shouldHandleStateChanges,m=void 0===v||v,b=n.storeKey,S=void 0===b?"store":b,h=n.forwardRef,P=void 0!==h&&h,g=n.context,O=void 0===g?c:g,w=y(n,Ee),C=O;return function(r){var n=r.displayName||r.name||"Component",u=a(n),c=d({},w,{getDisplayName:a,methodName:f,renderCountProp:l,shouldHandleStateChanges:m,storeKey:S,displayName:u,wrappedComponentName:n,WrappedComponent:r}),i=w.pure;var s=i?t.useMemo:function(e){return e()};function v(n){var u=t.useMemo((function(){var e=n.reactReduxForwardedRef,t=y(n,Te);return[n.context,e,t]}),[n]),a=u[0],i=u[1],f=u[2],l=t.useMemo((function(){return a&&a.Consumer&&Q.exports.isContextConsumer(o.default.createElement(a.Consumer,null))?a:C}),[a,C]),v=t.useContext(l),b=!!n.store&&!!n.store.getState&&!!n.store.dispatch,S=b?n.store:v.store,h=t.useMemo((function(){return function(t){return e(t.dispatch,c)}(S)}),[S]),P=t.useMemo((function(){if(!m)return je;var e=p(S,b?null:v.subscription),t=e.notifyNestedSubs.bind(e);return[e,t]}),[S,b,v]),g=P[0],O=P[1],w=t.useMemo((function(){return b?v:d({},v,{subscription:g})}),[b,v,g]),x=t.useReducer(Ne,Re,Fe),$=x[0][0],M=x[1];if($&&$.error)throw $.error;var E=t.useRef(),T=t.useRef(f),R=t.useRef(),j=t.useRef(!1),N=s((function(){return R.current&&f===T.current?R.current:h(S.getState(),f)}),[S,$,f]);_e(De,[T,E,j,f,N,R,O]),_e(qe,[m,S,g,h,T,E,j,R,O,M],[S,g,h]);var _=t.useMemo((function(){return o.default.createElement(r,d({},N,{ref:i}))}),[i,r,N]);return t.useMemo((function(){return m?o.default.createElement(l.Provider,{value:w},_):_}),[l,_,w])}var b=i?o.default.memo(v):v;if(b.WrappedComponent=r,b.displayName=v.displayName=u,P){var h=o.default.forwardRef((function(e,t){return o.default.createElement(b,d({},e,{reactReduxForwardedRef:t}))}));return h.displayName=u,h.WrappedComponent=r,J(h,r)}return J(b,r)}}function He(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}function Ue(e,t){if(He(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])||!He(e[r[n]],t[r[n]]))return!1;return!0}function Ae(e){return function(t,r){var n=e(t,r);function o(){return n}return o.dependsOnOwnProps=!1,o}}function Le(e){return null!=e.dependsOnOwnProps?!!e.dependsOnOwnProps:1!==e.length}function We(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=Le(e);var o=n(t,r);return"function"==typeof o&&(n.mapToProps=o,n.dependsOnOwnProps=Le(o),o=n(t,r)),o},n}}var ze=[function(e){return"function"==typeof e?We(e):void 0},function(e){return e?void 0:Ae((function(e){return{dispatch:e}}))},function(e){return e&&"object"==typeof e?Ae((function(t){return function(e,t){var r={},n=function(n){var o=e[n];"function"==typeof o&&(r[n]=function(){return t(o.apply(void 0,arguments))})};for(var o in e)n(o);return r}(e,t)})):void 0}];var Ie=[function(e){return"function"==typeof e?We(e):void 0},function(e){return e?void 0:Ae((function(){return{}}))}];function Ve(e,t,r){return d({},r,e,t)}var Ke=[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,c){var i=e(t,r,c);return a?o&&u(i,n)||(n=i):(a=!0,n=i),n}}}(e):void 0},function(e){return e?void 0:function(){return Ve}}],Be=["initMapStateToProps","initMapDispatchToProps","initMergeProps"];function Ye(e,t,r,n){return function(o,u){return r(e(o,u),t(n,u),u)}}function Ge(e,t,r,n,o){var u,a,c,i,f,s=o.areStatesEqual,p=o.areOwnPropsEqual,l=o.areStatePropsEqual,d=!1;function y(o,d){var y,v,m=!p(d,a),b=!s(o,u);return u=o,a=d,m&&b?(c=e(u,a),t.dependsOnOwnProps&&(i=t(n,a)),f=r(c,i,a)):m?(e.dependsOnOwnProps&&(c=e(u,a)),t.dependsOnOwnProps&&(i=t(n,a)),f=r(c,i,a)):b?(y=e(u,a),v=!l(y,c),c=y,v&&(f=r(c,i,a)),f):f}return function(o,s){return d?y(o,s):(c=e(u=o,a=s),i=t(n,a),f=r(c,i,a),d=!0,f)}}function Je(e,t){var r=t.initMapStateToProps,n=t.initMapDispatchToProps,o=t.initMergeProps,u=y(t,Be),a=r(e,u),c=n(e,u),i=o(e,u);return(u.pure?Ge:Ye)(a,c,i,e,u)}var Qe=["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"];function Xe(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 Ze(e,t){return e===t}function et(e){var t=void 0===e?{}:e,r=t.connectHOC,n=void 0===r?ke:r,o=t.mapStateToPropsFactories,u=void 0===o?Ie:o,a=t.mapDispatchToPropsFactories,c=void 0===a?ze:a,i=t.mergePropsFactories,f=void 0===i?Ke:i,s=t.selectorFactory,p=void 0===s?Je:s;return function(e,t,r,o){void 0===o&&(o={});var a=o.pure,i=void 0===a||a,s=o.areStatesEqual,l=void 0===s?Ze:s,v=o.areOwnPropsEqual,m=void 0===v?Ue:v,b=o.areStatePropsEqual,S=void 0===b?Ue:b,h=o.areMergedPropsEqual,P=void 0===h?Ue:h,g=y(o,Qe),O=Xe(e,u,"mapStateToProps"),w=Xe(t,c,"mapDispatchToProps"),C=Xe(r,f,"mergeProps");return n(p,d({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:!!e,initMapStateToProps:O,initMapDispatchToProps:w,initMergeProps:C,pure:i,areStatesEqual:l,areOwnPropsEqual:m,areStatePropsEqual:S,areMergedPropsEqual:P},g))}}var tt=et();function rt(){return t.useContext(c)}function nt(e){void 0===e&&(e=c);var r=e===c?rt:function(){return t.useContext(e)};return function(){return r().store}}var ot=nt();function ut(e){void 0===e&&(e=c);var t=e===c?ot:nt(e);return function(){return t().dispatch}}var at=ut(),ct=function(e,t){return e===t};function it(e){void 0===e&&(e=c);var r=e===c?rt:function(){return t.useContext(e)};return function(e,n){void 0===n&&(n=ct);var o=r(),u=function(e,r,n,o){var u,a=t.useReducer((function(e){return e+1}),0)[1],c=t.useMemo((function(){return p(n,o)}),[n,o]),i=t.useRef(),f=t.useRef(),s=t.useRef(),d=t.useRef(),y=n.getState();try{if(e!==f.current||y!==s.current||i.current){var v=e(y);u=void 0!==d.current&&r(v,d.current)?d.current:v}else u=d.current}catch(e){throw i.current&&(e.message+="\nThe error may be correlated with this previous error:\n"+i.current.stack+"\n\n"),e}return l((function(){f.current=e,s.current=y,d.current=u,i.current=void 0})),l((function(){function e(){try{var e=n.getState();if(e===s.current)return;var t=f.current(e);if(r(t,d.current))return;d.current=t,s.current=e}catch(e){i.current=e}a()}return c.onStateChange=e,c.trySubscribe(),e(),function(){return c.tryUnsubscribe()}}),[n,c]),u}(e,n,o.store,o.subscription);return t.useDebugValue(u),u}}var ft=it();i=r.unstable_batchedUpdates,Object.defineProperty(e,"batch",{enumerable:!0,get:function(){return r.unstable_batchedUpdates}}),e.Provider=function(e){var r=e.store,n=e.context,u=e.children,a=t.useMemo((function(){var e=p(r);return e.onStateChange=e.notifyNestedSubs,{store:r,subscription:e}}),[r]),i=t.useMemo((function(){return r.getState()}),[r]);return l((function(){var e=a.subscription;return e.trySubscribe(),i!==r.getState()&&e.notifyNestedSubs(),function(){e.tryUnsubscribe(),e.onStateChange=null}}),[a,i]),o.default.createElement((n||c).Provider,{value:a},u)},e.ReactReduxContext=c,e.connect=tt,e.connectAdvanced=ke,e.createDispatchHook=ut,e.createSelectorHook=it,e.createStoreHook=nt,e.shallowEqual=Ue,e.useDispatch=at,e.useSelector=ft,e.useStore=ot,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..2b6247bdbc
--- /dev/null
+++ b/browser/components/newtab/vendor/react-transition-group.js
@@ -0,0 +1,9 @@
+!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 o(){return(o=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 i(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}function a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function s(e,t){return e(t={exports:{}},t.exports),t.exports
+/** @license React v16.13.1
+ * react-is.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.
+ */}n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n;var c="function"==typeof Symbol&&Symbol.for,l=c?Symbol.for("react.element"):60103,u=c?Symbol.for("react.portal"):60106,p=c?Symbol.for("react.fragment"):60107,d=c?Symbol.for("react.strict_mode"):60108,f=c?Symbol.for("react.profiler"):60114,h=c?Symbol.for("react.provider"):60109,m=c?Symbol.for("react.context"):60110,E=c?Symbol.for("react.async_mode"):60111,y=c?Symbol.for("react.concurrent_mode"):60111,x=c?Symbol.for("react.forward_ref"):60112,v=c?Symbol.for("react.suspense"):60113,g=c?Symbol.for("react.suspense_list"):60120,b=c?Symbol.for("react.memo"):60115,C=c?Symbol.for("react.lazy"):60116,S=c?Symbol.for("react.block"):60121,O=c?Symbol.for("react.fundamental"):60117,N=c?Symbol.for("react.responder"):60118,T=c?Symbol.for("react.scope"):60119;function k(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case l:switch(e=e.type){case E:case y:case p:case f:case d:case v:return e;default:switch(e=e&&e.$$typeof){case m:case x:case C:case b:case h:return e;default:return t}}case u:return t}}}function P(e){return k(e)===y}var w={AsyncMode:E,ConcurrentMode:y,ContextConsumer:m,ContextProvider:h,Element:l,ForwardRef:x,Fragment:p,Lazy:C,Memo:b,Portal:u,Profiler:f,StrictMode:d,Suspense:v,isAsyncMode:function(e){return P(e)||k(e)===E},isConcurrentMode:P,isContextConsumer:function(e){return k(e)===m},isContextProvider:function(e){return k(e)===h},isElement:function(e){return"object"==typeof e&&null!==e&&e.$$typeof===l},isForwardRef:function(e){return k(e)===x},isFragment:function(e){return k(e)===p},isLazy:function(e){return k(e)===C},isMemo:function(e){return k(e)===b},isPortal:function(e){return k(e)===u},isProfiler:function(e){return k(e)===f},isStrictMode:function(e){return k(e)===d},isSuspense:function(e){return k(e)===v},isValidElementType:function(e){return"string"==typeof e||"function"==typeof e||e===p||e===y||e===f||e===d||e===v||e===g||"object"==typeof e&&null!==e&&(e.$$typeof===C||e.$$typeof===b||e.$$typeof===h||e.$$typeof===m||e.$$typeof===x||e.$$typeof===O||e.$$typeof===N||e.$$typeof===T||e.$$typeof===S)},typeOf:k},j=s((function(e,t){})),M=(j.AsyncMode,j.ConcurrentMode,j.ContextConsumer,j.ContextProvider,j.Element,j.ForwardRef,j.Fragment,j.Lazy,j.Memo,j.Portal,j.Profiler,j.StrictMode,j.Suspense,j.isAsyncMode,j.isConcurrentMode,j.isContextConsumer,j.isContextProvider,j.isElement,j.isForwardRef,j.isFragment,j.isLazy,j.isMemo,j.isPortal,j.isProfiler,j.isStrictMode,j.isSuspense,j.isValidElementType,j.typeOf,s((function(e){e.exports=w})),Object.getOwnPropertySymbols),R=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable;function A(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(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,Function.call.bind(Object.prototype.hasOwnProperty);function L(){}function _(){}_.resetWarningCache=L;var D=s((function(e){e.exports=function(){function e(e,t,n,r,o,i){if("SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==i){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,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:_,resetWarningCache:L};return n.PropTypes=n,n}()}));D.object,D.oneOfType,D.element,D.bool,D.func;function F(e,t){return e.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}var V={disabled:!1},I=r.createContext(null),U="entering",q="entered",z=function(e){function t(t,n){var r;r=e.call(this,t,n)||this;var o,i=n&&!n.isMounting?t.enter:t.appear;return r.appearStatus=null,t.in?i?(o="exited",r.appearStatus=U):o=q:o=t.unmountOnExit||t.mountOnEnter?"unmounted":"exited",r.state={status:o},r.nextCallback=null,r}a(t,e),t.getDerivedStateFromProps=function(e,t){return e.in&&"unmounted"===t.status?{status:"exited"}:null};var o=t.prototype;return o.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},o.componentDidUpdate=function(e){var t=null;if(e!==this.props){var n=this.state.status;this.props.in?n!==U&&n!==q&&(t=U):n!==U&&n!==q||(t="exiting")}this.updateStatus(!1,t)},o.componentWillUnmount=function(){this.cancelNextCallback()},o.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}},o.updateStatus=function(e,t){void 0===e&&(e=!1),null!==t?(this.cancelNextCallback(),t===U?this.performEnter(e):this.performExit()):this.props.unmountOnExit&&"exited"===this.state.status&&this.setState({status:"unmounted"})},o.performEnter=function(e){var t=this,r=this.props.enter,o=this.context?this.context.isMounting:e,i=this.props.nodeRef?[o]:[n.findDOMNode(this),o],a=i[0],s=i[1],c=this.getTimeouts(),l=o?c.appear:c.enter;!e&&!r||V.disabled?this.safeSetState({status:q},(function(){t.props.onEntered(a)})):(this.props.onEnter(a,s),this.safeSetState({status:U},(function(){t.props.onEntering(a,s),t.onTransitionEnd(l,(function(){t.safeSetState({status:q},(function(){t.props.onEntered(a,s)}))}))})))},o.performExit=function(){var e=this,t=this.props.exit,r=this.getTimeouts(),o=this.props.nodeRef?void 0:n.findDOMNode(this);t&&!V.disabled?(this.props.onExit(o),this.safeSetState({status:"exiting"},(function(){e.props.onExiting(o),e.onTransitionEnd(r.exit,(function(){e.safeSetState({status:"exited"},(function(){e.props.onExited(o)}))}))}))):this.safeSetState({status:"exited"},(function(){e.props.onExited(o)}))},o.cancelNextCallback=function(){null!==this.nextCallback&&(this.nextCallback.cancel(),this.nextCallback=null)},o.safeSetState=function(e,t){t=this.setNextCallback(t),this.setState(e,t)},o.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},o.onTransitionEnd=function(e,t){this.setNextCallback(t);var r=this.props.nodeRef?this.props.nodeRef.current:n.findDOMNode(this),o=null==e&&!this.props.addEndListener;if(r&&!o){if(this.props.addEndListener){var i=this.props.nodeRef?[this.nextCallback]:[r,this.nextCallback],a=i[0],s=i[1];this.props.addEndListener(a,s)}null!=e&&setTimeout(this.nextCallback,e)}else setTimeout(this.nextCallback,0)},o.render=function(){var e=this.state.status;if("unmounted"===e)return null;var t=this.props,n=t.children,o=(t.in,t.mountOnEnter,t.unmountOnExit,t.appear,t.enter,t.exit,t.timeout,t.addEndListener,t.onEnter,t.onEntering,t.onEntered,t.onExit,t.onExiting,t.onExited,t.nodeRef,i(t,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]));return r.createElement(I.Provider,{value:null},"function"==typeof n?n(e,o):r.cloneElement(r.Children.only(n),o))},t}(r.Component);function W(){}z.contextType=I,z.propTypes={},z.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:W,onEntering:W,onEntered:W,onExit:W,onExiting:W,onExited:W},z.UNMOUNTED="unmounted",z.EXITED="exited",z.ENTERING=U,z.ENTERED=q,z.EXITING="exiting";var G=function(e,t){return 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}))},X=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=F(n.className,r):n.setAttribute("class",F(n.className&&n.className.baseVal||"",r)));var n,r}))},B=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return(t=e.call.apply(e,[this].concat(r))||this).appliedClasses={appear:{},enter:{},exit:{}},t.onEnter=function(e,n){var r=t.resolveArguments(e,n),o=r[0],i=r[1];t.removeClasses(o,"exit"),t.addClass(o,i?"appear":"enter","base"),t.props.onEnter&&t.props.onEnter(e,n)},t.onEntering=function(e,n){var r=t.resolveArguments(e,n),o=r[0],i=r[1]?"appear":"enter";t.addClass(o,i,"active"),t.props.onEntering&&t.props.onEntering(e,n)},t.onEntered=function(e,n){var r=t.resolveArguments(e,n),o=r[0],i=r[1]?"appear":"enter";t.removeClasses(o,i),t.addClass(o,i,"done"),t.props.onEntered&&t.props.onEntered(e,n)},t.onExit=function(e){var n=t.resolveArguments(e)[0];t.removeClasses(n,"appear"),t.removeClasses(n,"enter"),t.addClass(n,"exit","base"),t.props.onExit&&t.props.onExit(e)},t.onExiting=function(e){var n=t.resolveArguments(e)[0];t.addClass(n,"exit","active"),t.props.onExiting&&t.props.onExiting(e)},t.onExited=function(e){var n=t.resolveArguments(e)[0];t.removeClasses(n,"exit"),t.addClass(n,"exit","done"),t.props.onExited&&t.props.onExited(e)},t.resolveArguments=function(e,n){return t.props.nodeRef?[t.props.nodeRef.current,e]:[e,n]},t.getClassNames=function(e){var n=t.props.classNames,r="string"==typeof n,o=r?""+(r&&n?n+"-":"")+e:n[e];return{baseClassName:o,activeClassName:r?o+"-active":n[e+"Active"],doneClassName:r?o+"-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"],o=this.getClassNames("enter").doneClassName;"appear"===t&&"done"===n&&o&&(r+=" "+o),"active"===n&&e&&e.scrollTop,r&&(this.appliedClasses[t][n]=r,G(e,r))},n.removeClasses=function(e,t){var n=this.appliedClasses[t],r=n.base,o=n.active,i=n.done;this.appliedClasses[t]={},r&&X(e,r),o&&X(e,o),i&&X(e,i)},n.render=function(){var e=this.props,t=(e.classNames,i(e,["classNames"]));return r.createElement(z,o({},t,{onEnter:this.onEnter,onEntered:this.onEntered,onEntering:this.onEntering,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}))},t}(r.Component);function H(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 Y(e,t,n){return null!=n[t]?n[t]:e.props[t]}function J(e,n,r){var o=H(e.children),i=function(e,t){function n(n){return n in t?t[n]:e[n]}e=e||{},t=t||{};var r,o=Object.create(null),i=[];for(var a in e)a in t?i.length&&(o[a]=i,i=[]):i.push(a);var s={};for(var c in t){if(o[c])for(r=0;r<o[c].length;r++){var l=o[c][r];s[o[c][r]]=n(l)}s[c]=n(c)}for(r=0;r<i.length;r++)s[i[r]]=n(i[r]);return s}(n,o);return Object.keys(i).forEach((function(a){var s=i[a];if(t.isValidElement(s)){var c=a in n,l=a in o,u=n[a],p=t.isValidElement(u)&&!u.props.in;!l||c&&!p?l||!c||p?l&&c&&t.isValidElement(u)&&(i[a]=t.cloneElement(s,{onExited:r.bind(null,s),in:u.props.in,exit:Y(s,"exit",e),enter:Y(s,"enter",e)})):i[a]=t.cloneElement(s,{in:!1}):i[a]=t.cloneElement(s,{onExited:r.bind(null,s),in:!0,exit:Y(s,"exit",e),enter:Y(s,"enter",e)})}})),i}B.defaultProps={classNames:""},B.propTypes={};var K=Object.values||function(e){return Object.keys(e).map((function(t){return e[t]}))},Q=function(e){function n(t,n){var r,o=(r=e.call(this,t,n)||this).handleExited.bind(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(r));return r.state={contextValue:{isMounting:!0},handleExited:o,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,o,i=n.children,a=n.handleExited;return{children:n.firstRender?(r=e,o=a,H(r.children,(function(e){return t.cloneElement(e,{onExited:o.bind(null,e),in:!0,appear:Y(e,"appear",r),enter:Y(e,"enter",r),exit:Y(e,"exit",r)})}))):J(e,i,a),firstRender:!1}},s.handleExited=function(e,t){var n=H(this.props.children);e.key in n||(e.props.onExited&&e.props.onExited(t),this.mounted&&this.setState((function(t){var n=o({},t.children);return delete n[e.key],{children:n}})))},s.render=function(){var e=this.props,t=e.component,n=e.childFactory,o=i(e,["component","childFactory"]),a=this.state.contextValue,s=K(this.state.children).map(n);return delete o.appear,delete o.enter,delete o.exit,null===t?r.createElement(I.Provider,{value:a},s):r.createElement(I.Provider,{value:a},r.createElement(t,o,s))},n}(r.Component);Q.propTypes={},Q.defaultProps={component:"div",childFactory:function(e){return e}};var Z,ee,te=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];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 o=t.prototype;return o.handleLifecycle=function(e,t,o){var i,a=this.props.children,s=r.Children.toArray(a)[t];if(s.props[e]&&(i=s.props)[e].apply(i,o),this.props[e]){var c=s.props.nodeRef?void 0:n.findDOMNode(this);this.props[e](c)}},o.render=function(){var e=this.props,t=e.children,n=e.in,o=i(e,["children","in"]),a=r.Children.toArray(t),s=a[0],c=a[1];return delete o.onEnter,delete o.onEntering,delete o.onEntered,delete o.onExit,delete o.onExiting,delete o.onExited,r.createElement(Q,o,n?r.cloneElement(s,{key:"first",onEnter:this.handleEnter,onEntering:this.handleEntering,onEntered:this.handleEntered}):r.cloneElement(c,{key:"second",onEnter:this.handleExit,onEntering:this.handleExiting,onEntered:this.handleExited}))},t}(r.Component);te.propTypes={};var ne="out-in",re="in-out",oe=function(e,t,n){return function(){var r;e.props[t]&&(r=e.props)[t].apply(r,arguments),n()}},ie=((Z={})[ne]=function(e){var t=e.current,n=e.changeState;return r.cloneElement(t,{in:!1,onExited:oe(t,"onExited",(function(){n(U,null)}))})},Z[re]=function(e){var t=e.current,n=e.changeState,o=e.children;return[t,r.cloneElement(o,{in:!0,onEntered:oe(o,"onEntered",(function(){n(U)}))})]},Z),ae=((ee={})[ne]=function(e){var t=e.children,n=e.changeState;return r.cloneElement(t,{in:!0,onEntered:oe(t,"onEntered",(function(){n(q,r.cloneElement(t,{in:!0}))}))})},ee[re]=function(e){var t=e.current,n=e.children,o=e.changeState;return[r.cloneElement(t,{in:!1,onExited:oe(t,"onExited",(function(){o(q,r.cloneElement(n,{in:!0}))}))}),r.cloneElement(n,{in:!0})]},ee),se=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return(t=e.call.apply(e,[this].concat(r))||this).state={status:q,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===U&&e.mode===re?{status:U}:!t.current||(n=t.current,o=e.children,n===o||r.isValidElement(n)&&r.isValidElement(o)&&null!=n.key&&n.key===o.key)?{current:r.cloneElement(e.children,{in:!0})}:{status:"exiting"};var n,o},n.render=function(){var e,t=this.props,n=t.children,o=t.mode,i=this.state,a=i.status,s=i.current,c={children:n,current:s,changeState:this.changeState,status:a};switch(a){case U:e=ae[o](c);break;case"exiting":e=ie[o](c);break;case q:e=s}return r.createElement(I.Provider,{value:{isMounting:!this.appeared}},e)},t}(r.Component);se.propTypes={},se.defaultProps={mode:ne},e.CSSTransition=B,e.ReplaceTransition=te,e.SwitchTransition=se,e.Transition=z,e.TransitionGroup=Q,e.config=V,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..6cbe9e60cc
--- /dev/null
+++ b/browser/components/newtab/webpack.system-addon.config.js
@@ -0,0 +1,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 path = require("path");
+const webpack = require("webpack");
+const { ResourceUriPlugin } = require("./tools/resourceUriPlugin");
+
+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: [
+ // The ResourceUriPlugin handles translating resource URIs in import
+ // statements in .mjs files, in a similar way to what babel-jsm-to-commonjs
+ // does for jsm files.
+ new ResourceUriPlugin({ resourcePathRegEx }),
+ new webpack.BannerPlugin(
+ `THIS FILE IS AUTO-GENERATED: ${path.basename(__filename)}`
+ ),
+ new webpack.optimize.ModuleConcatenationPlugin(),
+ ],
+ module: {
+ rules: [
+ {
+ test: /\.jsx?$/,
+ exclude: /node_modules\/(?!@fluent\/).*/,
+ 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: [
+ [
+ "./tools/babel-jsm-to-commonjs.js",
+ {
+ 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", "."],
+ fallback: {
+ stream: require.resolve("stream-browserify"),
+ },
+ },
+ 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..81060bf320
--- /dev/null
+++ b/browser/components/newtab/yamscripts.yml
@@ -0,0 +1,58 @@
+# This file compiles to package.json scripts.
+# When you add or modify anything, you *MUST* run:
+# npm run yamscripts
+# to compile your changes.
+
+scripts:
+ # bundle: Build all assets for activity stream
+ bundle:
+ webpack: webpack-cli --config webpack.system-addon.config.js
+ css: sass content-src/styles:css --no-source-map
+ welcomeBundle: webpack-cli --config webpack.aboutwelcome.config.js
+ welcomeCss: sass content-src/aboutwelcome:aboutwelcome/content --no-source-map
+ 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
+ css: =>bundle:css -- --source-map --embed-sources --embed-source-map --load-path=content-src -w
+ welcomeBundle: =>bundle:welcomeBundle -- --env development -w
+ welcomeCss: =>bundle:welcomeCss -- --source-map --embed-sources --embed-source-map -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/lcov-report/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 soft browser/locales/en-US/browser/newtab)
+ license: (cd $npm_package_config_mc_root && ./mach lint -l license $npm_package_config_newtab_path)
+ stylelint: (cd $npm_package_config_mc_root && ./mach lint -l stylelint $npm_package_config_newtab_path)
+
+ # 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
+ stylelint: =>lint:stylelint -- --fix