summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab
diff options
context:
space:
mode:
Diffstat (limited to 'browser/components/newtab')
-rw-r--r--browser/components/newtab/.eslintrc.js184
-rw-r--r--browser/components/newtab/.nvmrc1
-rw-r--r--browser/components/newtab/AboutNewTabService.sys.mjs510
-rw-r--r--browser/components/newtab/bin/render-activity-stream-html.js188
-rw-r--r--browser/components/newtab/bin/try-runner.js366
-rw-r--r--browser/components/newtab/bin/vendor.js38
-rw-r--r--browser/components/newtab/common/Actions.sys.mjs457
-rw-r--r--browser/components/newtab/common/Dedupe.sys.mjs36
-rw-r--r--browser/components/newtab/common/Reducers.sys.mjs855
-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/activity-stream.jsx57
-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/Base/Base.jsx262
-rw-r--r--browser/components/newtab/content-src/components/Base/_Base.scss126
-rw-r--r--browser/components/newtab/content-src/components/Card/Card.jsx362
-rw-r--r--browser/components/newtab/content-src/components/Card/_Card.scss333
-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.scss108
-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.scss59
-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.jsx270
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx85
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss244
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.jsx506
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.scss337
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamAdmin/SimpleHashRouter.jsx35
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx386
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss67
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx542
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss352
-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.jsx529
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss303
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx145
-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.jsx56
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss48
-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.scss47
-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.scss182
-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.scss79
-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.scss90
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx251
-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/ModalOverlay/ModalOverlay.jsx56
-rw-r--r--browser/components/newtab/content-src/components/ModalOverlay/_ModalOverlay.scss103
-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.jsx189
-rw-r--r--browser/components/newtab/content-src/components/Search/_Search.scss394
-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.jsx889
-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.scss631
-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/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.js140
-rw-r--r--browser/components/newtab/content-src/lib/link-menu-options.js309
-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.scss172
-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.scss97
-rw-r--r--browser/components/newtab/content-src/styles/_variables.scss215
-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.css4248
-rw-r--r--browser/components/newtab/css/activity-stream-mac.css4252
-rw-r--r--browser/components/newtab/css/activity-stream-windows.css4248
-rw-r--r--browser/components/newtab/data/content/abouthomecache/page.html.template46
-rw-r--r--browser/components/newtab/data/content/abouthomecache/script.js.template19
-rw-r--r--browser/components/newtab/data/content/activity-stream.bundle.js9558
-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/icon-removed-bookmark.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/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.rst119
-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_events.md19
-rw-r--r--browser/components/newtab/docs/v2-system-addon/geo_locale.md23
-rw-r--r--browser/components/newtab/docs/v2-system-addon/mochitests.md26
-rw-r--r--browser/components/newtab/docs/v2-system-addon/preferences.md270
-rw-r--r--browser/components/newtab/docs/v2-system-addon/sections.md82
-rw-r--r--browser/components/newtab/docs/v2-system-addon/telemetry.md10
-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.mn40
-rw-r--r--browser/components/newtab/karma.mc.config.js287
-rw-r--r--browser/components/newtab/lib/AboutPreferences.sys.mjs298
-rw-r--r--browser/components/newtab/lib/ActivityStream.sys.mjs700
-rw-r--r--browser/components/newtab/lib/ActivityStreamMessageChannel.sys.mjs333
-rw-r--r--browser/components/newtab/lib/ActivityStreamPrefs.sys.mjs100
-rw-r--r--browser/components/newtab/lib/ActivityStreamStorage.sys.mjs119
-rw-r--r--browser/components/newtab/lib/DefaultSites.sys.mjs46
-rw-r--r--browser/components/newtab/lib/DiscoveryStreamFeed.sys.mjs2265
-rw-r--r--browser/components/newtab/lib/DownloadsManager.sys.mjs188
-rw-r--r--browser/components/newtab/lib/FaviconFeed.sys.mjs198
-rw-r--r--browser/components/newtab/lib/FilterAdult.sys.mjs3040
-rw-r--r--browser/components/newtab/lib/HighlightsFeed.sys.mjs322
-rw-r--r--browser/components/newtab/lib/LinksCache.sys.mjs133
-rw-r--r--browser/components/newtab/lib/NewTabInit.sys.mjs55
-rw-r--r--browser/components/newtab/lib/PersistentCache.sys.mjs90
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.mjs60
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.mjs58
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.sys.mjs277
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.worker.mjs26
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.mjs306
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.mjs1119
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/Tokenize.mjs83
-rw-r--r--browser/components/newtab/lib/PlacesFeed.sys.mjs572
-rw-r--r--browser/components/newtab/lib/PrefsFeed.sys.mjs273
-rw-r--r--browser/components/newtab/lib/RecommendationProvider.sys.mjs291
-rw-r--r--browser/components/newtab/lib/Screenshots.sys.mjs140
-rw-r--r--browser/components/newtab/lib/SearchShortcuts.sys.mjs73
-rw-r--r--browser/components/newtab/lib/SectionsManager.sys.mjs715
-rw-r--r--browser/components/newtab/lib/ShortURL.sys.mjs88
-rw-r--r--browser/components/newtab/lib/SiteClassifier.sys.mjs103
-rw-r--r--browser/components/newtab/lib/Store.sys.mjs188
-rw-r--r--browser/components/newtab/lib/SystemTickFeed.sys.mjs70
-rw-r--r--browser/components/newtab/lib/TelemetryFeed.sys.mjs1122
-rw-r--r--browser/components/newtab/lib/TippyTopProvider.sys.mjs60
-rw-r--r--browser/components/newtab/lib/TopSitesFeed.sys.mjs2007
-rw-r--r--browser/components/newtab/lib/TopStoriesFeed.sys.mjs731
-rw-r--r--browser/components/newtab/lib/UTEventReporting.sys.mjs62
-rw-r--r--browser/components/newtab/lib/cache.worker.js203
-rw-r--r--browser/components/newtab/loaders/inject-loader.js59
-rw-r--r--browser/components/newtab/metrics.yaml1589
-rw-r--r--browser/components/newtab/moz.build35
-rw-r--r--browser/components/newtab/nsIAboutNewTabService.idl39
-rw-r--r--browser/components/newtab/package-lock.json12455
-rw-r--r--browser/components/newtab/package.json115
-rw-r--r--browser/components/newtab/pings.yaml75
-rw-r--r--browser/components/newtab/prerendered/activity-stream-debug.html55
-rw-r--r--browser/components/newtab/prerendered/activity-stream-noscripts.html44
-rw-r--r--browser/components/newtab/prerendered/activity-stream.html55
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser.toml52
-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.js82
-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.js365
-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.toml81
-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_context_menu_item.js18
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_content.js219
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_render.js28
-rw-r--r--browser/components/newtab/test/browser/browser_discovery_card.js49
-rw-r--r--browser/components/newtab/test/browser/browser_discovery_render.js31
-rw-r--r--browser/components/newtab/test/browser/browser_enabled_newtabpage.js33
-rw-r--r--browser/components/newtab/test/browser/browser_foxdoodle_set_default.js69
-rw-r--r--browser/components/newtab/test/browser/browser_getScreenshots.js88
-rw-r--r--browser/components/newtab/test/browser/browser_highlights_section.js96
-rw-r--r--browser/components/newtab/test/browser/browser_multistage_spotlight.js90
-rw-r--r--browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js141
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_glean.js28
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_header.js76
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js153
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_overrides.js134
-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.js38
-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.js304
-rw-r--r--browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js153
-rw-r--r--browser/components/newtab/test/browser/file_pdf.PDF12
-rw-r--r--browser/components/newtab/test/browser/head.js244
-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/topstories.json11
-rw-r--r--browser/components/newtab/test/schemas/asrouter_event_ping.schema.json36
-rw-r--r--browser/components/newtab/test/schemas/base_ping.schema.json29
-rw-r--r--browser/components/newtab/test/schemas/pings.js181
-rw-r--r--browser/components/newtab/test/schemas/session_ping.schema.json122
-rw-r--r--browser/components/newtab/test/schemas/user_event_ping.schema.json75
-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.js1525
-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/DiscoveryStreamAdmin.test.jsx267
-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.jsx138
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx582
-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.jsx96
-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.jsx276
-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/LinkMenu.test.jsx667
-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.jsx1930
-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.jsx148
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Topics.test.jsx22
-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.js155
-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.js445
-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.js3523
-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/LinksCache.test.js16
-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/PrefsFeed.test.js357
-rw-r--r--browser/components/newtab/test/unit/lib/RecommendationProvider.test.js331
-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/SystemTickFeed.test.js79
-rw-r--r--browser/components/newtab/test/unit/lib/TippyTopProvider.test.js121
-rw-r--r--browser/components/newtab/test/unit/lib/UTEventReporting.test.js115
-rw-r--r--browser/components/newtab/test/unit/unit-entry.js733
-rw-r--r--browser/components/newtab/test/unit/utils.js406
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js33
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js255
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutNewTab.js363
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js69
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js90
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry_glean.js238
-rw-r--r--browser/components/newtab/test/xpcshell/test_HighlightsFeed.js1402
-rw-r--r--browser/components/newtab/test/xpcshell/test_PlacesFeed.js1812
-rw-r--r--browser/components/newtab/test/xpcshell/test_Store.js453
-rw-r--r--browser/components/newtab/test/xpcshell/test_TelemetryFeed.js3285
-rw-r--r--browser/components/newtab/test/xpcshell/test_TopSitesFeed.js3397
-rw-r--r--browser/components/newtab/test/xpcshell/test_TopSitesFeed_glean.js2023
-rw-r--r--browser/components/newtab/test/xpcshell/topstories.json53
-rw-r--r--browser/components/newtab/test/xpcshell/xpcshell.toml34
-rw-r--r--browser/components/newtab/tools/resourceUriPlugin.js65
-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.sys.mjs691
-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.system-addon.config.js65
-rw-r--r--browser/components/newtab/yamscripts.yml60
440 files changed, 146464 insertions, 0 deletions
diff --git a/browser/components/newtab/.eslintrc.js b/browser/components/newtab/.eslintrc.js
new file mode 100644
index 0000000000..5fc7a4dcff
--- /dev/null
+++ b/browser/components/newtab/.eslintrc.js
@@ -0,0 +1,184 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.
+ plugins: ["import", "react", "jsx-a11y"],
+ settings: {
+ react: {
+ version: "16.2.0",
+ },
+ },
+ extends: ["plugin:jsx-a11y/recommended"],
+ overrides: [
+ {
+ // TODO: Bug 1773467 - Move these to .mjs or figure out a generic way
+ // to identify these as modules.
+ files: [
+ "content-src/**/*.js",
+ "test/schemas/**/*.js",
+ "test/unit/**/*.js",
+ ],
+ parserOptions: {
+ sourceType: "module",
+ },
+ },
+ {
+ // These files use fluent-dom to insert content
+ files: [
+ "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/**",
+ "loaders/**",
+ "tools/**",
+ "test/unit/**",
+ ],
+ env: {
+ node: true,
+ },
+ },
+ {
+ // Use a configuration that's appropriate for modules, workers and
+ // non-production files.
+ files: ["*.jsm", "lib/cache.worker.js", "test/**"],
+ rules: {
+ "no-implicit-globals": "off",
+ },
+ },
+ {
+ files: ["content-src/**", "test/unit/**"],
+ rules: {
+ // Disallow commonjs in these directories.
+ "import/no-commonjs": 2,
+ },
+ },
+ {
+ // These tests simulate the browser environment.
+ files: "test/unit/**",
+ env: {
+ browser: true,
+ mocha: true,
+ },
+ globals: {
+ assert: true,
+ chai: true,
+ sinon: true,
+ },
+ },
+ {
+ files: "test/**",
+ rules: {
+ "func-name-matching": 0,
+ "lines-between-class-members": 0,
+ },
+ },
+ ],
+ rules: {
+ "fetch-options/no-fetch-credentials": "error",
+
+ "react/jsx-boolean-value": ["error", "always"],
+ "react/jsx-key": "error",
+ "react/jsx-no-bind": [
+ "error",
+ { allowArrowFunctions: true, allowFunctions: true },
+ ],
+ "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",
+ "func-name-matching": "error",
+ "getter-return": "error",
+ "guard-for-in": "error",
+ "max-depth": ["error", 4],
+ "max-nested-callbacks": ["error", 4],
+ "max-params": ["error", 6],
+ "max-statements": ["error", 50],
+ "new-cap": ["error", { newIsCap: true, capIsNew: false }],
+ "no-alert": "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-multi-assign": "error",
+ "no-multi-str": "error",
+ "no-new": "error",
+ "no-new-func": "error",
+ "no-octal-escape": "error",
+ "no-param-reassign": "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"],
+ "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.sys.mjs b/browser/components/newtab/AboutNewTabService.sys.mjs
new file mode 100644
index 0000000000..e73e1b1880
--- /dev/null
+++ b/browser/components/newtab/AboutNewTabService.sys.mjs
@@ -0,0 +1,510 @@
+/**
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 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.
+ */
+
+import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
+import { E10SUtils } from "resource://gre/modules/E10SUtils.sys.mjs";
+import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.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 =
+ "chrome://browser/content/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.
+ */
+export 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.
+ */
+export function AboutNewTabStubService() {
+ if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_DEFAULT) {
+ return new BaseAboutNewTabService();
+ }
+ return new AboutNewTabChildService();
+}
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..41b77c35db
--- /dev/null
+++ b/browser/components/newtab/bin/render-activity-stream-html.js
@@ -0,0 +1,188 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-disable no-console */
+const fs = require("fs");
+const { mkdir } = require("shelljs");
+const path = require("path");
+const { pathToFileURL } = require("url");
+const chalk = require("chalk");
+
+const DEFAULT_OPTIONS = {
+ // Glob leading from CWD to the parent of the intended prerendered directory.
+ // Starting in newtab/bin/ and we want to write to newtab/prerendered/ so we
+ // go up one level.
+ addonPath: "..",
+ // depends on the registration in browser/components/newtab/jar.mn
+ 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 AboutNewTabChild.sys.mjs
+ 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://global/skin/design-system/tokens-brand.css"
+ />
+ <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>${options.noscripts ? "" : scriptRender}
+ <script
+ async
+ type="module"
+ src="chrome://global/content/elements/moz-toggle.mjs"
+ ></script>
+ </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(chalk.green(`✓ ${file}`));
+ }
+}
+
+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.
+ */
+async function main() {
+ const { default: meow } = await import("meow");
+ const fileUrl = pathToFileURL(__filename);
+ const cli = meow(
+ `
+ Usage
+ $ node ./bin/render-activity-stream-html.js [options]
+
+ Options
+ -a PATH, --addon-path PATH Path to the parent of the target directory.
+ default: "${DEFAULT_OPTIONS.addonPath}"
+ -b URL, --base-url URL Base URL for assets.
+ default: "${DEFAULT_OPTIONS.baseUrl}"
+ --help Show this help message.
+`,
+ {
+ description: false,
+ // `pkg` is a tiny optimization. It prevents meow from looking for a package
+ // that doesn't technically exist. meow searches for a package and changes
+ // the process name to the package name. It resolves to the newtab
+ // package.json, which would give a confusing name and be wasteful.
+ pkg: {
+ name: "render-activity-stream-html",
+ version: "0.0.0",
+ },
+ // `importMeta` is required by meow 10+. It was added to support ESM, but
+ // meow now requires it, and no longer supports CJS style imports. But it
+ // only uses import.meta.url, which can be polyfilled like this:
+ importMeta: { url: fileUrl },
+ flags: {
+ addonPath: {
+ type: "string",
+ alias: "a",
+ default: DEFAULT_OPTIONS.addonPath,
+ },
+ baseUrl: {
+ type: "string",
+ alias: "b",
+ default: DEFAULT_OPTIONS.baseUrl,
+ },
+ },
+ }
+ );
+
+ const options = Object.assign({ debug: false }, cli.flags || {});
+ 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..93b88fac23
--- /dev/null
+++ b/browser/components/newtab/bin/try-runner.js
@@ -0,0 +1,366 @@
+/* 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, writeFileSync } = require("fs");
+const path = require("path");
+const { pathToFileURL } = require("url");
+const chalk = require("chalk");
+
+function logErrors(tool, errors) {
+ for (const error of errors) {
+ console.log(`TEST-UNEXPECTED-FAIL | ${tool} | ${error}`);
+ }
+ return errors;
+}
+
+function execOut(...args) {
+ let exitCode = 0;
+ let out;
+ let err;
+
+ try {
+ out = execFileSync(...args, {
+ silent: false,
+ });
+ } catch (e) {
+ // For debugging on (eg) try server...
+ //
+ // if (e) {
+ // logErrors("execOut", ["execFileSync returned exception: ", e]);
+ // }
+
+ out = e && e.stdout;
+ err = e && e.stderr;
+ exitCode = e && e.status;
+ }
+ return { exitCode, out: out && out.toString(), err: err && err.toString() };
+}
+
+function logStart(name) {
+ console.log(`TEST-START | ${name}`);
+}
+
+function logSkip(name) {
+ console.log(`TEST-SKIP | ${name}`);
+}
+
+const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
+
+const tests = {
+ bundles() {
+ logStart("bundles");
+
+ 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"),
+ },
+ // These should get split out to their own try-runner eventually (bug 1866170).
+ "about:welcome bundle": {
+ path: path.join(
+ "../",
+ "aboutwelcome",
+ "content",
+ "aboutwelcome.bundle.js"
+ ),
+ },
+ "aboutwelcome.css": {
+ path: path.join("../", "aboutwelcome", "content", "aboutwelcome.css"),
+ extraCheck: content => {
+ if (content.match(/^\s*@import/m)) {
+ return "aboutwelcome.css contains an @import statement. We should not import styles through the stylesheet, because it is loaded in multiple environments, including the browser chrome for feature callouts. To add other stylesheets to about:welcome or spotlight, add them to aboutwelcome.html or spotlight.html instead.";
+ }
+ return null;
+ },
+ },
+ // These should get split out to their own try-runner eventually (bug 1866170).
+ "about:asrouter bundle": {
+ path: path.join(
+ "../",
+ "asrouter",
+ "content",
+ "asrouter-admin.bundle.js"
+ ),
+ },
+ "ASRouterAdmin.css": {
+ path: path.join(
+ "../",
+ "asrouter",
+ "content",
+ "components",
+ "ASRouterAdmin",
+ "ASRouterAdmin.css"
+ ),
+ },
+ };
+ const errors = [];
+
+ for (const name of Object.keys(items)) {
+ const item = items[name];
+ item.before = readFileSync(item.path, item.encoding || "utf8");
+ }
+
+ let newtabBundleExitCode = execOut(npmCommand, ["run", "bundle"]).exitCode;
+
+ // Until we split out the try runner for about:welcome out into its own
+ // script, we manually run its bundle script.
+ let cwd = process.cwd();
+ process.chdir("../aboutwelcome");
+ let welcomeBundleExitCode = execOut(npmCommand, ["run", "bundle"]).exitCode;
+ process.chdir(cwd);
+
+ // Same thing for about:asrouter
+ process.chdir("../asrouter");
+ let asrouterBundleExitCode = execOut(npmCommand, [
+ "run",
+ "bundle",
+ ]).exitCode;
+ process.chdir(cwd);
+
+ 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 (item.extraCheck) {
+ const extraError = item.extraCheck(after);
+ if (extraError) {
+ errors.push(extraError);
+ }
+ }
+ }
+
+ if (newtabBundleExitCode !== 0) {
+ errors.push("newtab npm:bundle did not run successfully");
+ }
+
+ if (welcomeBundleExitCode !== 0) {
+ errors.push("about:welcome npm:bundle did not run successfully");
+ }
+
+ if (asrouterBundleExitCode !== 0) {
+ errors.push("about:asrouter npm:bundle did not run successfully");
+ }
+
+ logErrors("bundles", errors);
+ return errors.length === 0;
+ },
+
+ karma() {
+ logStart(`karma ${process.cwd()}`);
+
+ 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 ${process.cwd()}`, 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;
+ },
+
+ welcomekarma() {
+ let cwd = process.cwd();
+ process.chdir("../aboutwelcome");
+ const result = this.karma();
+ process.chdir(cwd);
+ return result;
+ },
+
+ asrouterkarma() {
+ let cwd = process.cwd();
+ process.chdir("../asrouter");
+ const result = this.karma();
+ process.chdir(cwd);
+ return result;
+ },
+
+ zipCodeCoverage() {
+ logStart("zipCodeCoverage");
+
+ const newtabCoveragePath = "logs/coverage/lcov.info";
+ const welcomeCoveragePath = "../aboutwelcome/logs/coverage/lcov.info";
+ const asrouterCoveragePath = "../asrouter/logs/coverage/lcov.info";
+
+ let newtabCoverage = readFileSync(newtabCoveragePath, "utf8");
+ const welcomeCoverage = readFileSync(welcomeCoveragePath, "utf8");
+ const asrouterCoverage = readFileSync(asrouterCoveragePath, "utf8");
+
+ newtabCoverage = `${newtabCoverage}${welcomeCoverage}${asrouterCoverage}`;
+ writeFileSync(newtabCoveragePath, newtabCoverage, "utf8");
+
+ 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;
+ },
+};
+
+async function main() {
+ const { default: meow } = await import("meow");
+ const fileUrl = pathToFileURL(__filename);
+ const cli = meow(
+ `
+ Usage
+ $ node bin/try-runner.js <tests> [options]
+
+ Options
+ -t NAME, --test NAME Run only the specified test. If not specified,
+ all tests will be run. Argument can be passed
+ multiple times to run multiple tests.
+ --help Show this help message.
+
+ Examples
+ $ node bin/try-runner.js bundles karma
+ $ node bin/try-runner.js -t karma -t zip
+`,
+ {
+ description: false,
+ // `pkg` is a tiny optimization. It prevents meow from looking for a package
+ // that doesn't technically exist. meow searches for a package and changes
+ // the process name to the package name. It resolves to the newtab
+ // package.json, which would give a confusing name and be wasteful.
+ pkg: {
+ name: "try-runner",
+ version: "1.0.0",
+ },
+ // `importMeta` is required by meow 10+. It was added to support ESM, but
+ // meow now requires it, and no longer supports CJS style imports. But it
+ // only uses import.meta.url, which can be polyfilled like this:
+ importMeta: { url: fileUrl },
+ flags: {
+ test: {
+ type: "string",
+ isMultiple: true,
+ alias: "t",
+ },
+ },
+ }
+ );
+ const aliases = {
+ bundle: "bundles",
+ build: "bundles",
+ coverage: "karma",
+ cov: "karma",
+ zip: "zipCodeCoverage",
+ welcomecoverage: "welcomekarma",
+ welcomecov: "welcomekarma",
+ asroutercoverage: "asrouterkarma",
+ asroutercov: "asrouterkarma",
+ };
+
+ const inputs = [...cli.input, ...cli.flags.test].map(input =>
+ (aliases[input] || input).toLowerCase()
+ );
+
+ function shouldRunTest(name) {
+ if (inputs.length) {
+ return inputs.includes(name.toLowerCase());
+ }
+ return true;
+ }
+
+ const results = [];
+ for (const name of Object.keys(tests)) {
+ if (shouldRunTest(name)) {
+ results.push([name, tests[name]()]);
+ } else {
+ logSkip(name);
+ }
+ }
+
+ for (const [name, result] of results) {
+ // colorize output based on result
+ console.log(result ? chalk.green(`✓ ${name}`) : chalk.red(`✗ ${name}`));
+ }
+
+ const success = results.every(([, result]) => result);
+ process.exitCode = success ? 0 : 1;
+ console.log("CODE", process.exitCode);
+}
+
+main();
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..df5c9f0c91
--- /dev/null
+++ b/browser/components/newtab/common/Actions.sys.mjs
@@ -0,0 +1,457 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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_OVERRIDE",
+ "DISCOVERY_STREAM_PERSONALIZATION_RESET",
+ "DISCOVERY_STREAM_PERSONALIZATION_TOGGLE",
+ "DISCOVERY_STREAM_PERSONALIZATION_UPDATED",
+ "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",
+ "SOV_UPDATED",
+ "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/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..d4f879b834
--- /dev/null
+++ b/browser/components/newtab/common/Reducers.sys.mjs
@@ -0,0 +1,855 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 },
+ 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: [],
+ // The "Share-of-Voice" allocations generated by TopSitesFeed
+ sov: {
+ ready: false,
+ positions: [
+ // {position: 0, assignedPartner: "amp"},
+ // {position: 1, assignedPartner: "moz-sales"},
+ ],
+ },
+ },
+ 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: [],
+ isPrivacyInfoModalVisible: false,
+ isCollectionDismissible: false,
+ feeds: {
+ data: {
+ // "https://foo.com/feed1": {lastUpdated: 123, data: [], personalized: false}
+ },
+ loaded: false,
+ },
+ spocs: {
+ spocs_endpoint: "",
+ lastUpdated: null,
+ data: {
+ // "spocs": {title: "", context: "", items: [], personalized: false},
+ // "placement1": {title: "", context: "", items: [], personalized: false},
+ },
+ 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.SOV_UPDATED:
+ const sov = {
+ ready: action.data.ready,
+ positions: action.data.positions,
+ };
+ return { ...prevState, sov };
+ 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
+ ),
+ })
+ );
+ 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,
+ };
+ case at.DISCOVERY_STREAM_PERSONALIZATION_RESET:
+ return { ...INITIAL_STATE.Personalization };
+ 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,
+ 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,
+ 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..7064595496
--- /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'],
+ 'esModule': 'resource:///modules/AboutNewTabService.sys.mjs',
+ '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..dce8a229a4
--- /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:///modules/asrouter/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/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/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/Base/Base.jsx b/browser/components/newtab/content-src/components/Base/Base.jsx
new file mode 100644
index 0000000000..0580267f26
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/Base.jsx
@@ -0,0 +1,262 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { DiscoveryStreamAdmin } from "content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin";
+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 ? (
+ <DiscoveryStreamAdmin 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 mayHaveSponsoredStories = prefs["system.showSponsored"];
+ 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(" ");
+
+ return (
+ <div>
+ <CustomizeMenu
+ onClose={this.closeCustomizationMenu}
+ onOpen={this.openCustomizationMenu}
+ openPreferences={this.openPreferences}
+ setPref={this.setPref}
+ enabledSections={enabledSections}
+ pocketRegion={pocketRegion}
+ mayHaveSponsoredTopSites={mayHaveSponsoredTopSites}
+ mayHaveSponsoredStories={mayHaveSponsoredStories}
+ 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>
+ {prefs.showSearch && (
+ <div className="non-collapsible-section">
+ <ErrorBoundary>
+ <Search
+ showLogo={
+ noSectionsEnabled || prefs["logowordmark.alwaysVisible"]
+ }
+ handoffEnabled={searchHandoffEnabled}
+ {...props.Search}
+ />
+ </ErrorBoundary>
+ </div>
+ )}
+ <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..1282173df5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/_Base.scss
@@ -0,0 +1,126 @@
+.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;
+ }
+}
+
+.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;
+ }
+ }
+}
+
+.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..74288ff07f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/_Card.scss
@@ -0,0 +1,333 @@
+@use 'sass:math';
+
+/* stylelint-disable max-nesting-depth */
+
+.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..10cc58a1b1
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss
@@ -0,0 +1,108 @@
+/* stylelint-disable max-nesting-depth */
+
+.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..e3192a944c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss
@@ -0,0 +1,59 @@
+@use 'sass:math';
+
+/* stylelint-disable max-nesting-depth */
+
+.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..57ed935e93
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx
@@ -0,0 +1,270 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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) {
+ // eventSource: TOP_SITES | TOP_STORIES | HIGHLIGHTS
+ const { preference, eventSource } = e.target.dataset;
+ 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);
+ }
+ } else if (e.target.nodeName === "MOZ-TOGGLE") {
+ value = e.target.pressed;
+ if (eventSource) {
+ this.inputUserEvent(eventSource, value);
+ }
+ }
+ this.props.setPref(preference, 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">
+ <moz-toggle
+ id="shortcuts-toggle"
+ pressed={topSitesEnabled || null}
+ onToggle={this.onPreferenceSelect}
+ data-preference="feeds.topsites"
+ data-eventSource="TOP_SITES"
+ data-l10n-id="newtab-custom-shortcuts-toggle"
+ data-l10n-attrs="label, description"
+ />
+ <div>
+ <div className="more-info-top-wrapper">
+ <div className="more-information" ref={this.topSitesDrawerRef}>
+ <select
+ id="row-selector"
+ className="selector"
+ name="row-count"
+ data-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}
+ data-preference="showSponsoredTopSites"
+ data-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">
+ <moz-toggle
+ id="pocket-toggle"
+ pressed={pocketEnabled || null}
+ onToggle={this.onPreferenceSelect}
+ aria-describedby="custom-pocket-subtitle"
+ data-preference="feeds.section.topstories"
+ data-eventSource="TOP_STORIES"
+ data-l10n-id="newtab-custom-stories-toggle"
+ data-l10n-attrs="label, description"
+ />
+ </label>
+ <div>
+ {(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}
+ data-preference="showSponsored"
+ data-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}
+ data-preference="showRecentSaves"
+ data-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">
+ <moz-toggle
+ id="highlights-toggle"
+ pressed={highlightsEnabled || null}
+ onToggle={this.onPreferenceSelect}
+ data-preference="feeds.section.highlights"
+ data-eventSource="HIGHLIGHTS"
+ data-l10n-id="newtab-custom-recent-toggle"
+ data-l10n-attrs="label, description"
+ />
+ </label>
+ </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..3d33f6fde7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx
@@ -0,0 +1,85 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { 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.mayHaveSponsoredStories}
+ 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..f534b8701b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss
@@ -0,0 +1,244 @@
+@media (height < 700px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px;
+ }
+}
+
+@media (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) {
+ // We need customize-animate-enter and customize-animate-exit to fix bug 1868232
+ // These first 2 classes happen only while the element is animating.
+ &.customize-animate-enter,
+ &.customize-animate-exit,
+ // We only add these so the css is visible for inspecting while not animating.
+ // Otherwise it's difficult to see and inspect this css because the transition is so fast.
+ &.customize-animate-enter-done,
+ &.customize-animate-exit-done {
+ 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 {
+ moz-toggle {
+ margin-bottom: 10px;
+ }
+
+ .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;
+ }
+ }
+
+ .more-info-top-wrapper,
+ .more-info-pocket-wrapper {
+ margin-inline-start: -2px;
+ overflow: hidden;
+
+ .more-information {
+ 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/DiscoveryStreamAdmin/DiscoveryStreamAdmin.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.jsx
new file mode 100644
index 0000000000..0112013391
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.jsx
@@ -0,0 +1,506 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { connect } from "react-redux";
+import React from "react";
+import { SimpleHashRouter } from "./SimpleHashRouter";
+
+const Row = props => (
+ <tr className="message-item" {...props}>
+ {props.children}
+ </tr>
+);
+
+function relativeTime(timestamp) {
+ if (!timestamp) {
+ return "";
+ }
+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
+ const minutes = Math.floor((Date.now() - timestamp) / 60000);
+ if (seconds < 2) {
+ return "just now";
+ } else if (seconds < 60) {
+ return `${seconds} seconds ago`;
+ } else if (minutes === 1) {
+ return "1 minute ago";
+ } else if (minutes < 600) {
+ return `${minutes} minutes ago`;
+ }
+ return new Date(timestamp).toLocaleString();
+}
+
+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 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 DiscoveryStreamAdminUI 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.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);
+ }
+
+ 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>
+ );
+ }
+
+ 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 collapsible".split(" ");
+ const { config, 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>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 DiscoveryStreamAdminInner extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.setState = this.setState.bind(this);
+ }
+
+ render() {
+ return (
+ <div
+ className={`discoverystream-admin ${
+ this.props.collapsed ? "collapsed" : "expanded"
+ }`}
+ >
+ <main className="main-panel">
+ <h1>Discovery Stream Admin</h1>
+
+ <p className="helpLink">
+ <span className="icon icon-small-spacer icon-info" />{" "}
+ <span>
+ Need to access the ASRouter Admin dev tools?{" "}
+ <a target="blank" href="about:asrouter">
+ Click here
+ </a>
+ </span>
+ </p>
+
+ <React.Fragment>
+ <DiscoveryStreamAdminUI
+ state={{
+ DiscoveryStream: this.props.DiscoveryStream,
+ Personalization: this.props.Personalization,
+ }}
+ otherPrefs={this.props.Prefs.values}
+ dispatch={this.props.dispatch}
+ />
+ </React.Fragment>
+ </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("#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");
+ }
+
+ 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={`discoverystream-admin-toggle ${
+ isCollapsed ? "collapsed" : "expanded"
+ }`}
+ onClick={this.renderAdmin ? this.onCollapseToggle : null}
+ >
+ <span className="icon icon-devtools" />
+ </a>
+ {renderAdmin ? (
+ <DiscoveryStreamAdminInner
+ {...props}
+ collapsed={this.state.collapsed}
+ />
+ ) : null}
+ </React.Fragment>
+ );
+ }
+}
+
+const _DiscoveryStreamAdmin = props => (
+ <SimpleHashRouter>
+ <CollapseToggle {...props} />
+ </SimpleHashRouter>
+);
+
+export const DiscoveryStreamAdmin = connect(state => ({
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Personalization: state.Personalization,
+ Prefs: state.Prefs,
+}))(_DiscoveryStreamAdmin);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.scss b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.scss
new file mode 100644
index 0000000000..a01227dd3d
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin.scss
@@ -0,0 +1,337 @@
+/* stylelint-disable max-nesting-depth */
+
+.discoverystream-admin-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;
+ }
+}
+
+.discoverystream-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;
+ }
+
+ .button {
+ &:disabled,
+ &:disabled:active {
+ opacity: 0.5;
+ cursor: unset;
+ box-shadow: none;
+ }
+ }
+
+ .impressions-section {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+
+ .impressions-item {
+ display: flex;
+ flex-flow: column nowrap;
+ padding: 8px;
+ border: 1px solid $border-color;
+ border-radius: 5px;
+
+ .impressions-inner-box {
+ display: flex;
+ flex-flow: row nowrap;
+ gap: 8px;
+ }
+
+ .impressions-category {
+ font-size: 1.15em;
+ white-space: nowrap;
+ flex-grow: 0.1;
+ }
+
+ .impressions-buttons {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+
+ button {
+ margin: 0;
+ }
+ }
+
+ .impressions-editor {
+ display: flex;
+ flex-grow: 1.5;
+
+ .general-textarea {
+ width: auto;
+ flex-grow: 1;
+ }
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/SimpleHashRouter.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/SimpleHashRouter.jsx
new file mode 100644
index 0000000000..9c3fd8579c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamAdmin/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/DiscoveryStreamBase/DiscoveryStreamBase.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx
new file mode 100644
index 0000000000..dff122b366
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx
@@ -0,0 +1,386 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+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}
+ ctaButtonSponsors={component.properties.ctaButtonSponsors}
+ ctaButtonVariant={component.properties.ctaButtonVariant}
+ 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..f13e0eb7ed
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx
@@ -0,0 +1,542 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ ctaButtonSponsors,
+ ctaButtonVariant,
+ 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}
+ publisher={rec.publisher}
+ pocket_id={rec.pocket_id}
+ context_type={rec.context_type}
+ bookmarkGuid={rec.bookmarkGuid}
+ is_collection={this.props.is_collection}
+ saveToPocketCard={saveToPocketCard}
+ ctaButtonSponsors={ctaButtonSponsors}
+ ctaButtonVariant={ctaButtonVariant}
+ recommendation_id={rec.recommendation_id}
+ />
+ )
+ );
+ }
+
+ 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..cab3a20578
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss
@@ -0,0 +1,352 @@
+$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: image-set(url('chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif'), url('chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif') 2x);
+ 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 (height <= 1065px) {
+ .excerpt {
+ display: none;
+ }
+ }
+
+ @media (max-width: $break-point-widest) {
+ @include small-cards;
+ }
+
+ @media (min-width: $break-point-widest) and (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..6aef56fb33
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx
@@ -0,0 +1,529 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ ctaButtonVariant,
+}) => (
+ <div className="meta">
+ <div className="info-wrap">
+ {ctaButtonVariant !== "variant-b" && (
+ <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}
+ cta_button_variant={ctaButtonVariant}
+ source={source}
+ />
+ )}
+ {/* 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",
+ recommendation_id: this.props.recommendation_id,
+ tile_id: this.props.id,
+ ...(this.props.shim && this.props.shim.click
+ ? { shim: this.props.shim.click }
+ : {}),
+ },
+ })
+ );
+
+ 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",
+ recommendation_id: this.props.recommendation_id,
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ 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",
+ recommendation_id: this.props.recommendation_id,
+ tile_id: this.props.id,
+ ...(this.props.shim && this.props.shim.save
+ ? { shim: this.props.shim.save }
+ : {}),
+ },
+ })
+ );
+
+ 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 }
+ : {}),
+ recommendation_id: this.props.recommendation_id,
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ 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.source || this.props.publisher;
+ 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 ctaButtonEnabled = this.props.ctaButtonSponsors?.includes(
+ this.props.sponsor?.toLowerCase()
+ );
+ let ctaButtonVariant = "";
+ if (ctaButtonEnabled) {
+ ctaButtonVariant = this.props.ctaButtonVariant;
+ }
+ let ctaButtonVariantClassName = ctaButtonVariant;
+
+ const ctaButtonClassName = ctaButtonEnabled ? `ds-card-cta-button` : ``;
+ 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} ${ctaButtonClassName} ${ctaButtonVariantClassName}`}
+ 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>
+ {ctaButtonVariant === "variant-b" && (
+ <div className="cta-header">Shop Now</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}
+ ctaButtonVariant={ctaButtonVariant}
+ />
+ <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 }
+ : {}),
+ recommendation_id: this.props.recommendation_id,
+ },
+ ]}
+ 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..92afedff26
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss
@@ -0,0 +1,303 @@
+// 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;
+ }
+ }
+
+ &.ds-card-cta-button.variant-a,
+ &.ds-card-cta-button.variant-b {
+ .img {
+ padding-top: 52.4%;
+ }
+
+ .story-sponsored-label {
+ margin: var(--space-small) 0 0;
+ }
+
+ .source {
+ text-decoration: underline;
+ }
+
+ .story-footer {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: center;
+ column-gap: var(--space-small);
+ margin-top: 0;
+ }
+
+ .story-cta-button {
+ cursor: inherit;
+ background: var(--button-background-color);
+ border-radius: var(--border-radius-small);
+ border: none;
+ padding: var(--space-xsmall) 16px;
+ font-size: var(--font-size-small);
+ font-weight: var(--font-weight-bold);
+ min-height: var(--size-item-large);
+ min-width: 97px;
+ color: var(--newtab-text-primary-color);
+ margin-top: var(--space-small);
+
+ &:hover {
+ background: var(--button-background-color-hover);
+ }
+ }
+
+ .cta-header {
+ background: var(--button-background-color);
+ font-size: var(--font-size-root);
+ font-weight: var(--font-weight-bold);
+ text-align: end;
+ padding: var(--space-xsmall) 16px;
+ color: var(--newtab-text-primary-color);
+ min-height: var(--size-item-large);
+ }
+ }
+
+ 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..5c7e79685e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx
@@ -0,0 +1,145 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ cta_button_variant,
+ source,
+ } = this.props;
+
+ const sponsorLabel = SponsorLabel({
+ sponsored_by_override,
+ sponsor,
+ context,
+ });
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type,
+ });
+
+ if (cta_button_variant === "variant-a") {
+ return (
+ <div className="story-footer">
+ {/* this button is decorative only */}
+ <button aria-hidden="true" className="story-cta-button">
+ Shop Now
+ </button>
+ {sponsorLabel}
+ </div>
+ );
+ }
+
+ if (cta_button_variant === "variant-b") {
+ return (
+ <div className="story-footer">
+ {sponsorLabel}
+ <span className="source clamp cta-footer-source">{source}</span>
+ </div>
+ );
+ }
+
+ 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..dc01e0cc51
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.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 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"
+ 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..4b4db5df33
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss
@@ -0,0 +1,48 @@
+.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..f342c9829b
--- /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/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..54b39524d8
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss
@@ -0,0 +1,47 @@
+/* stylelint-disable max-nesting-depth */
+
+.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..0c7a158efb
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss
@@ -0,0 +1,182 @@
+/* stylelint-disable max-nesting-depth */
+
+.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..4e9d6c3383
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss
@@ -0,0 +1,79 @@
+/* stylelint-disable max-nesting-depth */
+
+.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..4f8b5740e2
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopicsWidget/_TopicsWidget.scss
@@ -0,0 +1,90 @@
+/* stylelint-disable max-nesting-depth */
+
+.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..1eb4863271
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx
@@ -0,0 +1,251 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 } : {}),
+ recommendation_id: link.recommendation_id,
+ })),
+ })
+ );
+ 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/ModalOverlay/ModalOverlay.jsx b/browser/components/newtab/content-src/components/ModalOverlay/ModalOverlay.jsx
new file mode 100644
index 0000000000..fdfdf22db2
--- /dev/null
+++ b/browser/components/newtab/content-src/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/components/ModalOverlay/_ModalOverlay.scss b/browser/components/newtab/content-src/components/ModalOverlay/_ModalOverlay.scss
new file mode 100644
index 0000000000..3bc2dffca0
--- /dev/null
+++ b/browser/components/newtab/content-src/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(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(width <= 960px) {
+ margin-top: 100px;
+ }
+
+ @media(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(width <= 850px) and (height <= 730px) {
+ position: sticky;
+ }
+
+ // if modal is narrow enough, footer becomes sticky
+ @media(width <= 650px) and (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/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..64308963c9
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/Search.jsx
@@ -0,0 +1,189 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* globals ContentSearchUIController, ContentSearchHandoffUIController */
+
+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.sys.mjs 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();
+ }
+ }
+
+ 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"
+ ref={this.onSearchHandoffButtonMount}
+ onClick={this.onSearchHandoffClick}
+ tabIndex="-1"
+ >
+ <div className="fake-textbox" />
+ <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..a9af0ab1e0
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/_Search.scss
@@ -0,0 +1,394 @@
+$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: image-set(url('chrome://branding/content/about-logo.png'), url('chrome://branding/content/about-logo@2x.png') 2x) no-repeat center;
+ background-size: $logo-size;
+ }
+
+ .wordmark {
+ background: url('chrome://branding/content/firefox-wordmark.svg') no-repeat center center;
+ background-size: $wordmark-size;
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-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);
+ }
+ }
+ }
+}
+
+@media (height <= 700px) {
+ .search-wrapper {
+ padding: 0 0 30px;
+ }
+}
+
+.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 (height > 700px) {
+ 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..b7f0038558
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSite.jsx
@@ -0,0 +1,889 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.
+ // This first event is for the shim property
+ // and is used by our ad service provider.
+ this.props.dispatch(
+ ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: TOP_SITES_SOURCE,
+ action_position: this.props.link.pos,
+ value: {
+ card_type: "spoc",
+ tile_id: this.props.link.id,
+ shim: this.props.link.shim && this.props.link.shim.click,
+ },
+ })
+ );
+
+ // A second event is recoded for internal usage.
+ 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..c69156c514
--- /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 "content-src/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..ff2e2df826
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/_TopSites.scss
@@ -0,0 +1,631 @@
+@use 'sass:math';
+
+/* stylelint-disable max-nesting-depth */
+
+$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;
+ border-radius: 8px;
+ display: inline-block;
+ margin-block-end: 16px;
+
+ // container for context menu
+ .top-site-inner {
+ position: relative;
+
+ > a {
+ padding: 20px $half-base-gutter 4px;
+ 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: 3px;
+ 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/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..20fcedc6c0
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/init-store.js
@@ -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/. */
+
+/* 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";
+
+/**
+ * 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);
+ };
+};
+
+/**
+ * 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(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..caac738170
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/link-menu-options.js
@@ -0,0 +1,309 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ data: {
+ advertiser_name: (site.label || site.hostname).toLocaleLowerCase(),
+ position: site.sponsored_position,
+ tile_id: site.sponsored_tile_id,
+ },
+ }),
+ 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 } : {}),
+ // If not sponsored, hostname could be anything (Cat3 Data!).
+ // So only put in advertiser_name for sponsored topsites.
+ ...(site.sponsored_position
+ ? {
+ advertiser_name: (
+ site.label || site.hostname
+ )?.toLocaleLowerCase(),
+ }
+ : {}),
+ position: pos,
+ ...(site.sponsored_tile_id ? { tile_id: site.sponsored_tile_id } : {}),
+ is_pocket_card: site.type === "CardGrid",
+ })),
+ }),
+ 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..8bd3a7a397
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_activity-stream.scss
@@ -0,0 +1,172 @@
+@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/DiscoveryStreamAdmin/DiscoveryStreamAdmin';
+@import '../components/PocketLoggedInCta/PocketLoggedInCta';
+@import '../components/MoreRecommendations/MoreRecommendations';
+@import '../components/DiscoveryStreamBase/DiscoveryStreamBase';
+@import '../components/ModalOverlay/ModalOverlay';
+
+// 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/content-src/components/Button/Button';
+// stylelint-enable no-invalid-position-at-import-rule
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..6b097ae93e
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_theme.scss
@@ -0,0 +1,97 @@
+@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);
+
+ @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..9fd0083841
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_variables.scss
@@ -0,0 +1,215 @@
+@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/';
+
+$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..336c7573ab
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-linux.css
@@ -0,0 +1,4248 @@
+@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-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;
+ }
+}
+
+.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;
+ }
+}
+
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ border-radius: 8px;
+ display: inline-block;
+ margin-block-end: 16px;
+}
+.top-site-outer .top-site-inner {
+ position: relative;
+}
+.top-site-outer .top-site-inner > a {
+ padding: 20px 16px 4px;
+ 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: 3px;
+ 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: image-set(url("chrome://branding/content/about-logo.png"), url("chrome://branding/content/about-logo@2x.png") 2x) no-repeat center;
+ background-size: 82px;
+}
+.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);
+}
+
+@media (height <= 700px) {
+ .search-wrapper {
+ padding: 0 0 30px;
+ }
+}
+.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 (height > 700px) {
+ 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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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 (height < 700px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px;
+ }
+}
+@media (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.customize-animate-enter, .customize-menu.customize-animate-exit, .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-exit-done {
+ 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 moz-toggle {
+ margin-bottom: 10px;
+}
+.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 .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 {
+ 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);
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.discoverystream-admin-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px;
+}
+.discoverystream-admin-toggle .icon-devtools {
+ background-image: url("chrome://global/skin/icons/developer.svg");
+ padding: 15px;
+}
+.discoverystream-admin-toggle:dir(rtl) {
+ transform: scaleX(-1);
+}
+.discoverystream-admin-toggle:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2);
+}
+
+.discoverystream-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);
+}
+.discoverystream-admin.collapsed {
+ display: none;
+}
+.discoverystream-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px;
+}
+.discoverystream-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.discoverystream-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color);
+}
+.discoverystream-admin .sidebar li a:hover {
+ background: var(--newtab-background-color-secondary);
+}
+.discoverystream-admin h1 {
+ font-weight: 200;
+ font-size: 32px;
+}
+.discoverystream-admin h2 .button,
+.discoverystream-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0;
+}
+.discoverystream-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px;
+}
+.discoverystream-admin .json-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ box-shadow: none;
+}
+.discoverystream-admin table {
+ border-collapse: collapse;
+ width: 100%;
+}
+.discoverystream-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin table.minimal-table td {
+ padding: 8px;
+}
+.discoverystream-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+}
+.discoverystream-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin table.errorReporting td {
+ padding: 4px;
+}
+.discoverystream-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.discoverystream-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.discoverystream-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin .message-item td.message-summary {
+ width: 60%;
+}
+.discoverystream-admin .message-item td.button-column {
+ width: 15%;
+}
+.discoverystream-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item.blocked .message-id,
+.discoverystream-admin .message-item.blocked .message-summary {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item.blocked .message-id {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px;
+}
+.discoverystream-admin .providerUrl {
+ font-size: 12px;
+}
+.discoverystream-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;
+}
+.discoverystream-admin .errorState {
+ border: 1px solid var(--newtab-status-error);
+}
+.discoverystream-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.discoverystream-admin .helpLink a {
+ text-decoration: underline;
+}
+.discoverystream-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.discoverystream-admin .ds-component {
+ margin-bottom: 20px;
+}
+.discoverystream-admin .modalOverlayInner {
+ height: 80%;
+}
+.discoverystream-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin .collapsed {
+ display: none;
+}
+.discoverystream-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px;
+}
+.discoverystream-admin .button:disabled, .discoverystream-admin .button:disabled:active {
+ opacity: 0.5;
+ cursor: unset;
+ box-shadow: none;
+}
+.discoverystream-admin .impressions-section {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+.discoverystream-admin .impressions-section .impressions-item {
+ display: flex;
+ flex-flow: column nowrap;
+ padding: 8px;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-inner-box {
+ display: flex;
+ flex-flow: row nowrap;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-category {
+ font-size: 1.15em;
+ white-space: nowrap;
+ flex-grow: 0.1;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons button {
+ margin: 0;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor {
+ display: flex;
+ flex-grow: 1.5;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor .general-textarea {
+ width: auto;
+ flex-grow: 1;
+}
+
+.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;
+}
+
+.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 (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 (width <= 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px;
+ }
+}
+@media (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 (width <= 850px) and (height <= 730px) {
+ .modalOverlayInner .footer {
+ position: sticky;
+ }
+}
+@media (width <= 650px) and (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;
+}
+
+.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: image-set(url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif"), url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif") 2x);
+ 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: 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 (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 (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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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.ds-card-cta-button.variant-a .img, .ds-card.ds-card-cta-button.variant-b .img {
+ padding-top: 52.4%;
+}
+.ds-card.ds-card-cta-button.variant-a .story-sponsored-label, .ds-card.ds-card-cta-button.variant-b .story-sponsored-label {
+ margin: var(--space-small) 0 0;
+}
+.ds-card.ds-card-cta-button.variant-a .source, .ds-card.ds-card-cta-button.variant-b .source {
+ text-decoration: underline;
+}
+.ds-card.ds-card-cta-button.variant-a .story-footer, .ds-card.ds-card-cta-button.variant-b .story-footer {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: center;
+ column-gap: var(--space-small);
+ margin-top: 0;
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button, .ds-card.ds-card-cta-button.variant-b .story-cta-button {
+ cursor: inherit;
+ background: var(--button-background-color);
+ border-radius: var(--border-radius-small);
+ border: none;
+ padding: var(--space-xsmall) 16px;
+ font-size: var(--font-size-small);
+ font-weight: var(--font-weight-bold);
+ min-height: var(--size-item-large);
+ min-width: 97px;
+ color: var(--newtab-text-primary-color);
+ margin-top: var(--space-small);
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button:hover, .ds-card.ds-card-cta-button.variant-b .story-cta-button:hover {
+ background: var(--button-background-color-hover);
+}
+.ds-card.ds-card-cta-button.variant-a .cta-header, .ds-card.ds-card-cta-button.variant-b .cta-header {
+ background: var(--button-background-color);
+ font-size: var(--font-size-root);
+ font-weight: var(--font-weight-bold);
+ text-align: end;
+ padding: var(--space-xsmall) 16px;
+ color: var(--newtab-text-primary-color);
+ min-height: var(--size-item-large);
+}
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
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..01eff46415
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-mac.css
@@ -0,0 +1,4252 @@
+@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-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;
+ }
+}
+
+.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;
+ }
+}
+
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ border-radius: 8px;
+ display: inline-block;
+ margin-block-end: 16px;
+}
+.top-site-outer .top-site-inner {
+ position: relative;
+}
+.top-site-outer .top-site-inner > a {
+ padding: 20px 16px 4px;
+ 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: 3px;
+ 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: image-set(url("chrome://branding/content/about-logo.png"), url("chrome://branding/content/about-logo@2x.png") 2x) no-repeat center;
+ background-size: 82px;
+}
+.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);
+}
+
+@media (height <= 700px) {
+ .search-wrapper {
+ padding: 0 0 30px;
+ }
+}
+.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 (height > 700px) {
+ 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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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 (height < 700px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px;
+ }
+}
+@media (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.customize-animate-enter, .customize-menu.customize-animate-exit, .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-exit-done {
+ 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 moz-toggle {
+ margin-bottom: 10px;
+}
+.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 .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 {
+ 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);
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.discoverystream-admin-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px;
+}
+.discoverystream-admin-toggle .icon-devtools {
+ background-image: url("chrome://global/skin/icons/developer.svg");
+ padding: 15px;
+}
+.discoverystream-admin-toggle:dir(rtl) {
+ transform: scaleX(-1);
+}
+.discoverystream-admin-toggle:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2);
+}
+
+.discoverystream-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);
+}
+.discoverystream-admin.collapsed {
+ display: none;
+}
+.discoverystream-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px;
+}
+.discoverystream-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.discoverystream-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color);
+}
+.discoverystream-admin .sidebar li a:hover {
+ background: var(--newtab-background-color-secondary);
+}
+.discoverystream-admin h1 {
+ font-weight: 200;
+ font-size: 32px;
+}
+.discoverystream-admin h2 .button,
+.discoverystream-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0;
+}
+.discoverystream-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px;
+}
+.discoverystream-admin .json-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ box-shadow: none;
+}
+.discoverystream-admin table {
+ border-collapse: collapse;
+ width: 100%;
+}
+.discoverystream-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin table.minimal-table td {
+ padding: 8px;
+}
+.discoverystream-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+}
+.discoverystream-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin table.errorReporting td {
+ padding: 4px;
+}
+.discoverystream-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.discoverystream-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.discoverystream-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin .message-item td.message-summary {
+ width: 60%;
+}
+.discoverystream-admin .message-item td.button-column {
+ width: 15%;
+}
+.discoverystream-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item.blocked .message-id,
+.discoverystream-admin .message-item.blocked .message-summary {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item.blocked .message-id {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px;
+}
+.discoverystream-admin .providerUrl {
+ font-size: 12px;
+}
+.discoverystream-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;
+}
+.discoverystream-admin .errorState {
+ border: 1px solid var(--newtab-status-error);
+}
+.discoverystream-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.discoverystream-admin .helpLink a {
+ text-decoration: underline;
+}
+.discoverystream-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.discoverystream-admin .ds-component {
+ margin-bottom: 20px;
+}
+.discoverystream-admin .modalOverlayInner {
+ height: 80%;
+}
+.discoverystream-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin .collapsed {
+ display: none;
+}
+.discoverystream-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px;
+}
+.discoverystream-admin .button:disabled, .discoverystream-admin .button:disabled:active {
+ opacity: 0.5;
+ cursor: unset;
+ box-shadow: none;
+}
+.discoverystream-admin .impressions-section {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+.discoverystream-admin .impressions-section .impressions-item {
+ display: flex;
+ flex-flow: column nowrap;
+ padding: 8px;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-inner-box {
+ display: flex;
+ flex-flow: row nowrap;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-category {
+ font-size: 1.15em;
+ white-space: nowrap;
+ flex-grow: 0.1;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons button {
+ margin: 0;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor {
+ display: flex;
+ flex-grow: 1.5;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor .general-textarea {
+ width: auto;
+ flex-grow: 1;
+}
+
+.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;
+}
+
+.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 (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 (width <= 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px;
+ }
+}
+@media (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 (width <= 850px) and (height <= 730px) {
+ .modalOverlayInner .footer {
+ position: sticky;
+ }
+}
+@media (width <= 650px) and (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;
+}
+
+.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: image-set(url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif"), url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif") 2x);
+ 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: 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 (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 (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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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.ds-card-cta-button.variant-a .img, .ds-card.ds-card-cta-button.variant-b .img {
+ padding-top: 52.4%;
+}
+.ds-card.ds-card-cta-button.variant-a .story-sponsored-label, .ds-card.ds-card-cta-button.variant-b .story-sponsored-label {
+ margin: var(--space-small) 0 0;
+}
+.ds-card.ds-card-cta-button.variant-a .source, .ds-card.ds-card-cta-button.variant-b .source {
+ text-decoration: underline;
+}
+.ds-card.ds-card-cta-button.variant-a .story-footer, .ds-card.ds-card-cta-button.variant-b .story-footer {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: center;
+ column-gap: var(--space-small);
+ margin-top: 0;
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button, .ds-card.ds-card-cta-button.variant-b .story-cta-button {
+ cursor: inherit;
+ background: var(--button-background-color);
+ border-radius: var(--border-radius-small);
+ border: none;
+ padding: var(--space-xsmall) 16px;
+ font-size: var(--font-size-small);
+ font-weight: var(--font-weight-bold);
+ min-height: var(--size-item-large);
+ min-width: 97px;
+ color: var(--newtab-text-primary-color);
+ margin-top: var(--space-small);
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button:hover, .ds-card.ds-card-cta-button.variant-b .story-cta-button:hover {
+ background: var(--button-background-color-hover);
+}
+.ds-card.ds-card-cta-button.variant-a .cta-header, .ds-card.ds-card-cta-button.variant-b .cta-header {
+ background: var(--button-background-color);
+ font-size: var(--font-size-root);
+ font-weight: var(--font-weight-bold);
+ text-align: end;
+ padding: var(--space-xsmall) 16px;
+ color: var(--newtab-text-primary-color);
+ min-height: var(--size-item-large);
+}
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
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..69a2459268
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-windows.css
@@ -0,0 +1,4248 @@
+@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-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;
+ }
+}
+
+.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;
+ }
+}
+
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ border-radius: 8px;
+ display: inline-block;
+ margin-block-end: 16px;
+}
+.top-site-outer .top-site-inner {
+ position: relative;
+}
+.top-site-outer .top-site-inner > a {
+ padding: 20px 16px 4px;
+ 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: 3px;
+ 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: image-set(url("chrome://branding/content/about-logo.png"), url("chrome://branding/content/about-logo@2x.png") 2x) no-repeat center;
+ background-size: 82px;
+}
+.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);
+}
+
+@media (height <= 700px) {
+ .search-wrapper {
+ padding: 0 0 30px;
+ }
+}
+.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 (height > 700px) {
+ 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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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 (height < 700px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px;
+ }
+}
+@media (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.customize-animate-enter, .customize-menu.customize-animate-exit, .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-exit-done {
+ 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 moz-toggle {
+ margin-bottom: 10px;
+}
+.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 .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 {
+ 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);
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+ }
+}
+
+/* stylelint-disable max-nesting-depth */
+.discoverystream-admin-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px;
+}
+.discoverystream-admin-toggle .icon-devtools {
+ background-image: url("chrome://global/skin/icons/developer.svg");
+ padding: 15px;
+}
+.discoverystream-admin-toggle:dir(rtl) {
+ transform: scaleX(-1);
+}
+.discoverystream-admin-toggle:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2);
+}
+
+.discoverystream-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);
+}
+.discoverystream-admin.collapsed {
+ display: none;
+}
+.discoverystream-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px;
+}
+.discoverystream-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.discoverystream-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color);
+}
+.discoverystream-admin .sidebar li a:hover {
+ background: var(--newtab-background-color-secondary);
+}
+.discoverystream-admin h1 {
+ font-weight: 200;
+ font-size: 32px;
+}
+.discoverystream-admin h2 .button,
+.discoverystream-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0;
+}
+.discoverystream-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px;
+}
+.discoverystream-admin .json-button:hover {
+ background-color: var(--newtab-element-hover-color);
+ box-shadow: none;
+}
+.discoverystream-admin table {
+ border-collapse: collapse;
+ width: 100%;
+}
+.discoverystream-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin table.minimal-table td {
+ padding: 8px;
+}
+.discoverystream-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+}
+.discoverystream-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin table.errorReporting td {
+ padding: 4px;
+}
+.discoverystream-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-background-color-secondary);
+}
+.discoverystream-admin .sourceLabel {
+ background: var(--newtab-background-color-secondary);
+ padding: 2px 5px;
+ border-radius: 3px;
+}
+.discoverystream-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: var(--newtab-status-error);
+}
+.discoverystream-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap;
+}
+.discoverystream-admin .message-item td.message-summary {
+ width: 60%;
+}
+.discoverystream-admin .message-item td.button-column {
+ width: 15%;
+}
+.discoverystream-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-color);
+}
+.discoverystream-admin .message-item.blocked .message-id,
+.discoverystream-admin .message-item.blocked .message-summary {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item.blocked .message-id {
+ opacity: 0.5;
+}
+.discoverystream-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px;
+}
+.discoverystream-admin .providerUrl {
+ font-size: 12px;
+}
+.discoverystream-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;
+}
+.discoverystream-admin .errorState {
+ border: 1px solid var(--newtab-status-error);
+}
+.discoverystream-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ align-items: center;
+}
+.discoverystream-admin .helpLink a {
+ text-decoration: underline;
+}
+.discoverystream-admin .helpLink .icon {
+ min-width: 18px;
+ min-height: 18px;
+}
+.discoverystream-admin .ds-component {
+ margin-bottom: 20px;
+}
+.discoverystream-admin .modalOverlayInner {
+ height: 80%;
+}
+.discoverystream-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex;
+}
+.discoverystream-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color);
+}
+.discoverystream-admin .collapsed {
+ display: none;
+}
+.discoverystream-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px;
+}
+.discoverystream-admin .button:disabled, .discoverystream-admin .button:disabled:active {
+ opacity: 0.5;
+ cursor: unset;
+ box-shadow: none;
+}
+.discoverystream-admin .impressions-section {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+.discoverystream-admin .impressions-section .impressions-item {
+ display: flex;
+ flex-flow: column nowrap;
+ padding: 8px;
+ border: 1px solid var(--newtab-border-color);
+ border-radius: 5px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-inner-box {
+ display: flex;
+ flex-flow: row nowrap;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-category {
+ font-size: 1.15em;
+ white-space: nowrap;
+ flex-grow: 0.1;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-buttons button {
+ margin: 0;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor {
+ display: flex;
+ flex-grow: 1.5;
+}
+.discoverystream-admin .impressions-section .impressions-item .impressions-editor .general-textarea {
+ width: auto;
+ flex-grow: 1;
+}
+
+.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;
+}
+
+.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 (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 (width <= 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px;
+ }
+}
+@media (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 (width <= 850px) and (height <= 730px) {
+ .modalOverlayInner .footer {
+ position: sticky;
+ }
+}
+@media (width <= 650px) and (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;
+}
+
+.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: image-set(url("chrome://activity-stream/content/data/content/assets/pocket-onboarding.avif"), url("chrome://activity-stream/content/data/content/assets/pocket-onboarding@2x.avif") 2x);
+ 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: 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 (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 (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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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.ds-card-cta-button.variant-a .img, .ds-card.ds-card-cta-button.variant-b .img {
+ padding-top: 52.4%;
+}
+.ds-card.ds-card-cta-button.variant-a .story-sponsored-label, .ds-card.ds-card-cta-button.variant-b .story-sponsored-label {
+ margin: var(--space-small) 0 0;
+}
+.ds-card.ds-card-cta-button.variant-a .source, .ds-card.ds-card-cta-button.variant-b .source {
+ text-decoration: underline;
+}
+.ds-card.ds-card-cta-button.variant-a .story-footer, .ds-card.ds-card-cta-button.variant-b .story-footer {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: center;
+ column-gap: var(--space-small);
+ margin-top: 0;
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button, .ds-card.ds-card-cta-button.variant-b .story-cta-button {
+ cursor: inherit;
+ background: var(--button-background-color);
+ border-radius: var(--border-radius-small);
+ border: none;
+ padding: var(--space-xsmall) 16px;
+ font-size: var(--font-size-small);
+ font-weight: var(--font-weight-bold);
+ min-height: var(--size-item-large);
+ min-width: 97px;
+ color: var(--newtab-text-primary-color);
+ margin-top: var(--space-small);
+}
+.ds-card.ds-card-cta-button.variant-a .story-cta-button:hover, .ds-card.ds-card-cta-button.variant-b .story-cta-button:hover {
+ background: var(--button-background-color-hover);
+}
+.ds-card.ds-card-cta-button.variant-a .cta-header, .ds-card.ds-card-cta-button.variant-b .cta-header {
+ background: var(--button-background-color);
+ font-size: var(--font-size-root);
+ font-weight: var(--font-weight-bold);
+ text-align: end;
+ padding: var(--space-xsmall) 16px;
+ color: var(--newtab-text-primary-color);
+ min-height: var(--size-item-large);
+}
+.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;
+}
+
+/* stylelint-disable max-nesting-depth */
+.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;
+}
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..60898ed6b8
--- /dev/null
+++ b/browser/components/newtab/data/content/abouthomecache/page.html.template
@@ -0,0 +1,46 @@
+#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://global/skin/design-system/tokens-brand.css">
+ <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>
+ <script async type="module" src="chrome://global/content/elements/moz-toggle.mjs"></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..14691a95f4
--- /dev/null
+++ b/browser/components/newtab/data/content/activity-stream.bundle.js
@@ -0,0 +1,9558 @@
+/*! 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_OVERRIDE",
+ "DISCOVERY_STREAM_PERSONALIZATION_RESET",
+ "DISCOVERY_STREAM_PERSONALIZATION_TOGGLE",
+ "DISCOVERY_STREAM_PERSONALIZATION_UPDATED",
+ "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",
+ "SOV_UPDATED",
+ "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: 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/DiscoveryStreamAdmin/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/DiscoveryStreamAdmin/DiscoveryStreamAdmin.jsx
+function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+const Row = props => /*#__PURE__*/external_React_default().createElement("tr", _extends({
+ className: "message-item"
+}, props), props.children);
+function relativeTime(timestamp) {
+ if (!timestamp) {
+ return "";
+ }
+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
+ const minutes = Math.floor((Date.now() - timestamp) / 60000);
+ if (seconds < 2) {
+ return "just now";
+ } else if (seconds < 60) {
+ return `${seconds} seconds ago`;
+ } else if (minutes === 1) {
+ return "1 minute ago";
+ } else if (minutes < 600) {
+ return `${minutes} minutes ago`;
+ }
+ return new Date(timestamp).toLocaleString();
+}
+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 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 DiscoveryStreamAdminUI 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.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);
+ }
+ 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)));
+ }
+ renderFeedData(url) {
+ 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?.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 collapsible".split(" ");
+ const {
+ config,
+ 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, "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 DiscoveryStreamAdminInner extends (external_React_default()).PureComponent {
+ constructor(props) {
+ super(props);
+ this.setState = this.setState.bind(this);
+ }
+ render() {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: `discoverystream-admin ${this.props.collapsed ? "collapsed" : "expanded"}`
+ }, /*#__PURE__*/external_React_default().createElement("main", {
+ className: "main-panel"
+ }, /*#__PURE__*/external_React_default().createElement("h1", null, "Discovery Stream 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 to access the ASRouter Admin dev tools?", " ", /*#__PURE__*/external_React_default().createElement("a", {
+ target: "blank",
+ href: "about:asrouter"
+ }, "Click here"))), /*#__PURE__*/external_React_default().createElement((external_React_default()).Fragment, null, /*#__PURE__*/external_React_default().createElement(DiscoveryStreamAdminUI, {
+ state: {
+ DiscoveryStream: this.props.DiscoveryStream,
+ Personalization: this.props.Personalization
+ },
+ otherPrefs: this.props.Prefs.values,
+ dispatch: this.props.dispatch
+ }))));
+ }
+}
+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("#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");
+ }
+ 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: `discoverystream-admin-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(DiscoveryStreamAdminInner, _extends({}, props, {
+ collapsed: this.state.collapsed
+ })) : null);
+ }
+}
+const _DiscoveryStreamAdmin = props => /*#__PURE__*/external_React_default().createElement(SimpleHashRouter, null, /*#__PURE__*/external_React_default().createElement(CollapseToggle, props));
+const DiscoveryStreamAdmin = (0,external_ReactRedux_namespaceObject.connect)(state => ({
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Personalization: state.Personalization,
+ Prefs: state.Prefs
+}))(_DiscoveryStreamAdmin);
+;// 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,
+ data: {
+ advertiser_name: (site.label || site.hostname).toLocaleLowerCase(),
+ position: site.sponsored_position,
+ tile_id: site.sponsored_tile_id
+ }
+ }),
+ 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
+ } : {}),
+ // If not sponsored, hostname could be anything (Cat3 Data!).
+ // So only put in advertiser_name for sponsored topsites.
+ ...(site.sponsored_position ? {
+ advertiser_name: (site.label || site.hostname)?.toLocaleLowerCase()
+ } : {}),
+ position: pos,
+ ...(site.sponsored_tile_id ? {
+ tile_id: site.sponsored_tile_id
+ } : {}),
+ is_pocket_card: site.type === "CardGrid"
+ }))
+ }),
+ 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 VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+
+// Per analytical requirement, we set the minimal intersection ratio to
+// 0.5, and an impression is identified when the wrapped item has at least
+// 50% visibility.
+//
+// This constant is exported for unit test
+const INTERSECTION_RATIO = 0.5;
+
+/**
+ * Impression wrapper for Discovery Stream related React components.
+ *
+ * It makses use of the Intersection Observer API to detect the visibility,
+ * and relies on page visibility to ensure the impression is reported
+ * only when the component is visible on the page.
+ *
+ * Note:
+ * * This wrapper used to be used either at the individual card level,
+ * or by the card container components.
+ * It is now only used for individual card level.
+ * * Each impression will be sent only once as soon as the desired
+ * visibility is detected
+ * * Batching is not yet implemented, hence it might send multiple
+ * impression pings separately
+ */
+class ImpressionStats_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
+ } : {}),
+ recommendation_id: link.recommendation_id
+ }))
+ }));
+ 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 === 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 /*#__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,
+ cta_button_variant,
+ source
+ } = this.props;
+ const sponsorLabel = SponsorLabel({
+ sponsored_by_override,
+ sponsor,
+ context
+ });
+ const dsMessageLabel = DSMessageLabel({
+ context,
+ context_type
+ });
+ if (cta_button_variant === "variant-a") {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "story-footer"
+ }, /*#__PURE__*/external_React_default().createElement("button", {
+ "aria-hidden": "true",
+ className: "story-cta-button"
+ }, "Shop Now"), sponsorLabel);
+ }
+ if (cta_button_variant === "variant-b") {
+ return /*#__PURE__*/external_React_default().createElement("div", {
+ className: "story-footer"
+ }, sponsorLabel, /*#__PURE__*/external_React_default().createElement("span", {
+ className: "source clamp cta-footer-source"
+ }, source));
+ }
+ 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,
+ ctaButtonVariant
+}) => /*#__PURE__*/external_React_default().createElement("div", {
+ className: "meta"
+}, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "info-wrap"
+}, ctaButtonVariant !== "variant-b" && /*#__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,
+ cta_button_variant: ctaButtonVariant,
+ source: source
+}), 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",
+ recommendation_id: this.props.recommendation_id,
+ tile_id: this.props.id,
+ ...(this.props.shim && this.props.shim.click ? {
+ shim: this.props.shim.click
+ } : {})
+ }
+ }));
+ 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",
+ recommendation_id: this.props.recommendation_id
+ }]
+ }));
+ }
+ }
+ 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",
+ recommendation_id: this.props.recommendation_id,
+ tile_id: this.props.id,
+ ...(this.props.shim && this.props.shim.save ? {
+ shim: this.props.shim.save
+ } : {})
+ }
+ }));
+ 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
+ } : {}),
+ recommendation_id: this.props.recommendation_id
+ }]
+ }));
+ }
+ }
+ 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.source || this.props.publisher;
+ 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 ctaButtonEnabled = this.props.ctaButtonSponsors?.includes(this.props.sponsor?.toLowerCase());
+ let ctaButtonVariant = "";
+ if (ctaButtonEnabled) {
+ ctaButtonVariant = this.props.ctaButtonVariant;
+ }
+ let ctaButtonVariantClassName = ctaButtonVariant;
+ const ctaButtonClassName = ctaButtonEnabled ? `ds-card-cta-button` : ``;
+ 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} ${ctaButtonClassName} ${ctaButtonVariantClassName}`,
+ 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
+ })), ctaButtonVariant === "variant-b" && /*#__PURE__*/external_React_default().createElement("div", {
+ className: "cta-header"
+ }, "Shop Now"), /*#__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,
+ ctaButtonVariant: ctaButtonVariant
+ }), /*#__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
+ } : {}),
+ recommendation_id: this.props.recommendation_id
+ }],
+ 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",
+ 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?.disconnect();
+ 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 () => 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?.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?.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 {
+ 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 /*#__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() {
+ const prefs = this.props.Prefs.values;
+ const {
+ items,
+ hybridLayout,
+ hideCardBackground,
+ fourCardLayout,
+ compactGrid,
+ essentialReadsHeader,
+ editorsPicksHeader,
+ onboardingExperience,
+ ctaButtonSponsors,
+ ctaButtonVariant,
+ 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,
+ publisher: rec.publisher,
+ pocket_id: rec.pocket_id,
+ context_type: rec.context_type,
+ bookmarkGuid: rec.bookmarkGuid,
+ is_collection: this.props.is_collection,
+ saveToPocketCard: saveToPocketCard,
+ ctaButtonSponsors: ctaButtonSponsors,
+ ctaButtonVariant: ctaButtonVariant,
+ recommendation_id: rec.recommendation_id
+ }));
+ }
+ 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 = /*#__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?.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?.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?.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 ? Object.assign.bind() : 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/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 },
+ 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: [],
+ // The "Share-of-Voice" allocations generated by TopSitesFeed
+ sov: {
+ ready: false,
+ positions: [
+ // {position: 0, assignedPartner: "amp"},
+ // {position: 1, assignedPartner: "moz-sales"},
+ ],
+ },
+ },
+ 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: [],
+ isPrivacyInfoModalVisible: false,
+ isCollectionDismissible: false,
+ feeds: {
+ data: {
+ // "https://foo.com/feed1": {lastUpdated: 123, data: [], personalized: false}
+ },
+ loaded: false,
+ },
+ spocs: {
+ spocs_endpoint: "",
+ lastUpdated: null,
+ data: {
+ // "spocs": {title: "", context: "", items: [], personalized: false},
+ // "placement1": {title: "", context: "", items: [], personalized: false},
+ },
+ 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.SOV_UPDATED:
+ const sov = {
+ ready: action.data.ready,
+ positions: action.data.positions,
+ };
+ return { ...prevState, sov };
+ 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
+ ),
+ })
+ );
+ 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,
+ };
+ case actionTypes.DISCOVERY_STREAM_PERSONALIZATION_RESET:
+ return { ...INITIAL_STATE.Personalization };
+ 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,
+ 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,
+ 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 ? Object.assign.bind() : 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?.sponsored_position || 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.
+ // This first event is for the shim property
+ // and is used by our ad service provider.
+ this.props.dispatch(actionCreators.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: TOP_SITES_SOURCE,
+ action_position: this.props.link.pos,
+ value: {
+ card_type: "spoc",
+ tile_id: this.props.link.id,
+ shim: this.props.link.shim && this.props.link.shim.click
+ }
+ }));
+
+ // A second event is recoded for internal usage.
+ 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 ? Object.assign.bind() : 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 ? Object.assign.bind() : 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 ? Object.assign.bind() : 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) {
+ 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?.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,
+ ctaButtonSponsors: component.properties.ctaButtonSponsors,
+ ctaButtonVariant: component.properties.ctaButtonVariant,
+ 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) {
+ // eventSource: TOP_SITES | TOP_STORIES | HIGHLIGHTS
+ const {
+ preference,
+ eventSource
+ } = e.target.dataset;
+ 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);
+ }
+ } else if (e.target.nodeName === "MOZ-TOGGLE") {
+ value = e.target.pressed;
+ if (eventSource) {
+ this.inputUserEvent(eventSource, value);
+ }
+ }
+ this.props.setPref(preference, 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 /*#__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("moz-toggle", {
+ id: "shortcuts-toggle",
+ pressed: topSitesEnabled || null,
+ onToggle: this.onPreferenceSelect,
+ "data-preference": "feeds.topsites",
+ "data-eventSource": "TOP_SITES",
+ "data-l10n-id": "newtab-custom-shortcuts-toggle",
+ "data-l10n-attrs": "label, description"
+ }), /*#__PURE__*/external_React_default().createElement("div", null, /*#__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",
+ "data-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,
+ "data-preference": "showSponsoredTopSites",
+ "data-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("moz-toggle", {
+ id: "pocket-toggle",
+ pressed: pocketEnabled || null,
+ onToggle: this.onPreferenceSelect,
+ "aria-describedby": "custom-pocket-subtitle",
+ "data-preference": "feeds.section.topstories",
+ "data-eventSource": "TOP_STORIES",
+ "data-l10n-id": "newtab-custom-stories-toggle",
+ "data-l10n-attrs": "label, description"
+ })), /*#__PURE__*/external_React_default().createElement("div", null, (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,
+ "data-preference": "showSponsored",
+ "data-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,
+ "data-preference": "showRecentSaves",
+ "data-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("moz-toggle", {
+ id: "highlights-toggle",
+ pressed: highlightsEnabled || null,
+ onToggle: this.onPreferenceSelect,
+ "data-preference": "feeds.section.highlights",
+ "data-eventSource": "HIGHLIGHTS",
+ "data-l10n-id": "newtab-custom-recent-toggle",
+ "data-l10n-attrs": "label, description"
+ }))), /*#__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.mayHaveSponsoredStories,
+ 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/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: ./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 */
+
+
+
+
+
+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.sys.mjs 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();
+ }
+ }
+ 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", {
+ className: "search-handoff-button",
+ ref: this.onSearchHandoffButtonMount,
+ onClick: this.onSearchHandoffClick,
+ tabIndex: "-1"
+ }, /*#__PURE__*/external_React_default().createElement("div", {
+ className: "fake-textbox"
+ }), /*#__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 ? Object.assign.bind() : 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(DiscoveryStreamAdmin, {
+ 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 mayHaveSponsoredStories = prefs["system.showSponsored"];
+ 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(" ");
+ 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,
+ mayHaveSponsoredStories: mayHaveSponsoredStories,
+ showing: customizeMenuVisible
+ }), /*#__PURE__*/external_React_default().createElement("div", {
+ className: outerClassName,
+ onClick: this.closeCustomizationMenu
+ }, /*#__PURE__*/external_React_default().createElement("main", null, 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("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";
+
+/**
+ * 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);
+ };
+};
+
+/**
+ * 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)(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: external "ReactDOM"
+const external_ReactDOM_namespaceObject = ReactDOM;
+var external_ReactDOM_default = /*#__PURE__*/__webpack_require__.n(external_ReactDOM_namespaceObject);
+;// 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/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/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/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/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..48cf01c331
--- /dev/null
+++ b/browser/components/newtab/docs/index.rst
@@ -0,0 +1,119 @@
+======================
+Firefox Home (New Tab)
+======================
+
+All files related to Firefox Home, which includes content that appears on ``about:home`` and
+``about:newtab``, 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
+
+Discovery Stream Developer tools
+--------------------------------
+
+You can access the developer tools for the Discovery Stream components of about:newtab by
+visiting `about:config` and setting `browser.newtabpage.activity-stream.asrouter.devtoolsEnabled`
+to `true`.
+
+Then, go to any `about:newtab` page and click on the wrench icon in the top-right corner.
+
+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..0366bd3e29
--- /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://firefox-source-docs.mozilla.org/networking/cache2/doc.html).
+
+### `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_events.md b/browser/components/newtab/docs/v2-system-addon/data_events.md
new file mode 100644
index 0000000000..78236bc3b1
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/data_events.md
@@ -0,0 +1,19 @@
+# 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.
+
+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.
+
+The data collected in the Activity Stream is documented
+(along with the other data collected in Firefox Desktop)
+in the [Glean Dictionary](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop).
+
+Ping specifically collected on Firefox Home (New Tab) include:
+* ["newtab"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/newtab)
+* ["pocket-button"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/pocket-button)
+* ["top-sites"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/top-sites)
+* ["quick-suggest"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/quick-suggest)
+* ["messaging-system"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/messaging-system)
+* ["spoc"](https://dictionary.telemetry.mozilla.org/apps/firefox_desktop/pings/spoc)
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..4641e5d001
--- /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.sys.mjs`).
+
+## 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..da77874401
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/mochitests.md
@@ -0,0 +1,26 @@
+# Mochitests
+
+We use [mochitests](https://firefox-source-docs.mozilla.org/testing/browser-chrome/) 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/browser`, and as of this writing, they are all the `browser-chrome` 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.
+
+* 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..ec6ba82491
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/preferences.md
@@ -0,0 +1,270 @@
+# 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.sys.mjs`.
+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.sys.mjs`.
+
+```js
+// Import Prefs
+const { Prefs } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs"
+);
+
+// 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,
+ "personalized": true,
+ }
+ ```
+ - `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`.
+ - `personalized` (boolean): When this is `true` personalized content based on browsing history will be displayed.
+ - `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/sections.md b/browser/components/newtab/docs/v2-system-addon/sections.md
new file mode 100644
index 0000000000..332cf5b26d
--- /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.sys.mjs` 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..848c931717
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/telemetry.md
@@ -0,0 +1,10 @@
+# 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. 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..d7b9912862
--- /dev/null
+++ b/browser/components/newtab/jar.mn
@@ -0,0 +1,40 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.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/*)
+ res/activity-stream/vendor/Redux.sys.mjs (./vendor/Redux.sys.mjs)
+ 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..78ef457865
--- /dev/null
+++ b/browser/components/newtab/karma.mc.config.js
@@ -0,0 +1,287 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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.sys.mjs": {
+ statements: 98,
+ lines: 98,
+ functions: 94,
+ branches: 66,
+ },
+ /**
+ * TelemetryFeed.sys.mjs is tested via an xpcshell test
+ */
+ "lib/TelemetryFeed.sys.mjs": {
+ statements: 10,
+ lines: 10,
+ functions: 9,
+ branches: 0,
+ },
+ "content-src/lib/init-store.js": {
+ statements: 98,
+ lines: 98,
+ functions: 100,
+ branches: 100,
+ },
+ "lib/ActivityStreamStorage.sys.mjs": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 83,
+ },
+ "lib/DownloadsManager.sys.mjs": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 78,
+ },
+ /**
+ * PlacesFeed.sys.mjs is tested via an xpcshell test
+ */
+ "lib/PlacesFeed.sys.mjs": {
+ statements: 7,
+ lines: 7,
+ functions: 8,
+ branches: 0,
+ },
+ "lib/UTEventReporting.sys.mjs": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 75,
+ },
+ "lib/Screenshots.sys.mjs": {
+ statements: 94,
+ lines: 94,
+ functions: 75,
+ branches: 84,
+ },
+ /**
+ * Store.sys.mjs is tested via an xpcshell test
+ */
+ "lib/Store.sys.mjs": {
+ statements: 8,
+ lines: 8,
+ functions: 0,
+ branches: 0,
+ },
+ /**
+ * TopSitesFeed.sys.mjs is tested via an xpcshell test
+ */
+ "lib/TopSitesFeed.sys.mjs": {
+ statements: 9,
+ lines: 9,
+ functions: 5,
+ branches: 0,
+ },
+ /**
+ * TopStoresFeed.sys.mjs is not tested in automation and is slated
+ * for eventual removal.
+ */
+ "lib/TopStoriesFeed.sys.mjs": {
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "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/DiscoveryStreamAdmin/*.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/link-menu-options.js": {
+ statements: 96,
+ lines: 96,
+ functions: 96,
+ branches: 70,
+ },
+ "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.sys.mjs"
+ resolve: {
+ extensions: [".js", ".jsx"],
+ modules: [PATHS.moduleResolveDirectory, "node_modules"],
+ fallback: {
+ stream: require.resolve("stream-browserify"),
+ buffer: require.resolve("buffer"),
+ },
+ alias: {
+ asrouter: path.join(__dirname, "../asrouter"),
+ },
+ },
+ plugins: [
+ // The ResourceUriPlugin handles translating resource URIs in import
+ // statements in .mjs files to paths on the filesystem.
+ new ResourceUriPlugin({
+ resourcePathRegExes: [
+ [
+ new RegExp("^resource://activity-stream/"),
+ path.join(__dirname, "./"),
+ ],
+ ],
+ }),
+ 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: [
+ {
+ test: /\.js$/,
+ exclude: [/node_modules\/(?!@fluent\/).*/, /test/],
+ loader: "babel-loader",
+ },
+ {
+ test: /\.jsx$/,
+ exclude: /node_modules/,
+ loader: "babel-loader",
+ options: {
+ presets: ["@babel/preset-react"],
+ },
+ },
+ {
+ test: /\.md$/,
+ use: "raw-loader",
+ },
+ {
+ enforce: "post",
+ test: /\.js[mx]?$/,
+ loader: "@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")],
+ },
+ ],
+ },
+ },
+ // Silences some overly-verbose logging of individual module builds
+ webpackMiddleware: { noInfo: true },
+ });
+};
diff --git a/browser/components/newtab/lib/AboutPreferences.sys.mjs b/browser/components/newtab/lib/AboutPreferences.sys.mjs
new file mode 100644
index 0000000000..33f7ecdaeb
--- /dev/null
+++ b/browser/components/newtab/lib/AboutPreferences.sys.mjs
@@ -0,0 +1,298 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ actionCreators as ac,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+const HTML_NS = "http://www.w3.org/1999/xhtml";
+export 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",
+ },
+];
+
+export 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,
+ ]);
+ }
+
+ /**
+ * 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);
+ homeDescription.classList.add("description-deemphasized");
+
+ 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 description = createAppend("description", detailVbox);
+ description.classList.add("indent", "text-deemphasized");
+ document.l10n.setAttributes(
+ description,
+ 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");
+ description.setAttribute("flex", 1);
+ detailHbox.appendChild(description);
+
+ // 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();
+ }
+}
diff --git a/browser/components/newtab/lib/ActivityStream.sys.mjs b/browser/components/newtab/lib/ActivityStream.sys.mjs
new file mode 100644
index 0000000000..f2287fe45e
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStream.sys.mjs
@@ -0,0 +1,700 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// AppConstants, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AboutPreferences: "resource://activity-stream/lib/AboutPreferences.sys.mjs",
+ DEFAULT_SITES: "resource://activity-stream/lib/DefaultSites.sys.mjs",
+ DefaultPrefs: "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs",
+ DiscoveryStreamFeed:
+ "resource://activity-stream/lib/DiscoveryStreamFeed.sys.mjs",
+ FaviconFeed: "resource://activity-stream/lib/FaviconFeed.sys.mjs",
+ HighlightsFeed: "resource://activity-stream/lib/HighlightsFeed.sys.mjs",
+ NewTabInit: "resource://activity-stream/lib/NewTabInit.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PrefsFeed: "resource://activity-stream/lib/PrefsFeed.sys.mjs",
+ PlacesFeed: "resource://activity-stream/lib/PlacesFeed.sys.mjs",
+ RecommendationProvider:
+ "resource://activity-stream/lib/RecommendationProvider.sys.mjs",
+ Region: "resource://gre/modules/Region.sys.mjs",
+ SectionsFeed: "resource://activity-stream/lib/SectionsManager.sys.mjs",
+ Store: "resource://activity-stream/lib/Store.sys.mjs",
+ SystemTickFeed: "resource://activity-stream/lib/SystemTickFeed.sys.mjs",
+ TelemetryFeed: "resource://activity-stream/lib/TelemetryFeed.sys.mjs",
+ TopSitesFeed: "resource://activity-stream/lib/TopSitesFeed.sys.mjs",
+ TopStoriesFeed: "resource://activity-stream/lib/TopStoriesFeed.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.
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+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.
+export 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: "User pref for sponsored Pocket content",
+ value: true,
+ },
+ ],
+ [
+ "system.showSponsored",
+ {
+ title: "System pref for sponsored Pocket content",
+ // This pref is dynamic as the sponsored content depends on the region
+ getValue: showSpocs,
+ },
+ ],
+ [
+ "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,
+ },
+ ],
+ [
+ "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,
+ });
+ },
+ },
+ ],
+ [
+ "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);
+}
+
+export 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/ActivityStreamMessageChannel.sys.mjs b/browser/components/newtab/lib/ActivityStreamMessageChannel.sys.mjs
new file mode 100644
index 0000000000..de9d2cb800
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamMessageChannel.sys.mjs
@@ -0,0 +1,333 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, {
+ AboutHomeStartupCache: "resource:///modules/BrowserGlue.sys.mjs",
+ AboutNewTabParent: "resource:///actors/AboutNewTabParent.sys.mjs",
+});
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+const ABOUT_NEW_TAB_URL = "about:newtab";
+
+export 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",
+};
+
+export 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);
+ }
+ }
+
+ // It's possible that those existing tabs had sent some messages up
+ // to us before the feeds / ActivityStreamMessageChannel was ready.
+ //
+ // AboutNewTabParent takes care of queueing those for us, so
+ // now that we're ready, we can flush these queued messages.
+ lazy.AboutNewTabParent.flushQueuedMessagesFromContent();
+ }
+
+ /**
+ * 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);
+ }
+}
diff --git a/browser/components/newtab/lib/ActivityStreamPrefs.sys.mjs b/browser/components/newtab/lib/ActivityStreamPrefs.sys.mjs
new file mode 100644
index 0000000000..192ff30288
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamPrefs.sys.mjs
@@ -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/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// AppConstants, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+// eslint-disable-next-line mozilla/use-static-import
+const { Preferences } = ChromeUtils.importESModule(
+ "resource://gre/modules/Preferences.sys.mjs"
+);
+
+const ACTIVITY_STREAM_PREF_BRANCH = "browser.newtabpage.activity-stream.";
+
+export 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);
+ }
+}
+
+export 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
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/ActivityStreamStorage.sys.mjs b/browser/components/newtab/lib/ActivityStreamStorage.sys.mjs
new file mode 100644
index 0000000000..1e128ec3f2
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamStorage.sys.mjs
@@ -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/. */
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ IndexedDB: "resource://gre/modules/IndexedDB.sys.mjs",
+});
+
+export 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;
+ }
+}
+
+export function getDefaultOptions(options) {
+ return { collapsed: !!options.collapsed };
+}
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.sys.mjs b/browser/components/newtab/lib/DiscoveryStreamFeed.sys.mjs
new file mode 100644
index 0000000000..257036b9da
--- /dev/null
+++ b/browser/components/newtab/lib/DiscoveryStreamFeed.sys.mjs
@@ -0,0 +1,2265 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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, {
+ 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",
+});
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// setTimeout / clearTimeout, and overrides importESModule
+// to be a no-op (which can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+const { setTimeout, clearTimeout } = ChromeUtils.importESModule(
+ "resource://gre/modules/Timer.sys.mjs"
+);
+import {
+ actionTypes as at,
+ actionCreators as ac,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+const CACHE_KEY = "discovery_stream";
+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 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_SYSTEM_SHOW_SPONSORED = "system.showSponsored";
+const PREF_SHOW_SPONSORED_TOPSITES = "showSponsoredTopSites";
+// Nimbus variable to enable the SOV feature for sponsored tiles.
+const NIMBUS_VARIABLE_CONTILE_SOV_ENABLED = "topSitesContileSovEnabled";
+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";
+
+let getHardcodedLayout;
+
+export 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;
+ }
+
+ get config() {
+ if (this._prefCache.config) {
+ return this._prefCache.config;
+ }
+ try {
+ this._prefCache.config = JSON.parse(
+ this.store.getState().Prefs.values[PREF_CONFIG]
+ );
+ } 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 preffedRegionBffConfigString = pocketConfig.regionBffConfig || "";
+ const preffedRegionBffConfig = preffedRegionBffConfigString
+ .split(",")
+ .map(s => s.trim());
+ const regionBff = preffedRegionBffConfig.includes(this.region);
+ this._isBff = 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.store.getState().Prefs.values[PREF_SYSTEM_SHOW_SPONSORED]
+ );
+ }
+
+ 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() {
+ return this.recommendationProvider.personalized;
+ }
+
+ 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.config.api_key_pref;
+ const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
+
+ 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 { spocs, feeds } = cachedData;
+ const updateTimePerComponent = {
+ spocs: this.spocsCacheUpdateTime,
+ feed: COMPONENT_FEEDS_UPDATE_TIME,
+ };
+ const EXPIRATION_TIME = isStartup
+ ? STARTUP_CACHE_EXPIRE_TIME
+ : updateTimePerComponent[key];
+ switch (key) {
+ 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 {
+ 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.spocs || expirationPerComponent.feeds;
+ }
+
+ 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;
+ }
+
+ generateFeedUrl(isBff) {
+ if (isBff) {
+ return `https://${lazy.NimbusFeatures.saveToPocket.getVariable(
+ "bffApi"
+ )}/desktop/v1/recommendations?locale=$locale&region=$region&count=30`;
+ }
+ return FEED_URL;
+ }
+
+ loadLayout(sendUpdate, isStartup) {
+ let layoutData = {};
+ let url = "";
+
+ 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;
+ const { spocTopsitesPlacementEnabled } = pocketConfig;
+
+ let items = isBasicLayout ? 3 : 21;
+ if (pocketConfig.fourCardLayout || pocketConfig.hybridLayout) {
+ items = isBasicLayout ? 4 : 24;
+ }
+
+ const ctaButtonSponsors = pocketConfig.ctaButtonSponsors
+ ?.split(",")
+ .map(s => s.trim().toLowerCase());
+ let ctaButtonVariant = "";
+ // We specifically against hard coded values, instead of applying whatever is in the pref.
+ // This is to ensure random class names from a user modified pref doesn't make it into the class list.
+ if (
+ pocketConfig.ctaButtonVariant === "variant-a" ||
+ pocketConfig.ctaButtonVariant === "variant-b"
+ ) {
+ ctaButtonVariant = pocketConfig.ctaButtonVariant;
+ }
+
+ 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 = this.generateFeedUrl(this.isBff);
+
+ // Set layout config.
+ // Changing values in this layout in memory object is unnecessary.
+ layoutData = getHardcodedLayout({
+ spocsUrl,
+ feedUrl,
+ items,
+ sponsoredCollectionsEnabled,
+ spocPlacementData,
+ spocTopsitesPlacementEnabled,
+ 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,
+ // For now button variants are for experimentation and English only.
+ ctaButtonSponsors: this.locale.startsWith("en-") ? ctaButtonSponsors : [],
+ ctaButtonVariant: this.locale.startsWith("en-") ? ctaButtonVariant : "",
+ });
+
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: layoutData,
+ meta: {
+ isStartup,
+ },
+ });
+
+ if (layoutData.spocs) {
+ url =
+ this.store.getState().Prefs.values[PREF_SPOCS_ENDPOINT] ||
+ this.config.spocs_endpoint ||
+ layoutData.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, layoutData.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 } : {}),
+ };
+ }
+
+ 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 = cachedData.spocs;
+ let placements = this.getPlacements();
+
+ if (
+ this.showSpocs &&
+ placements?.length &&
+ this.isExpired({ cachedData, key: "spocs", isStartup })
+ ) {
+ // We optimistically set this to true, because if SOV is not ready, we fetch them.
+ let useTopsitesPlacement = true;
+
+ // If SOV is turned off or not available, we optimistically fetch sponsored topsites.
+ if (
+ lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_SOV_ENABLED
+ )
+ ) {
+ let { positions, ready } = this.store.getState().TopSites.sov;
+ if (ready) {
+ // We don't need to await here, because we don't need it now.
+ this.cache.set("sov", positions);
+ } else {
+ // If SOV is not available, and there is a SOV cache, use it.
+ positions = cachedData.sov;
+ }
+
+ if (positions?.length) {
+ // If SOV is ready and turned on, we can check if we need moz-sales position.
+ useTopsitesPlacement = positions.some(
+ allocation => allocation.assignedPartner === "moz-sales"
+ );
+ }
+ }
+
+ // We can filter out the topsite placement from the fetch.
+ if (!useTopsitesPlacement) {
+ placements = placements.filter(
+ placement => placement.name !== "sponsored-topsites"
+ );
+ }
+
+ if (placements?.length) {
+ const endpoint =
+ this.store.getState().DiscoveryStream.spocs.spocs_endpoint;
+
+ const headers = new Headers();
+ headers.append("content-type", "application/json");
+
+ const apiKeyPref = this.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.store.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE,
+ data: {
+ override: !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, personalized } =
+ await this.scoreItems(blockedResults, "spocs");
+
+ spocsState.spocs = {
+ ...spocsState.spocs,
+ [placement.name]: {
+ title,
+ context,
+ sponsor,
+ sponsored_by_override,
+ personalized,
+ items: scoredResults,
+ },
+ };
+ }
+ );
+ await Promise.all(spocsResultPromises);
+
+ this.cleanUpFlightImpressionPref(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: {},
+ };
+ await this.cache.set("spocs", {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.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,
+ }),
+ });
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ 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;
+ // If this is initialized, we are ready to go.
+ const personalized = this.store.getState().Personalization.initialized;
+
+ const data = (
+ await Promise.all(
+ items.map(item => this.scoreItem(item, personalizedByType))
+ )
+ )
+ // Sort by highest scores.
+ .sort(this.sortItem);
+
+ return { data, personalized };
+ }
+
+ 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,
+ time_to_read: item.timeToRead,
+ raw_image_src: item.imageUrl,
+ recommendation_id: item.recommendationId,
+ }));
+ }
+ const { data: scoredItems, personalized } = await this.scoreItems(
+ recommendations,
+ "feed"
+ );
+ const { recsExpireTime } = settings;
+ const rotatedItems = this.rotate(scoredItems, recsExpireTime);
+ this.componentFeedFetched = true;
+ feed = {
+ lastUpdated: Date.now(),
+ personalized,
+ 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.spocs) {
+ await this.loadSpocs(this.store.dispatch);
+ }
+ if (expirationPerComponent.feeds) {
+ await this.loadComponentFeeds(this.store.dispatch);
+ }
+ }
+
+ async scoreFeeds(feedsState) {
+ if (feedsState.data) {
+ const feeds = {};
+ const feedsPromises = Object.keys(feedsState.data).map(url => {
+ let feed = feedsState.data[url];
+ if (feed.personalized) {
+ // Feed was previously personalized then cached, we don't need to do this again.
+ return Promise.resolve();
+ }
+ const feedPromise = this.scoreItems(feed.data.recommendations, "feed");
+ feedPromise.then(({ data: scoredItems, personalized }) => {
+ const { recsExpireTime } = feed.data.settings;
+ const recommendations = this.rotate(scoredItems, recsExpireTime);
+ feed = {
+ ...feed,
+ personalized,
+ 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 (nextSpocs.personalized || !items || !items.length) {
+ return;
+ }
+
+ const { data: scoreResult, personalized } = await this.scoreItems(
+ items,
+ "spocs"
+ );
+
+ spocsState.data = {
+ ...spocsState.data,
+ [placement.name]: {
+ ...nextSpocs,
+ personalized,
+ 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,
+ },
+ })
+ );
+ }
+
+ /**
+ * @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 component feeds, and spocs in order if caches have expired.
+ * @param {RefreshAll} options
+ */
+ async refreshAll(options = {}) {
+ const { updateOpenTabs, isStartup } = options;
+
+ const dispatch = updateOpenTabs
+ ? action => this.store.dispatch(ac.BroadcastToContent(action))
+ : this.store.dispatch;
+
+ 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) {
+ // We don't pass isStartup in _maybeUpdateCachedData on purpose,
+ // because startup loads have a longer cache timer,
+ // and we want this to update in the background sooner.
+ 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) {
+ // If stories are being re enabled, ensure we have stories.
+ this.refreshAll({ updateOpenTabs: true });
+ }
+ }
+
+ async enable(options = {}) {
+ await this.refreshAll(options);
+ this.loaded = true;
+ }
+
+ async reset() {
+ this.resetDataPrefs();
+ await this.resetCache();
+ this.resetState();
+ }
+
+ async resetCache() {
+ await this.resetAllCache();
+ }
+
+ async resetContentCache() {
+ await this.cache.set("feeds", {});
+ await this.cache.set("spocs", {});
+ await this.cache.set("sov", {});
+ }
+
+ async resetAllCache() {
+ await this.resetContentCache();
+ // 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.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({ updateOpenTabs: true });
+ }
+ }
+
+ // 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_SPOCS_CLEAR_ENDPOINT:
+ case PREF_ENDPOINTS:
+ // 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({ updateOpenTabs: true, isStartup: true });
+ }
+ 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_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_PERSONALIZATION_UPDATED:
+ if (this.personalized) {
+ const { feeds, spocs } = this.store.getState().DiscoveryStream;
+ const spocsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.spocsPersonalized;
+ const recsPersonalized =
+ this.store.getState().Prefs.values?.pocketConfig?.recsPersonalized;
+ if (recsPersonalized && feeds.loaded) {
+ this.scoreFeeds(feeds);
+ }
+ if (spocsPersonalized && spocs.loaded) {
+ this.scoreSpocs(spocs);
+ }
+ }
+ 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.
+ `spocTopsitesPlacementEnabled` Tuns on and off the sponsored topsites placement.
+ `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.
+ `ctaButtonSponsors` An array of sponsors we want to show a cta button on the card for.
+ `ctaButtonVariant` Sets the variant for the cta sponsor button.
+*/
+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] },
+ spocTopsitesPlacementEnabled = false,
+ spocTopsitesPlacementData = { ad_types: [3120], zone_ids: [280143] },
+ widgetPositions = [],
+ widgetData = [],
+ sponsoredCollectionsEnabled = false,
+ hybridLayout = false,
+ hideCardBackground = false,
+ fourCardLayout = false,
+ newFooterSection = false,
+ compactGrid = false,
+ essentialReadsHeader = false,
+ editorsPicksHeader = false,
+ onboardingExperience = false,
+ ctaButtonSponsors = [],
+ ctaButtonVariant = "",
+}) => ({
+ lastUpdate: Date.now(),
+ spocs: {
+ url: spocsUrl,
+ },
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "TopSites",
+ header: {
+ title: {
+ id: "newtab-section-header-topsites",
+ },
+ },
+ ...(spocTopsitesPlacementEnabled && 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-stories",
+ },
+ 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,
+ ctaButtonSponsors,
+ ctaButtonVariant,
+ },
+ 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/#recommend-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",
+ },
+ },
+ },
+ ]
+ : []),
+ ],
+ },
+ ],
+});
diff --git a/browser/components/newtab/lib/DownloadsManager.sys.mjs b/browser/components/newtab/lib/DownloadsManager.sys.mjs
new file mode 100644
index 0000000000..f095645d41
--- /dev/null
+++ b/browser/components/newtab/lib/DownloadsManager.sys.mjs
@@ -0,0 +1,188 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionTypes as at } from "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
+
+export 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/FaviconFeed.sys.mjs b/browser/components/newtab/lib/FaviconFeed.sys.mjs
new file mode 100644
index 0000000000..a76566d3e8
--- /dev/null
+++ b/browser/components/newtab/lib/FaviconFeed.sys.mjs
@@ -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 { actionTypes as at } from "resource://activity-stream/common/Actions.sys.mjs";
+import { getDomain } from "resource://activity-stream/lib/TippyTopProvider.sys.mjs";
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// RemoteSettings, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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.
+ */
+export 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()
+ );
+ }
+ }
+}
+
+export 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/FilterAdult.sys.mjs b/browser/components/newtab/lib/FilterAdult.sys.mjs
new file mode 100644
index 0000000000..a60ba3baa6
--- /dev/null
+++ b/browser/components/newtab/lib/FilterAdult.sys.mjs
@@ -0,0 +1,3040 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// XPCOMUtils, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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);
+}
+
+export 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)))
+ );
+ },
+};
+
+// 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.sys.mjs b/browser/components/newtab/lib/HighlightsFeed.sys.mjs
new file mode 100644
index 0000000000..c603b886da
--- /dev/null
+++ b/browser/components/newtab/lib/HighlightsFeed.sys.mjs
@@ -0,0 +1,322 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 { shortURL } from "resource://activity-stream/lib/ShortURL.sys.mjs";
+import {
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "resource://activity-stream/common/Reducers.sys.mjs";
+import { Dedupe } from "resource://activity-stream/common/Dedupe.sys.mjs";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ DownloadsManager: "resource://activity-stream/lib/DownloadsManager.sys.mjs",
+ FilterAdult: "resource://activity-stream/lib/FilterAdult.sys.mjs",
+ LinksCache: "resource://activity-stream/lib/LinksCache.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+ Screenshots: "resource://activity-stream/lib/Screenshots.sys.mjs",
+ SectionsManager: "resource://activity-stream/lib/SectionsManager.sys.mjs",
+});
+
+const HIGHLIGHTS_MAX_LENGTH = 16;
+
+export const MANY_EXTRA_LENGTH =
+ HIGHLIGHTS_MAX_LENGTH * 5 +
+ TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW;
+
+export const SECTION_ID = "highlights";
+export const SYNC_BOOKMARKS_FINISHED_EVENT = "weave:engine:sync:applied";
+export const BOOKMARKS_RESTORE_SUCCESS_EVENT = "bookmarks-restore-success";
+export const BOOKMARKS_RESTORE_FAILED_EVENT = "bookmarks-restore-failed";
+const RECENT_DOWNLOAD_THRESHOLD = 36 * 60 * 60 * 1000;
+
+export 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);
+ lazy.SectionsManager.onceInitialized(this.postInit.bind(this));
+ }
+
+ postInit() {
+ lazy.SectionsManager.enableSection(SECTION_ID, true /* isStartup */);
+ this.fetchHighlights({ broadcast: true, isStartup: true });
+ this.downloadsManager.init(this.store);
+ }
+
+ uninit() {
+ lazy.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 lazy.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;
+
+ lazy.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 => {
+ lazy.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;
+ }
+ }
+}
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/NewTabInit.sys.mjs b/browser/components/newtab/lib/NewTabInit.sys.mjs
new file mode 100644
index 0000000000..db30e009ec
--- /dev/null
+++ b/browser/components/newtab/lib/NewTabInit.sys.mjs
@@ -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/. */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "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.
+ */
+export 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/PersistentCache.sys.mjs b/browser/components/newtab/lib/PersistentCache.sys.mjs
new file mode 100644
index 0000000000..1db9ca102e
--- /dev/null
+++ b/browser/components/newtab/lib/PersistentCache.sys.mjs
@@ -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/. */
+
+/**
+ * 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.mjs b/browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.mjs
new file mode 100644
index 0000000000..d5930e3147
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.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/. */
+
+export 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.mjs b/browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.mjs
new file mode 100644
index 0000000000..5c77152d8d
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.mjs
@@ -0,0 +1,58 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 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.sys.mjs b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.sys.mjs
new file mode 100644
index 0000000000..406a0fa200
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.sys.mjs
@@ -0,0 +1,277 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ BasePromiseWorker: "resource://gre/modules/PromiseWorker.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
+ Utils: "resource://services-settings/Utils.sys.mjs",
+});
+
+const RECIPE_NAME = "personality-provider-recipe";
+const MODELS_NAME = "personality-provider-models";
+
+export 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 lazy.BasePromiseWorker(
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.worker.mjs",
+ { type: "module" }
+ );
+
+ 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,
+ };
+ }
+}
diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.worker.mjs b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.worker.mjs
new file mode 100644
index 0000000000..49797f4f2b
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.worker.mjs
@@ -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 { PersonalityProviderWorker } from "resource://activity-stream/lib/PersonalityProvider/PersonalityProviderWorkerClass.mjs";
+
+import { PromiseWorker } from "resource://gre/modules/workers/PromiseWorker.mjs";
+
+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.mjs b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.mjs
new file mode 100644
index 0000000000..372c061dd9
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.mjs
@@ -0,0 +1,306 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 {
+ tokenize,
+ toksToTfIdfVector,
+} from "resource://activity-stream/lib/PersonalityProvider/Tokenize.mjs";
+import { NaiveBayesTextTagger } from "resource://activity-stream/lib/PersonalityProvider/NaiveBayesTextTagger.mjs";
+import { NmfTextTagger } from "resource://activity-stream/lib/PersonalityProvider/NmfTextTagger.mjs";
+import { RecipeExecutor } from "resource://activity-stream/lib/PersonalityProvider/RecipeExecutor.mjs";
+
+// 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.
+ */
+export 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: loc, filename },
+ } = record;
+ const remoteFilePath = this.baseAttachmentsURL + loc;
+ 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(historyObj) {
+ let interestVector = {};
+
+ for (let historyRec of historyObj) {
+ 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.mjs b/browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.mjs
new file mode 100644
index 0000000000..4f420c0812
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.mjs
@@ -0,0 +1,1119 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * 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 .
+ */
+export 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.mjs b/browser/components/newtab/lib/PersonalityProvider/Tokenize.mjs
new file mode 100644
index 0000000000..740b2fc541
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/Tokenize.mjs
@@ -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/. */
+
+// 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).
+ */
+export 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.
+ */
+export 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.sys.mjs b/browser/components/newtab/lib/PlacesFeed.sys.mjs
new file mode 100644
index 0000000000..70011412f8
--- /dev/null
+++ b/browser/components/newtab/lib/PlacesFeed.sys.mjs
@@ -0,0 +1,572 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ actionUtils as au,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+import { shortURL } from "resource://activity-stream/lib/ShortURL.sys.mjs";
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// AboutNewTab, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+const { AboutNewTab } = ChromeUtils.importESModule(
+ "resource:///modules/AboutNewTab.sys.mjs"
+);
+
+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 },
+ });
+ }
+ }
+}
+
+export 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 {
+ // To avoid blocking Places notifications on expensive work, run it at the
+ // next tick of the events loop.
+ Services.tm.dispatchToMainThread(() =>
+ 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;
diff --git a/browser/components/newtab/lib/PrefsFeed.sys.mjs b/browser/components/newtab/lib/PrefsFeed.sys.mjs
new file mode 100644
index 0000000000..1c6f9b0d45
--- /dev/null
+++ b/browser/components/newtab/lib/PrefsFeed.sys.mjs
@@ -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 "resource://activity-stream/common/Actions.sys.mjs";
+import { Prefs } from "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs";
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// AppConstants, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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",
+});
+
+export 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,
+ });
+
+ // 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/RecommendationProvider.sys.mjs b/browser/components/newtab/lib/RecommendationProvider.sys.mjs
new file mode 100644
index 0000000000..03e976544f
--- /dev/null
+++ b/browser/components/newtab/lib/RecommendationProvider.sys.mjs
@@ -0,0 +1,291 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const lazy = {};
+ChromeUtils.defineESModuleGetters(lazy, {
+ PersistentCache: "resource://activity-stream/lib/PersistentCache.sys.mjs",
+ PersonalityProvider:
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.sys.mjs",
+});
+
+import {
+ actionTypes as at,
+ actionCreators as ac,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+
+const CACHE_KEY = "personalization";
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+const PREF_USER_TOPSTORIES = "feeds.section.topstories";
+const PREF_SYSTEM_TOPSTORIES = "feeds.system.topstories";
+const PREF_PERSONALIZATION = "discoverystream.personalization.enabled";
+const MIN_PERSONALIZATION_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
+const PREF_PERSONALIZATION_OVERRIDE =
+ "discoverystream.personalization.override";
+
+// 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.
+export class RecommendationProvider {
+ constructor() {
+ // Persistent cache for remote endpoint data.
+ this.cache = new lazy.PersistentCache(CACHE_KEY, true);
+ }
+
+ async setProvider(isStartup = false, 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) {
+ this.provider = new lazy.PersonalityProvider(this.modelKeys);
+ this.provider.setScores(scores);
+ }
+
+ if (this.provider && this.provider.init) {
+ await this.provider.init();
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_INIT,
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+ }
+
+ async enable(isStartup) {
+ await this.loadPersonalizationScoresCache(isStartup);
+ Services.obs.addObserver(this, "idle-daily");
+ this.loaded = true;
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+
+ 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 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 &&
+ (spocsPersonalized || recsPersonalized)
+ );
+ }
+
+ get modelKeys() {
+ if (!this._modelKeys) {
+ this._modelKeys =
+ this.store.getState().Prefs.values[PREF_PERSONALIZATION_MODEL_KEYS];
+ }
+
+ return this._modelKeys;
+ }
+
+ /*
+ * 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;
+ }
+
+ await this.setProvider();
+
+ const personalization = { scores: this.provider.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);
+ }
+
+ /*
+ * 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?.scores) {
+ await this.setProvider(isStartup, 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 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 },
+ });
+ }
+ }
+
+ 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();
+ }
+ if (this.loaded) {
+ Services.obs.removeObserver(this, "idle-daily");
+ }
+ this.loaded = false;
+ }
+
+ async resetState() {
+ this._modelKeys = null;
+ this.personalizationLastUpdated = null;
+ this.provider = null;
+ await this.cache.set("personalization", {});
+ this.store.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_RESET,
+ })
+ );
+ }
+
+ async observe(subject, topic, data) {
+ switch (topic) {
+ case "idle-daily":
+ await this.updatePersonalizationScores();
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
+ })
+ );
+ break;
+ }
+ }
+
+ async onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ await this.enable(true /* isStartup */);
+ break;
+ case at.DISCOVERY_STREAM_CONFIG_CHANGE:
+ this.teardown();
+ await this.resetState();
+ await this.enable();
+ break;
+ case at.DISCOVERY_STREAM_DEV_IDLE_DAILY:
+ Services.obs.notifyObservers(null, "idle-daily");
+ 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;
+ case at.DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE:
+ this.personalizationOverride(action.data.override);
+ break;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/Screenshots.sys.mjs b/browser/components/newtab/lib/Screenshots.sys.mjs
new file mode 100644
index 0000000000..e5423bd52f
--- /dev/null
+++ b/browser/components/newtab/lib/Screenshots.sys.mjs
@@ -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/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// XPCOMUtils, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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
+);
+
+export 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..1448f87ca4
--- /dev/null
+++ b/browser/components/newtab/lib/SearchShortcuts.sys.mjs
@@ -0,0 +1,73 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// 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) {
+ try {
+ return !!(await Services.search.getAppProvidedEngines()).find(
+ e => e.aliases.includes(keyword) && !e.hidden
+ );
+ } catch {
+ // When the search service has not successfully initialized,
+ // there will be no search engines ready.
+ return false;
+ }
+}
diff --git a/browser/components/newtab/lib/SectionsManager.sys.mjs b/browser/components/newtab/lib/SectionsManager.sys.mjs
new file mode 100644
index 0000000000..96bba0c9ea
--- /dev/null
+++ b/browser/components/newtab/lib/SectionsManager.sys.mjs
@@ -0,0 +1,715 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// EventEmitter, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+const { EventEmitter } = ChromeUtils.importESModule(
+ "resource://gre/modules/EventEmitter.sys.mjs"
+);
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+import { getDefaultOptions } from "resource://activity-stream/lib/ActivityStreamStorage.sys.mjs";
+
+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-generic",
+ },
+ descString: {
+ id: "home-prefs-recommended-by-description-generic",
+ },
+ nestedPrefs: [
+ ...(Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.system.showSponsored",
+ true
+ )
+ ? [
+ {
+ 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-stories",
+ },
+ 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-generic",
+ },
+ 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,
+ }),
+});
+
+export 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);
+
+export 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
+ );
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/ShortURL.sys.mjs b/browser/components/newtab/lib/ShortURL.sys.mjs
new file mode 100644
index 0000000000..6ee34c20dd
--- /dev/null
+++ b/browser/components/newtab/lib/ShortURL.sys.mjs
@@ -0,0 +1,88 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// XPCOMUtils, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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.
+ */
+export 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
+ */
+export 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
+ );
+}
diff --git a/browser/components/newtab/lib/SiteClassifier.sys.mjs b/browser/components/newtab/lib/SiteClassifier.sys.mjs
new file mode 100644
index 0000000000..64c7309bf5
--- /dev/null
+++ b/browser/components/newtab/lib/SiteClassifier.sys.mjs
@@ -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/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on this module. This
+// is because the Karma test environment already stubs out
+// RemoteSettings, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement).
+
+// eslint-disable-next-line mozilla/use-static-import
+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,
+ * },...]
+ */
+export 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;
+}
diff --git a/browser/components/newtab/lib/Store.sys.mjs b/browser/components/newtab/lib/Store.sys.mjs
new file mode 100644
index 0000000000..3a4fdfa98d
--- /dev/null
+++ b/browser/components/newtab/lib/Store.sys.mjs
@@ -0,0 +1,188 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { ActivityStreamMessageChannel } from "resource://activity-stream/lib/ActivityStreamMessageChannel.sys.mjs";
+import { ActivityStreamStorage } from "resource://activity-stream/lib/ActivityStreamStorage.sys.mjs";
+import { Prefs } from "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs";
+import { reducers } from "resource://activity-stream/common/Reducers.sys.mjs";
+import { redux } from "resource://activity-stream/vendor/Redux.sys.mjs";
+
+/**
+ * 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.
+ */
+export 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) {
+ // "snippets" is the name of one storage space, but these days it is used
+ // not for snippet-related data (snippets were removed in bug 1715158),
+ // but storage for impression or session data for all ASRouter messages.
+ //
+ // We keep the name "snippets" to avoid having to do an IndexedDB database
+ // migration.
+ 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;
+ }
+}
diff --git a/browser/components/newtab/lib/SystemTickFeed.sys.mjs b/browser/components/newtab/lib/SystemTickFeed.sys.mjs
new file mode 100644
index 0000000000..d87860fab2
--- /dev/null
+++ b/browser/components/newtab/lib/SystemTickFeed.sys.mjs
@@ -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 { actionTypes as at } from "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
+export const SYSTEM_TICK_INTERVAL = 5 * 60 * 1000;
+
+export 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/TelemetryFeed.sys.mjs b/browser/components/newtab/lib/TelemetryFeed.sys.mjs
new file mode 100644
index 0000000000..99bed168a8
--- /dev/null
+++ b/browser/components/newtab/lib/TelemetryFeed.sys.mjs
@@ -0,0 +1,1122 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// We use importESModule here instead of static import so that
+// the Karma test environment won't choke on these module. This
+// is because the Karma test environment already stubs out
+// XPCOMUtils, and overrides importESModule to be a no-op (which
+// can't be done for a static import statement). MESSAGE_TYPES_HASH / msg
+// isn't something that the tests for this module seem to rely on in the
+// Karma environment, but if that ever becomes the case, we should import
+// those into unit-entry like we do for the ASRouter tests.
+
+// eslint-disable-next-line mozilla/use-static-import
+const { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+// eslint-disable-next-line mozilla/use-static-import
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ActorConstants.sys.mjs"
+);
+
+import {
+ actionTypes as at,
+ actionUtils as au,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+import { Prefs } from "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs";
+import { classifySite } from "resource://activity-stream/lib/SiteClassifier.sys.mjs";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
+ AboutWelcomeTelemetry:
+ "resource:///modules/aboutwelcome/AboutWelcomeTelemetry.sys.mjs",
+ ClientID: "resource://gre/modules/ClientID.sys.mjs",
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ExtensionSettingsStore:
+ "resource://gre/modules/ExtensionSettingsStore.sys.mjs",
+ HomePage: "resource:///modules/HomePage.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.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.defineLazyGetter(
+ lazy,
+ "Telemetry",
+ () => new lazy.AboutWelcomeTelemetry()
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ lazy,
+ "handoffToAwesomebarPrefValue",
+ "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar",
+ false,
+ (preference, previousValue, new_value) =>
+ Glean.newtabHandoffPreference.enabled.set(new_value)
+);
+
+// This is a mapping table between the user preferences and its encoding code
+export const USER_PREFS_ENCODING = {
+ showSearch: 1 << 0,
+ "feeds.topsites": 1 << 1,
+ "feeds.section.topstories": 1 << 2,
+ "feeds.section.highlights": 1 << 3,
+ showSponsored: 1 << 5,
+ "asrouter.userprefs.cfr.addons": 1 << 6,
+ "asrouter.userprefs.cfr.features": 1 << 7,
+ showSponsoredTopSites: 1 << 8,
+};
+
+export const PREF_IMPRESSION_ID = "impressionId";
+export const TELEMETRY_PREF = "telemetry";
+export const EVENTS_TELEMETRY_PREF = "telemetry.ut.events";
+
+// 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",
+];
+
+ChromeUtils.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";
+ChromeUtils.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 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 TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+
+export class TelemetryFeed {
+ constructor() {
+ this.sessions = new Map();
+ this._prefs = new Prefs();
+ this._impressionId = this.getOrCreateImpressionId();
+ this._aboutHomeSeen = false;
+ this._classifySite = classifySite;
+ this._browserOpenNewtabStart = null;
+ }
+
+ get telemetryEnabled() {
+ return this._prefs.get(TELEMETRY_PREF);
+ }
+
+ get eventTelemetryEnabled() {
+ return this._prefs.get(EVENTS_TELEMETRY_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"
+ );
+ // 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);
+ Glean.newtabHandoffPreference.enabled.set(
+ lazy.handoffToAwesomebarPrefValue
+ );
+ }
+
+ 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 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;
+ }
+
+ 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.sendUTEvent(sessionEndEvent, this.utEvents.sendSessionEndEvent);
+ this.sessions.delete(portID);
+ }
+
+ /**
+ * 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;
+ }
+
+ 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 "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 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" };
+ }
+
+ sendUTEvent(event_object, eventFunction) {
+ if (this.telemetryEnabled && this.eventTelemetryEnabled) {
+ eventFunction(event_object);
+ }
+ }
+
+ handleTopSitesSponsoredImpressionStats(action) {
+ const { data } = action;
+ const {
+ type,
+ position,
+ source,
+ advertiser: advertiser_name,
+ tile_id,
+ } = data;
+ // Legacy telemetry 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,
+ 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,
+ newtab_visit_id: session.session_id,
+ is_sponsored: true,
+ position,
+ });
+ }
+ } else {
+ console.error("Unknown ping type for sponsored TopSites impression");
+ return;
+ }
+
+ Glean.topSites.pingType.set(pingType);
+ Glean.topSites.position.set(legacyTelemetryPosition);
+ Glean.topSites.source.set(source);
+ Glean.topSites.tileId.set(tile_id);
+ if (data.reporting_url) {
+ Glean.topSites.reportingUrl.set(data.reporting_url);
+ }
+ Glean.topSites.advertiser.set(advertiser_name);
+ Glean.topSites.contextId.set(lazy.contextId);
+ GleanPings.topSites.submit();
+ }
+
+ 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.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":
+ const { card_type, topic, recommendation_id, tile_id, shim } =
+ action.data.value ?? {};
+ if (
+ action.data.source === "POPULAR_TOPICS" ||
+ card_type === "topics_widget"
+ ) {
+ Glean.pocket.topicClick.record({
+ newtab_visit_id: session.session_id,
+ topic,
+ });
+ } else if (["spoc", "organic"].includes(card_type)) {
+ Glean.pocket.click.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: card_type === "spoc",
+ position: action.data.action_position,
+ recommendation_id,
+ tile_id,
+ });
+ if (shim) {
+ Glean.pocket.shim.set(shim);
+ GleanPings.spoc.submit("click");
+ }
+ }
+ 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,
+ recommendation_id: action.data.value?.recommendation_id,
+ tile_id: action.data.value?.tile_id,
+ });
+ if (action.data.value?.shim) {
+ Glean.pocket.shim.set(action.data.value.shim);
+ GleanPings.spoc.submit("save");
+ }
+ 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 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 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
+ );
+ 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;
+ 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";
+ }
+
+ 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.DISCOVERY_STREAM_IMPRESSION_STATS:
+ this.handleDiscoveryStreamImpressionStats(
+ 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;
+ case at.ABOUT_SPONSORED_TOP_SITES:
+ this.handleAboutSponsoredTopSites(action);
+ break;
+ case at.BLOCK_URL:
+ this.handleBlockUrl(action);
+ break;
+ }
+ }
+
+ handleBlockUrl(action) {
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ // TODO: Do we want to not send this unless there's a newtab_visit_id?
+ if (!session) {
+ return;
+ }
+
+ // Despite the action name, this is actually a bulk dismiss action:
+ // it can be applied to multiple topsites simultaneously.
+ const { data } = action;
+ for (const datum of data) {
+ if (datum.is_pocket_card) {
+ // There is no instrumentation for Pocket dismissals (yet).
+ continue;
+ }
+ const { position, advertiser_name, tile_id, isSponsoredTopSite } = datum;
+ Glean.topsites.dismiss.record({
+ advertiser_name,
+ tile_id,
+ newtab_visit_id: session.session_id,
+ is_sponsored: !!isSponsoredTopSite,
+ position,
+ });
+ }
+ }
+
+ handleAboutSponsoredTopSites(action) {
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ const { data } = action;
+ const { position, advertiser_name, tile_id } = data;
+
+ if (session) {
+ Glean.topsites.showPrivacyClick.record({
+ advertiser_name,
+ tile_id,
+ newtab_visit_id: session.session_id,
+ position,
+ });
+ }
+ }
+
+ /**
+ * Handle impression stats actions from Discovery Stream.
+ *
+ * @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 { tiles } = data;
+ tiles.forEach(tile => {
+ Glean.pocket.impression.record({
+ newtab_visit_id: session.session_id,
+ is_sponsored: tile.type === "spoc",
+ position: tile.pos,
+ recommendation_id: tile.recommendation_id,
+ tile_id: tile.id,
+ });
+ if (tile.shim) {
+ Glean.pocket.shim.set(tile.shim);
+ GleanPings.spoc.submit("impression");
+ }
+ });
+ }
+
+ /**
+ * 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() {
+ Services.prefs.addObserver(ACTIVITY_STREAM_PREF_BRANCH, this);
+
+ for (const pref of Object.keys(NEWTAB_PING_PREFS)) {
+ const fullPrefName = ACTIVITY_STREAM_PREF_BRANCH + pref;
+ this._setNewtabPrefMetrics(fullPrefName, false);
+ }
+ Glean.pocket.isSignedIn.set(lazy.pktApi.isUserLoggedIn());
+
+ Services.prefs.addObserver(TOP_SITES_BLOCKED_SPONSORS_PREF, this);
+ this._setBlockedSponsorsMetrics();
+ }
+
+ _stopObservingNewtabPingPrefs() {
+ Services.prefs.removeObserver(ACTIVITY_STREAM_PREF_BRANCH, this);
+ Services.prefs.removeObserver(TOP_SITES_BLOCKED_SPONSORS_PREF, this);
+ }
+
+ observe(subject, topic, data) {
+ if (data === TOP_SITES_BLOCKED_SPONSORS_PREF) {
+ this._setBlockedSponsorsMetrics();
+ } else {
+ this._setNewtabPrefMetrics(data, true);
+ }
+ }
+
+ _setNewtabPrefMetrics(fullPrefName, isChanged) {
+ 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;
+ }
+ if (isChanged) {
+ switch (fullPrefName) {
+ case `${ACTIVITY_STREAM_PREF_BRANCH}feeds.topsites`:
+ case `${ACTIVITY_STREAM_PREF_BRANCH}showSponsoredTopSites`:
+ Glean.topsites.prefChanged.record({
+ pref_name: fullPrefName,
+ new_value: Services.prefs.getBoolPref(fullPrefName),
+ });
+ break;
+ }
+ }
+ }
+
+ _setBlockedSponsorsMetrics() {
+ let blocklist;
+ try {
+ blocklist = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF, "[]")
+ );
+ } catch (e) {}
+ if (blocklist) {
+ Glean.newtab.blockedSponsors.set(blocklist);
+ }
+ }
+
+ uninit() {
+ this._stopObservingNewtabPingPrefs();
+
+ try {
+ Services.obs.removeObserver(
+ this.browserOpenNewtabStart,
+ "browser-open-newtab-start"
+ );
+ } 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, "utEvents")) {
+ this.utEvents.uninit();
+ }
+
+ // TODO: Send any unfinished sessions
+ }
+}
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/TopSitesFeed.sys.mjs b/browser/components/newtab/lib/TopSitesFeed.sys.mjs
new file mode 100644
index 0000000000..db21411fdd
--- /dev/null
+++ b/browser/components/newtab/lib/TopSitesFeed.sys.mjs
@@ -0,0 +1,2007 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 "resource://activity-stream/common/Actions.sys.mjs";
+import { TippyTopProvider } from "resource://activity-stream/lib/TippyTopProvider.sys.mjs";
+import {
+ insertPinned,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "resource://activity-stream/common/Reducers.sys.mjs";
+import { Dedupe } from "resource://activity-stream/common/Dedupe.sys.mjs";
+import { shortURL } from "resource://activity-stream/lib/ShortURL.sys.mjs";
+import { getDefaultOptions } from "resource://activity-stream/lib/ActivityStreamStorage.sys.mjs";
+
+import {
+ CUSTOM_SEARCH_SHORTCUTS,
+ SEARCH_SHORTCUTS_EXPERIMENT,
+ SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF,
+ SEARCH_SHORTCUTS_HAVE_PINNED_PREF,
+ checkHasSearchEngine,
+ getSearchProvider,
+ getSearchFormURL,
+} from "resource://activity-stream/lib/SearchShortcuts.sys.mjs";
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ FilterAdult: "resource://activity-stream/lib/FilterAdult.sys.mjs",
+ 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",
+ Screenshots: "resource://activity-stream/lib/Screenshots.sys.mjs",
+});
+
+ChromeUtils.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";
+ChromeUtils.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";
+export 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 NIMBUS_VARIABLE_CONTILE_POSITIONS = "contileTopsitesPositions";
+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,
+]);
+
+const DISPLAY_FAIL_REASON_OVERSOLD = "oversold";
+const DISPLAY_FAIL_REASON_DISMISSED = "dismissed";
+const DISPLAY_FAIL_REASON_UNRESOLVED = "unresolved";
+
+function getShortURLForCurrentSearch() {
+ const url = shortURL({ url: Services.search.defaultEngine.searchForm });
+ return url;
+}
+
+class TopSitesTelemetry {
+ constructor() {
+ this.allSponsoredTiles = {};
+ this.sponsoredTilesConfigured = 0;
+ }
+
+ _tileProviderForTiles(tiles) {
+ // Assumption: the list of tiles is from a single provider
+ return tiles && tiles.length ? this._tileProvider(tiles[0]) : null;
+ }
+
+ _tileProvider(tile) {
+ return tile.partner || SPONSORED_TILE_PARTNER_AMP;
+ }
+
+ _buildPropertyKey(tile) {
+ let provider = this._tileProvider(tile);
+ return provider + shortURL(tile);
+ }
+
+ // Returns an array of strings indicating the property name (based on the
+ // provider and brand) of tiles that have been filtered e.g. ["moz-salesbrand1"]
+ // currentTiles: The list of tiles remaining and may be displayed in new tab.
+ // this.allSponsoredTiles: The original list of tiles set via setTiles prior to any filtering
+ // The returned list indicated the difference between these two lists (excluding any previously filtered tiles).
+ _getFilteredTiles(currentTiles) {
+ let notPreviouslyFilteredTiles = Object.assign(
+ {},
+ ...Object.entries(this.allSponsoredTiles)
+ .filter(
+ ([k, v]) =>
+ v.display_fail_reason === null ||
+ v.display_fail_reason === undefined
+ )
+ .map(([k, v]) => ({ [k]: v }))
+ );
+
+ // Get the property names of the newly filtered list.
+ let remainingTiles = currentTiles.map(el => {
+ return this._buildPropertyKey(el);
+ });
+
+ // Get the property names of the tiles that were filtered.
+ let tilesToUpdate = Object.keys(notPreviouslyFilteredTiles).filter(
+ element => !remainingTiles.includes(element)
+ );
+ return tilesToUpdate;
+ }
+
+ setSponsoredTilesConfigured() {
+ const maxSponsored =
+ lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_MAX_SPONSORED
+ ) ?? MAX_NUM_SPONSORED;
+
+ this.sponsoredTilesConfigured = maxSponsored;
+ Glean.topsites.sponsoredTilesConfigured.set(maxSponsored);
+ }
+
+ clearTilesForProvider(provider) {
+ Object.entries(this.allSponsoredTiles)
+ .filter(([k, v]) => k.startsWith(provider))
+ .map(([k, v]) => delete this.allSponsoredTiles[k]);
+ }
+
+ _getAdvertiser(tile) {
+ let label = tile.label || null;
+ let title = tile.title || null;
+
+ return label ?? title ?? shortURL(tile);
+ }
+
+ setTiles(tiles) {
+ // Assumption: the list of tiles is from a single provider,
+ // should be called once per tile source.
+ if (tiles && tiles.length) {
+ let tile_provider = this._tileProviderForTiles(tiles);
+ this.clearTilesForProvider(tile_provider);
+
+ for (let sponsoredTile of tiles) {
+ this.allSponsoredTiles[this._buildPropertyKey(sponsoredTile)] = {
+ advertiser: this._getAdvertiser(sponsoredTile).toLowerCase(),
+ provider: tile_provider,
+ display_position: null,
+ display_fail_reason: null,
+ };
+ }
+ }
+ }
+
+ _setDisplayFailReason(filteredTiles, reason) {
+ for (let tile of filteredTiles) {
+ if (tile in this.allSponsoredTiles) {
+ let tileToUpdate = this.allSponsoredTiles[tile];
+ tileToUpdate.display_position = null;
+ tileToUpdate.display_fail_reason = reason;
+ }
+ }
+ }
+
+ determineFilteredTilesAndSetToOversold(nonOversoldTiles) {
+ let filteredTiles = this._getFilteredTiles(nonOversoldTiles);
+ this._setDisplayFailReason(filteredTiles, DISPLAY_FAIL_REASON_OVERSOLD);
+ }
+
+ determineFilteredTilesAndSetToDismissed(nonDismissedTiles) {
+ let filteredTiles = this._getFilteredTiles(nonDismissedTiles);
+ this._setDisplayFailReason(filteredTiles, DISPLAY_FAIL_REASON_DISMISSED);
+ }
+
+ _setTilePositions(currentTiles) {
+ // This function performs many loops over a small dataset. The size of
+ // dataset is limited by the number of sponsored tiles displayed on
+ // the newtab instance.
+ if (this.allSponsoredTiles) {
+ let tilePositionsAssigned = [];
+ // processing the currentTiles parameter, assigns a position to the
+ // corresponding property in this.allSponsoredTiles
+ currentTiles.forEach(item => {
+ let tile = this.allSponsoredTiles[this._buildPropertyKey(item)];
+ if (
+ tile &&
+ (tile.display_fail_reason === undefined ||
+ tile.display_fail_reason === null)
+ ) {
+ tile.display_position = item.sponsored_position;
+ // Track assigned tile slots.
+ tilePositionsAssigned.push(item.sponsored_position);
+ }
+ });
+
+ // Need to check if any objects in this.allSponsoredTiles do not
+ // have either a display_fail_reason or a display_position set.
+ // This can happen if the tiles list was updated before the
+ // metric is written to Glean.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=1877197
+ let tilesMissingPosition = [];
+ Object.keys(this.allSponsoredTiles).forEach(property => {
+ let tile = this.allSponsoredTiles[property];
+ if (!tile.display_fail_reason && !tile.display_position) {
+ tilesMissingPosition.push(property);
+ }
+ });
+
+ if (tilesMissingPosition.length) {
+ // Determine if any available slots exist based on max number of tiles
+ // and the list of tiles already used and assign to a tile with missing
+ // value.
+ for (let i = 1; i <= this.sponsoredTilesConfigured; i++) {
+ if (!tilePositionsAssigned.includes(i)) {
+ let tileProperty = tilesMissingPosition.shift();
+ this.allSponsoredTiles[tileProperty].display_position = i;
+ }
+ }
+ }
+
+ // At this point we might still have a few unresolved states. These
+ // rows will be tagged with a display_fail_reason `unresolved`.
+ this._detectErrorConditionAndSetUnresolved();
+ }
+ }
+
+ // Checks the data for inconsistent state and updates the display_fail_reason
+ _detectErrorConditionAndSetUnresolved() {
+ Object.keys(this.allSponsoredTiles).forEach(property => {
+ let tile = this.allSponsoredTiles[property];
+ if (
+ (!tile.display_fail_reason && !tile.display_position) ||
+ (tile.display_fail_reason && tile.display_position)
+ ) {
+ tile.display_position = null;
+ tile.display_fail_reason = DISPLAY_FAIL_REASON_UNRESOLVED;
+ }
+ });
+ }
+
+ finalizeNewtabPingFields(currentTiles) {
+ this._setTilePositions(currentTiles);
+ Glean.topsites.sponsoredTilesReceived.set(
+ JSON.stringify({
+ sponsoredTilesReceived: Object.values(this.allSponsoredTiles),
+ })
+ );
+ }
+}
+
+export 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();
+ await this._topSitesFeed.allocatePositions();
+ 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) {
+ lazy.log.warn("Contile response cache control header is empty");
+ 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);
+ this._topSitesFeed._telemetryUtility.setSponsoredTilesConfigured();
+ if (now <= lastFetch + validFor) {
+ try {
+ let cachedTiles = JSON.parse(
+ Services.prefs.getStringPref(CONTILE_CACHE_PREF)
+ );
+ this._topSitesFeed._telemetryUtility.setTiles(cachedTiles);
+ cachedTiles = this._filterBlockedSponsors(cachedTiles);
+ this._topSitesFeed._telemetryUtility.determineFilteredTilesAndSetToDismissed(
+ 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 this._topSitesFeed.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);
+ this._topSitesFeed._telemetryUtility.setSponsoredTilesConfigured();
+
+ // 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) {
+ this._topSitesFeed._telemetryUtility.clearTilesForProvider(
+ SPONSORED_TILE_PARTNER_AMP
+ );
+ 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;
+ this._topSitesFeed._telemetryUtility.setTiles(tiles);
+ if (
+ useAdditionalTiles !== undefined &&
+ !useAdditionalTiles &&
+ tiles.length > maxNumFromContile
+ ) {
+ tiles.length = maxNumFromContile;
+ this._topSitesFeed._telemetryUtility.determineFilteredTilesAndSetToOversold(
+ tiles
+ );
+ }
+ tiles = this._filterBlockedSponsors(tiles);
+ this._topSitesFeed._telemetryUtility.determineFilteredTilesAndSetToDismissed(
+ tiles
+ );
+ if (tiles.length > maxNumFromContile) {
+ lazy.log.info("Remove unused links from Contile");
+ tiles.length = maxNumFromContile;
+ this._topSitesFeed._telemetryUtility.determineFilteredTilesAndSetToOversold(
+ tiles
+ );
+ }
+ 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;
+ }
+}
+
+export class TopSitesFeed {
+ constructor() {
+ this._telemetryUtility = new TopSitesTelemetry();
+ this._contile = new ContileIntegration(this);
+ this._tippyTopProvider = new TippyTopProvider();
+ ChromeUtils.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
+ );
+
+ // Keep the number of positions in the array in sync with CONTILE_MAX_NUM_SPONSORED.
+ // sponsored_position is a 1-based index, and contilePositions is a 0-based index,
+ // so we need to add 1 to each of these.
+ // Also currently this does not work with SOV.
+ let contilePositions = lazy.NimbusFeatures.pocketNewtab
+ .getVariable(NIMBUS_VARIABLE_CONTILE_POSITIONS)
+ ?.split(",")
+ .map(item => parseInt(item, 10) + 1)
+ .filter(item => !Number.isNaN(item));
+ if (!contilePositions || contilePositions.length === 0) {
+ contilePositions = [1, 2];
+ }
+
+ let hasContileTiles = false;
+ if (contileEnabled) {
+ let contilePositionIndex = 0;
+ // 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(
+ contilePositions.length,
+ this._contile.sites.length
+ );
+ // Loop until we run out of spocs or positions.
+ for (let i = 0; i < minLength; i++) {
+ let site = this._contile.sites[i];
+ let hostname = shortURL(site);
+ let link = {
+ isDefault: true,
+ url: site.url,
+ hostname,
+ sendAttributionRequest: false,
+ label: site.name,
+ show_sponsored_label: hostname !== "yandex",
+ sponsored_position: contilePositions[contilePositionIndex++],
+ 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 = contilePositionIndex > 0;
+ //This is to catch where we receive 3 tiles but reduce to 2 early in the filtering, before blocked list applied.
+ this._telemetryUtility.determineFilteredTilesAndSetToOversold(
+ DEFAULT_TOP_SITES
+ );
+ }
+
+ // 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;
+ }
+
+ /**
+ * This thin wrapper around global.fetch makes it easier for us to write
+ * automated tests that simulate responses from this fetch.
+ */
+ fetch(...args) {
+ return fetch(...args);
+ }
+
+ /**
+ * 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
+ try {
+ await Services.search.init();
+ } catch {
+ // We continue anyway because we want the user to see their sponsored,
+ // saved, or visited shortcut tiles even if search engines are not
+ // available.
+ }
+
+ // 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
+ );
+ }
+ }
+ this._telemetryUtility.determineFilteredTilesAndSetToDismissed(
+ contileSponsored
+ );
+
+ const discoverySponsored = this.fetchDiscoveryStreamSpocs();
+ this._telemetryUtility.setTiles(discoverySponsored);
+
+ const sponsored = this._mergeSponsoredLinks({
+ [SPONSORED_TILE_PARTNER_AMP]: contileSponsored,
+ [SPONSORED_TILE_PARTNER_MOZ_SALES]: discoverySponsored,
+ });
+
+ this._maybeCapSponsoredLinks(sponsored);
+
+ // This will set all extra tiles to oversold, including moz-sales.
+ this._telemetryUtility.determineFilteredTilesAndSetToOversold(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;
+
+ this._telemetryUtility.finalizeNewtabPingFields(dedupedSponsored);
+ 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.
+ */
+ _mergeSponsoredLinks(sponsoredLinks) {
+ const { positions: allocatedPositions, ready: sovReady } =
+ this.store.getState().TopSites.sov || {};
+ if (
+ !this._contile.sov ||
+ !sovReady ||
+ !lazy.NimbusFeatures.pocketNewtab.getVariable(
+ NIMBUS_VARIABLE_CONTILE_SOV_ENABLED
+ )
+ ) {
+ return Object.values(sponsoredLinks).flat();
+ }
+
+ // AMP links might have empty slots, remove them as SOV doesn't need those.
+ sponsoredLinks[SPONSORED_TILE_PARTNER_AMP] =
+ sponsoredLinks[SPONSORED_TILE_PARTNER_AMP].filter(Boolean);
+
+ let sponsored = [];
+ let chosenPartners = [];
+
+ for (const allocation of allocatedPositions) {
+ let link = null;
+ const { assignedPartner } = allocation;
+ if (assignedPartner) {
+ // Unknown partners are allowed so that new parters can be added to Shepherd
+ // sooner without waiting for client changes.
+ link = sponsoredLinks[assignedPartner]?.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 === assignedPartner ||
+ sponsoredLinks[partner].length === 0
+ ) {
+ continue;
+ }
+ link = sponsoredLinks[partner].shift();
+ break;
+ }
+
+ if (!link) {
+ // No more links to be added across all the partners, just return.
+ if (chosenPartners.length) {
+ Glean.newtab.sovAllocation.set(
+ chosenPartners.map(entry => JSON.stringify(entry))
+ );
+ }
+ 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);
+
+ chosenPartners.push({
+ pos: allocation.position,
+ assigned: assignedPartner, // The assigned partner based on SOV
+ chosen: link.partner,
+ });
+ }
+ // Record chosen partners to glean
+ if (chosenPartners.length) {
+ Glean.newtab.sovAllocation.set(
+ chosenPartners.map(entry => JSON.stringify(entry))
+ );
+ }
+
+ // 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));
+ }
+ }
+
+ // Allocate ad positions to partners based on SOV via stable randomization.
+ async allocatePositions() {
+ // If the fetch to get sov fails for whatever reason, we can just return here.
+ // Code that uses this falls back to flattening allocations instead if this has failed.
+ if (!this._contile.sov) {
+ return;
+ }
+ // This sample input should ensure we return the same result for this allocation,
+ // even if called from other parts of the code.
+ const sampleInput = `${lazy.contextId}-${this._contile.sov.name}`;
+ const allocatedPositions = [];
+ for (const allocation of this._contile.sov.allocations) {
+ const allocatedPosition = {
+ position: allocation.position,
+ };
+ allocatedPositions.push(allocatedPosition);
+ const ratios = allocation.allocation.map(alloc => alloc.percentage);
+ if (ratios.length) {
+ const index = await lazy.Sampling.ratioSample(sampleInput, ratios);
+ allocatedPosition.assignedPartner =
+ allocation.allocation[index].partner;
+ }
+ }
+
+ this.store.dispatch(
+ ac.OnlyToMain({
+ type: at.SOV_UPDATED,
+ data: {
+ ready: !!allocatedPositions.length,
+ positions: allocatedPositions,
+ },
+ })
+ );
+ }
+
+ 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;
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/TopStoriesFeed.sys.mjs b/browser/components/newtab/lib/TopStoriesFeed.sys.mjs
new file mode 100644
index 0000000000..be030649dd
--- /dev/null
+++ b/browser/components/newtab/lib/TopStoriesFeed.sys.mjs
@@ -0,0 +1,731 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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,
+ actionCreators as ac,
+} from "resource://activity-stream/common/Actions.sys.mjs";
+import { Prefs } from "resource://activity-stream/lib/ActivityStreamPrefs.sys.mjs";
+import { shortURL } from "resource://activity-stream/lib/ShortURL.sys.mjs";
+import { SectionsManager } from "resource://activity-stream/lib/SectionsManager.sys.mjs";
+import { PersistentCache } from "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",
+});
+
+export const STORIES_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
+export const TOPICS_UPDATE_TIME = 3 * 60 * 60 * 1000; // 3 hours
+const STORIES_NOW_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours
+export const DEFAULT_RECS_EXPIRE_TIME = 60 * 60 * 1000; // 1 hour
+export const SECTION_ID = "topstories";
+const IMPRESSION_SOURCE = "TOP_STORIES";
+
+export 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";
+export 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";
+
+export 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;
+ }
+ }
+}
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..1195da05fa
--- /dev/null
+++ b/browser/components/newtab/lib/cache.worker.js
@@ -0,0 +1,203 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* 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-implicit-globals, 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, no-implicit-globals
+ 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..04845fcda0
--- /dev/null
+++ b/browser/components/newtab/metrics.yaml
@@ -0,0 +1,1589 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.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
+
+ sov_allocation:
+ type: string_list
+ description: >
+ The partner group assignment for sov
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1840311
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1840311#c3
+ data_sensitivity:
+ - technical
+ 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
+
+newtab.handoff_preference:
+ enabled:
+ lifetime: application
+ type: boolean
+ description: >
+ Records whether the
+ browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar preference is
+ enabled or disabled
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1864496
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1864496
+ data_sensitivity:
+ - interaction
+ expires: 128
+ notification_emails:
+ - fx-search-telemetry@mozilla.com
+
+
+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. Like `74357`.
+ type: quantity
+ 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
+
+ show_privacy_click:
+ type: event
+ description: >
+ Recorded when the "Our Sponsors and Your Privacy" menu item in the three-
+ dots menu of a sponsored topsite is clicked.
+ Corresponds to the receipt of a dispatched `ABOUT_SPONSORED_TOP_SITES`
+ action by `TelemetryFeed`.
+ bugs:
+ - https://mozilla-hub.atlassian.net/browse/DENG-1364
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_sensitivity: [interaction]
+ notification_emails:
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - sbetancourt@mozilla.com
+ expires: never
+ extra_keys:
+ advertiser_name: *advertiser_name
+ tile_id: *tile_id
+ newtab_visit_id: *newtab_visit_id
+ position: *topsite_position
+ send_in_pings:
+ - newtab
+
+ dismiss:
+ type: event
+ description: >
+ Recorded when the "Dismiss" menu item in the three-dots menu of a topsite
+ is clicked.
+ Corresponds to the receipt of a dispatched `BLOCK_URL` action by
+ `TelemetryFeed`.
+ Applies to both sponsored and non-sponsored topsites.
+ `advertiser_name` is only provided for sponsored topsites.
+ bugs:
+ - https://mozilla-hub.atlassian.net/browse/DENG-1363
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_sensitivity: [interaction]
+ notification_emails:
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - sbetancourt@mozilla.com
+ - kdemtchouk@mozilla.com
+ - mbowerman@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
+
+ pref_changed:
+ type: event
+ description: >
+ Recorded when specific topsites prefs have changed.
+
+ The list of possible prefs is presently:
+ * browser.newtabpage.activity-stream.feeds.topsites
+ * browser.newtabpage.activity-stream.showSponsoredTopSites
+ bugs:
+ - https://mozilla-hub.atlassian.net/browse/D0-1293
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1857324
+ data_sensitivity: [interaction]
+ notification_emails:
+ - chutten@mozilla.com
+ - mmccorquodale@mozilla.com
+ - sbetancourt@mozilla.com
+ - kdemtchouk@mozilla.com
+ - mbowerman@mozilla.com
+ expires: never
+ extra_keys:
+ pref_name:
+ description: The full name of the pref whose value just changed.
+ type: string
+ new_value:
+ description: The new (current) value the pref just changed to.
+ type: boolean
+ 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
+
+ sponsored_tiles_configured:
+ lifetime: application
+ type: quantity
+ unit: integer
+ description: >
+ The number of topsite tiles configured to be shown on newtab.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862493
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - gleonard@mozilla.com
+ expires: never
+ send_in_pings:
+ - newtab
+
+ sponsored_tiles_received:
+ lifetime: application
+ type: text
+ description: >
+ The stringified JSON of tiles processed for display (array of objects).
+ Includes tiles not displayed and reason for not displaying.
+ Fields included: advertiser, provider, display_position,
+ display_fail_reason.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - gleonard@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
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ 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
+ recommendation_id: &recommendation_id
+ description: >
+ The id from the Pocket API response that returned the recommendation.
+ Like "{61934fe5-fbb0-4f4e-b9dd-7eab5f6ee9cd}".
+ type: string
+ tile_id: &pocket_tile_id
+ description: >
+ A content identifier.
+ For organic Pocket recommendations it is an opaque id produced by
+ Pocket's recommendation systems.
+ For sponsored Pocket content it is Kevel's "ad ID".
+ 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
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ 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
+ recommendation_id: *recommendation_id
+ tile_id: *pocket_tile_id
+ 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
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ 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
+ recommendation_id: *recommendation_id
+ tile_id: *pocket_tile_id
+ 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
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1786612
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1817105#c11
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1854245
+ 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
+
+ shim:
+ type: text
+ lifetime: ping
+ description: |
+ Opaque partner identifier for a given ad impression or engagement action,
+ unique per market and region.
+ Pocket
+ [proxies requests to ad partners](https://github.com/Pocket/proxy-server/)
+ and provides them solely with market, region, and action to generate these
+ shims. Thus, though the contents of this field are obscure, they cannot
+ identify clients.
+ At time of writing this information is a comma-separated trio.
+ The first item is an index into the proxy server's list of acceptable http
+ endpoints for contacting the ad service. The second item is a
+ several-hundred-byte base64-encoded JSON-encoded struct with fields for,
+ amongst other things, market and region. The third is unknown, but appears
+ to be a signature or checksum.
+ This shim should not be sent with the client_id.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_sensitivity:
+ - stored_content # Required for text type, and to encourage scrutiny
+ notification_emails:
+ - chutten@mozilla.com
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - spoc
+
+
+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
+
+ event_screen_family:
+ type: text
+ lifetime: ping
+ description: |
+ A string identifier of the message family derived from the message id
+ (e.g. MR_WELCOME_DEFAULT).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1867627
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ - nsauermann@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_screen_id:
+ type: text
+ lifetime: ping
+ description: |
+ A string identifier of the message screen id
+ (e.g. AW_MOBILE_DOWNLOAD).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1867627
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ - nsauermann@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_screen_initials:
+ type: text
+ lifetime: ping
+ description: |
+ A string identifier of the message screen initials
+ (e.g. 'EMAG' for EASY_SETUP, MOBILE_DOWNLOADS, AMO, GRATITUDE).
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1867627
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1825863
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - pmcmanis@mozilla.com
+ - dmosedale@mozilla.com
+ - nsauermann@mozilla.com
+ expires: never
+ send_in_pings:
+ - messaging-system
+
+ event_screen_index:
+ type: quantity
+ unit: integer
+ lifetime: ping
+ description: |
+ A number identifier of the screen index in a sequence of screens
+ (e.g. 0 for first message).
+ 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
+ - nsauermann@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. “IMPRESSION”, “CLICK_BUTTON”, "INDEXEDDB_OPEN_FAILED", “SESSION_END”)
+ 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
+
+ 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
+
+ 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
+
+top_sites: # Replacement for PingCentre "topsites-impression|click" pings.
+ ping_type:
+ type: string
+ description: >
+ The ping's type. In other situations might be designated by an event's
+ name or an interaction field. E.g. "topsites-impression",
+ "topsites-click".
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ position:
+ type: quantity
+ unit: topsite position
+ description: >
+ The position (1-based) of the topsites item being interatcted with.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ source:
+ type: string
+ description: >
+ The source of the interaction. Always set to "newtab".
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ tile_id:
+ type: string
+ description: >
+ String-encoded number for the tile's sponsored tile id.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - interaction
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ reporting_url:
+ type: url
+ description: >
+ The url to report this interaction to.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - web_activity
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ advertiser:
+ type: string
+ description: >
+ The name of the advertiser providing the sponsored TopSite.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - interaction
+ - web_activity
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
+
+ context_id:
+ type: uuid
+ description: >
+ An identifier to identify users for Contextual Services user interaction pings.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_sensitivity:
+ - technical
+ notification_emails:
+ - najiang@mozilla.com
+ expires: never
+ send_in_pings:
+ - top-sites
diff --git a/browser/components/newtab/moz.build b/browser/components/newtab/moz.build
new file mode 100644
index 0000000000..0d3bddb968
--- /dev/null
+++ b/browser/components/newtab/moz.build
@@ -0,0 +1,35 @@
+# -*- 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.toml",
+ "test/browser/browser.toml",
+]
+
+SPHINX_TREES["docs"] = "docs"
+
+XPCSHELL_TESTS_MANIFESTS += [
+ "test/xpcshell/xpcshell.toml",
+]
+
+XPIDL_SOURCES += [
+ "nsIAboutNewTabService.idl",
+]
+
+XPIDL_MODULE = "browser-newtab"
+
+EXTRA_JS_MODULES += [
+ "AboutNewTabService.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..7a9fead1b8
--- /dev/null
+++ b/browser/components/newtab/package-lock.json
@@ -0,0 +1,12455 @@
+{
+ "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.23.5",
+ "@babel/preset-react": "7.23.3",
+ "@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",
+ "enzyme": "3.11.0",
+ "enzyme-adapter-react-16": "1.15.6",
+ "joi-browser": "13.4.0",
+ "karma": "6.4.2",
+ "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.1",
+ "lodash": "4.17.21",
+ "mocha": "9.2.2",
+ "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",
+ "rimraf": "3.0.2",
+ "sass": "1.43.4",
+ "shelljs": "0.8.5",
+ "sinon": "12.0.1",
+ "stream-browserify": "3.0.0",
+ "util": "0.10.4",
+ "webpack": "5.89.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/@ampproject/remapping": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz",
+ "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.0",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz",
+ "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/highlight": "^7.23.4",
+ "chalk": "^2.4.2"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz",
+ "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.5.tgz",
+ "integrity": "sha512-Cwc2XjUrG4ilcfOw4wBAK+enbdgwAcAJCfGUItPBKR7Mjw4aEfAFYrLxeRp4jWgtNIKn3n2AlBOfwwafl+42/g==",
+ "dev": true,
+ "dependencies": {
+ "@ampproject/remapping": "^2.2.0",
+ "@babel/code-frame": "^7.23.5",
+ "@babel/generator": "^7.23.5",
+ "@babel/helper-compilation-targets": "^7.22.15",
+ "@babel/helper-module-transforms": "^7.23.3",
+ "@babel/helpers": "^7.23.5",
+ "@babel/parser": "^7.23.5",
+ "@babel/template": "^7.22.15",
+ "@babel/traverse": "^7.23.5",
+ "@babel/types": "^7.23.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/babel"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz",
+ "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.23.6",
+ "@jridgewell/gen-mapping": "^0.3.2",
+ "@jridgewell/trace-mapping": "^0.3.17",
+ "jsesc": "^2.5.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-annotate-as-pure": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz",
+ "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz",
+ "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/compat-data": "^7.23.5",
+ "@babel/helper-validator-option": "^7.23.5",
+ "browserslist": "^4.22.2",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-environment-visitor": {
+ "version": "7.22.20",
+ "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz",
+ "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-function-name": {
+ "version": "7.23.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz",
+ "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/template": "^7.22.15",
+ "@babel/types": "^7.23.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-hoist-variables": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz",
+ "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.22.15",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz",
+ "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.22.15"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz",
+ "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-module-imports": "^7.22.15",
+ "@babel/helper-simple-access": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/helper-validator-identifier": "^7.22.20"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz",
+ "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-simple-access": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz",
+ "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-split-export-declaration": {
+ "version": "7.22.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz",
+ "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==",
+ "dev": true,
+ "dependencies": {
+ "@babel/types": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz",
+ "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.22.20",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
+ "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz",
+ "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.23.8",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.8.tgz",
+ "integrity": "sha512-KDqYz4PiOWvDFrdHLPhKtCThtIcKVy6avWD2oG4GEvyQ+XDZwHD4YQd+H2vNMnq2rkdxsDkU82T+Vk8U/WXHRQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/template": "^7.22.15",
+ "@babel/traverse": "^7.23.7",
+ "@babel/types": "^7.23.6"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/highlight": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz",
+ "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "chalk": "^2.4.2",
+ "js-tokens": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz",
+ "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==",
+ "dev": true,
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-syntax-jsx": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.23.3.tgz",
+ "integrity": "sha512-EB2MELswq55OHUoRZLGg/zC7QWUKfNLpE57m/S2yr1uEneIgsTgrSzXP3NXEsMkVn76OlaVVnzN+ugObuYGwhg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-display-name": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.23.3.tgz",
+ "integrity": "sha512-GnvhtVfA2OAtzdX58FJxU19rhoGeQzyVndw3GgtdECQvQFXPEZIOVULHVZGAYmOgmqjXpVpfocAbSjh99V/Fqw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.23.4.tgz",
+ "integrity": "sha512-5xOpoPguCZCRbo/JeHlloSkTA8Bld1J/E1/kLfD1nsuiW1m8tduTA1ERCgIZokDflX/IBzKcqR3l7VlRgiIfHA==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.22.5",
+ "@babel/helper-module-imports": "^7.22.15",
+ "@babel/helper-plugin-utils": "^7.22.5",
+ "@babel/plugin-syntax-jsx": "^7.23.3",
+ "@babel/types": "^7.23.4"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-development": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.22.5.tgz",
+ "integrity": "sha512-bDhuzwWMuInwCYeDeMzyi7TaBgRQei6DqxhbyniL7/VG4RSS7HtSL2QbY4eESy1KJqlWt8g3xeEBGPuo+XqC8A==",
+ "dev": true,
+ "dependencies": {
+ "@babel/plugin-transform-react-jsx": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-pure-annotations": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.23.3.tgz",
+ "integrity": "sha512-qMFdSS+TUhB7Q/3HVPnEdYJDQIk57jkntAwSuz9xfSE4n+3I+vHYCli3HoHawN1Z3RfCz/y1zXA/JXjG6cVImQ==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.22.5",
+ "@babel/helper-plugin-utils": "^7.22.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/preset-react": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.23.3.tgz",
+ "integrity": "sha512-tbkHOS9axH6Ysf2OUEqoSZ6T3Fa2SrNH6WTWSPBboxKzdxNc9qOICeLXkNG0ZEwbQ1HY8liwOce4aN/Ceyuq6w==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.22.5",
+ "@babel/helper-validator-option": "^7.22.15",
+ "@babel/plugin-transform-react-display-name": "^7.23.3",
+ "@babel/plugin-transform-react-jsx": "^7.22.15",
+ "@babel/plugin-transform-react-jsx-development": "^7.22.5",
+ "@babel/plugin-transform-react-pure-annotations": "^7.23.3"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.23.8",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.8.tgz",
+ "integrity": "sha512-Y7KbAP984rn1VGMbGqKmBLio9V7y5Je9GvU4rQPCPinCyNfUcToxIXl06d59URp/F3LwinvODxab5N/G6qggkw==",
+ "dependencies": {
+ "regenerator-runtime": "^0.14.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.22.15",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz",
+ "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.22.13",
+ "@babel/parser": "^7.22.15",
+ "@babel/types": "^7.22.15"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.23.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz",
+ "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.23.5",
+ "@babel/generator": "^7.23.6",
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-function-name": "^7.23.0",
+ "@babel/helper-hoist-variables": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/parser": "^7.23.6",
+ "@babel/types": "^7.23.6",
+ "debug": "^4.3.1",
+ "globals": "^11.1.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz",
+ "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.23.4",
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "to-fast-properties": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@colors/colors": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
+ "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.1.90"
+ }
+ },
+ "node_modules/@discoveryjs/json-ext": {
+ "version": "0.5.7",
+ "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz",
+ "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==",
+ "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/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/@jridgewell/gen-mapping": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
+ "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/set-array": "^1.0.1",
+ "@jridgewell/sourcemap-codec": "^1.4.10",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz",
+ "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/set-array": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
+ "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/source-map": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz",
+ "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.0",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.4.15",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
+ "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
+ "dev": true
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.21",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz",
+ "integrity": "sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "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/convert-source-map": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
+ "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
+ "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/@sinonjs/commons": {
+ "version": "1.8.6",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.6.tgz",
+ "integrity": "sha512-Ky+XkAkqPZSm3NLBeUng77EBQl3cmeJhITaGHdYH8kjVB+aun3S4XBRti2zt17mtt0mIUDiNxYeoJm6drVvBJQ==",
+ "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.1.3",
+ "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.1.3.tgz",
+ "integrity": "sha512-nhOb2dWPeb1sd3IQXL/dVPnKHDOAFfvichtBf4xV00/rU1QbPCQqKMbvIheIjqwVjh7qIgf2AHTHi391yMOMpQ==",
+ "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.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz",
+ "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==",
+ "dev": true
+ },
+ "node_modules/@socket.io/component-emitter": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz",
+ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==",
+ "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.17",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz",
+ "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/eslint": {
+ "version": "8.56.2",
+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.2.tgz",
+ "integrity": "sha512-uQDwm1wFHmbBbCZCqAlq6Do9LYwByNZHWzXppSnay9SuwJ+VRbjkbLABer54kcPnMSlG6Fdiy2yaFXm/z9Z5gw==",
+ "dev": true,
+ "dependencies": {
+ "@types/estree": "*",
+ "@types/json-schema": "*"
+ }
+ },
+ "node_modules/@types/eslint-scope": {
+ "version": "3.7.7",
+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz",
+ "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==",
+ "dev": true,
+ "dependencies": {
+ "@types/eslint": "*",
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz",
+ "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==",
+ "dev": true
+ },
+ "node_modules/@types/hoist-non-react-statics": {
+ "version": "3.3.5",
+ "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.5.tgz",
+ "integrity": "sha512-SbcrWzkKBw2cdwRTwQAswfpB9g9LJWfjtUeW/jvNwbhC8cpmmNYVePa+ncbUe0rGTQ7G3Ff6mYUN2VMfLVr+Sg==",
+ "dependencies": {
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0"
+ }
+ },
+ "node_modules/@types/json-schema": {
+ "version": "7.0.15",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+ "dev": true
+ },
+ "node_modules/@types/node": {
+ "version": "20.11.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.0.tgz",
+ "integrity": "sha512-o9bjXmDNcF7GbM4CNQpmi+TutCgap/K3w1JyKgxAjqx41zp9qlIAVFi0IhCNsJcXolEqLWhbFbEeL0PvYm4pcQ==",
+ "dev": true,
+ "dependencies": {
+ "undici-types": "~5.26.4"
+ }
+ },
+ "node_modules/@types/prop-types": {
+ "version": "15.7.11",
+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.11.tgz",
+ "integrity": "sha512-ga8y9v9uyeiLdpKddhxYQkxNDrfvuPrlFb0N1qnZZByvcElJaXthF1UhvCh9TLWJBEHeNtdnbysW7Y6Uq8CVng=="
+ },
+ "node_modules/@types/react": {
+ "version": "18.2.47",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.2.47.tgz",
+ "integrity": "sha512-xquNkkOirwyCgoClNk85BjP+aqnIS+ckAJ8i37gAbDs14jfW/J23f2GItAf33oiUPQnqNMALiFeoM9Y5mbjpVQ==",
+ "dependencies": {
+ "@types/prop-types": "*",
+ "@types/scheduler": "*",
+ "csstype": "^3.0.2"
+ }
+ },
+ "node_modules/@types/react-redux": {
+ "version": "7.1.33",
+ "resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.33.tgz",
+ "integrity": "sha512-NF8m5AjWCkert+fosDsN3hAlHzpjSiXlVy9EgQEmLoBhaNXbmyeGs/aj5dQzKuF+/q+S7JQagorGDW8pJ28Hmg==",
+ "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.8",
+ "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.8.tgz",
+ "integrity": "sha512-WZLiwShhwLRmeV6zH+GkbOFT6Z6VklCItrDioxUnv+u4Ll+8vKeFySoFyK/0ctcRpOmwAicELfmys1sDc/Rw+A=="
+ },
+ "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.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz",
+ "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/helper-numbers": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/floating-point-hex-parser": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz",
+ "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-api-error": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz",
+ "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-buffer": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz",
+ "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-numbers": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz",
+ "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/floating-point-hex-parser": "1.11.6",
+ "@webassemblyjs/helper-api-error": "1.11.6",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webassemblyjs/helper-wasm-bytecode": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz",
+ "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/helper-wasm-section": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz",
+ "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/ieee754": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz",
+ "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==",
+ "dev": true,
+ "dependencies": {
+ "@xtuc/ieee754": "^1.2.0"
+ }
+ },
+ "node_modules/@webassemblyjs/leb128": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz",
+ "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==",
+ "dev": true,
+ "dependencies": {
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webassemblyjs/utf8": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz",
+ "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==",
+ "dev": true
+ },
+ "node_modules/@webassemblyjs/wasm-edit": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz",
+ "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/helper-wasm-section": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6",
+ "@webassemblyjs/wasm-opt": "1.11.6",
+ "@webassemblyjs/wasm-parser": "1.11.6",
+ "@webassemblyjs/wast-printer": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-gen": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz",
+ "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/ieee754": "1.11.6",
+ "@webassemblyjs/leb128": "1.11.6",
+ "@webassemblyjs/utf8": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-opt": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz",
+ "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6",
+ "@webassemblyjs/wasm-parser": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/wasm-parser": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz",
+ "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-api-error": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/ieee754": "1.11.6",
+ "@webassemblyjs/leb128": "1.11.6",
+ "@webassemblyjs/utf8": "1.11.6"
+ }
+ },
+ "node_modules/@webassemblyjs/wast-printer": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz",
+ "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==",
+ "dev": true,
+ "dependencies": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "node_modules/@webpack-cli/configtest": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz",
+ "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==",
+ "dev": true,
+ "peerDependencies": {
+ "webpack": "4.x.x || 5.x.x",
+ "webpack-cli": "4.x.x"
+ }
+ },
+ "node_modules/@webpack-cli/info": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz",
+ "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==",
+ "dev": true,
+ "dependencies": {
+ "envinfo": "^7.7.3"
+ },
+ "peerDependencies": {
+ "webpack-cli": "4.x.x"
+ }
+ },
+ "node_modules/@webpack-cli/serve": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz",
+ "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==",
+ "dev": true,
+ "peerDependencies": {
+ "webpack-cli": "4.x.x"
+ },
+ "peerDependenciesMeta": {
+ "webpack-dev-server": {
+ "optional": 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.8",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
+ "dev": true,
+ "dependencies": {
+ "mime-types": "~2.1.34",
+ "negotiator": "0.6.3"
+ },
+ "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.9.0",
+ "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz",
+ "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==",
+ "dev": true,
+ "peerDependencies": {
+ "acorn": "^8"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ },
+ "peerDependencies": {
+ "react": "^0.14 || ^15.0.0 || ^16.0.0-alpha"
+ }
+ },
+ "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/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,
+ "peerDependencies": {
+ "ajv": "^6.9.1"
+ }
+ },
+ "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-regex": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz",
+ "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "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.3",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
+ "dev": true,
+ "dependencies": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "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/array-buffer-byte-length": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.0.tgz",
+ "integrity": "sha512-LPuwb2P+NrQw3XhxGc36+XSvuBPopovXYTR9Ew++Du9Yb/bx5AzBfrIsBoj0EZUifjQU+sHL21sseZ3jerWO/A==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "is-array-buffer": "^3.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.filter": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/array.prototype.filter/-/array.prototype.filter-1.0.3.tgz",
+ "integrity": "sha512-VizNcj/RGJiUyQBgzwxzE5oHdeuXY5hSbbmKMlphj1cy1Vl7Pn2asCGbSrru6hSQjmCzqTBPVWAF/whmEOVHbw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-array-method-boxes-properly": "^1.0.0",
+ "is-string": "^1.0.7"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.find": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/array.prototype.find/-/array.prototype.find-2.2.2.tgz",
+ "integrity": "sha512-DRumkfW97iZGOfn+lIXbkVrXL04sfYKX+EfOodo8XboR5sxPDVvOjZTF/rysusa9lmhmSOeD6Vp6RKQP+eP4Tg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-shim-unscopables": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.flat": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz",
+ "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-shim-unscopables": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/arraybuffer.prototype.slice": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.2.tgz",
+ "integrity": "sha512-yMBKppFur/fbHu9/6USUe03bZ4knMYiwFBcyiaXB8Go0qNehwX6inYPzK9U0NeQvGxKthcmHcaR8P5MStSRBAw==",
+ "dev": true,
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.0",
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "get-intrinsic": "^1.2.1",
+ "is-array-buffer": "^3.0.2",
+ "is-shared-array-buffer": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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/available-typed-arrays": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz",
+ "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0",
+ "webpack": ">=2"
+ }
+ },
+ "node_modules/babel-loader/node_modules/json5": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",
+ "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
+ "dev": true,
+ "dependencies": {
+ "minimist": "^1.2.0"
+ },
+ "bin": {
+ "json5": "lib/cli.js"
+ }
+ },
+ "node_modules/babel-loader/node_modules/loader-utils": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz",
+ "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==",
+ "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-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.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true
+ },
+ "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,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "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/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/body-parser": {
+ "version": "1.20.2",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz",
+ "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==",
+ "dev": true,
+ "dependencies": {
+ "bytes": "3.1.2",
+ "content-type": "~1.0.5",
+ "debug": "2.6.9",
+ "depd": "2.0.0",
+ "destroy": "1.2.0",
+ "http-errors": "2.0.0",
+ "iconv-lite": "0.4.24",
+ "on-finished": "2.4.1",
+ "qs": "6.11.0",
+ "raw-body": "2.5.2",
+ "type-is": "~1.6.18",
+ "unpipe": "1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8",
+ "npm": "1.2.8000 || >= 1.4.16"
+ }
+ },
+ "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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ },
+ "node_modules/boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
+ "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.22.2",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.2.tgz",
+ "integrity": "sha512-0UgcrvQmBDvZHFGdYUehrCNIazki7/lUP3kkoi/r3YB2amZbFM9J43ZRkJTXBUZK4gmx56+Sqk9+Vs9mwZx9+A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "dependencies": {
+ "caniuse-lite": "^1.0.30001565",
+ "electron-to-chromium": "^1.4.601",
+ "node-releases": "^2.0.14",
+ "update-browserslist-db": "^1.0.13"
+ },
+ "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,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/buffer-from": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "dev": true
+ },
+ "node_modules/bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "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/call-bind": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz",
+ "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.2",
+ "get-intrinsic": "^1.2.1",
+ "set-function-length": "^1.1.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/camelcase": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001576",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001576.tgz",
+ "integrity": "sha512-ff5BdakGe2P3SQsMsiqmt1Lc8221NR1VzHj5jXN5vBny9A6fpze94HiVV/n7XRosOlsShJcvMv5mdnpjOGCEgg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ]
+ },
+ "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/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.3",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz",
+ "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==",
+ "dev": true,
+ "dependencies": {
+ "get-func-name": "^2.0.2"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/cheerio": {
+ "version": "1.0.0-rc.12",
+ "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz",
+ "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==",
+ "dev": true,
+ "dependencies": {
+ "cheerio-select": "^2.1.0",
+ "dom-serializer": "^2.0.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1",
+ "htmlparser2": "^8.0.1",
+ "parse5": "^7.0.0",
+ "parse5-htmlparser2-tree-adapter": "^7.0.0"
+ },
+ "engines": {
+ "node": ">= 6"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/cheerio?sponsor=1"
+ }
+ },
+ "node_modules/cheerio-select": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
+ "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
+ "dev": true,
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-select": "^5.1.0",
+ "css-what": "^6.1.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "3.5.3",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
+ "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ ],
+ "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/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/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": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "dev": true
+ },
+ "node_modules/colorette": {
+ "version": "2.0.20",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
+ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "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": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==",
+ "dev": true
+ },
+ "node_modules/concat-map": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+ "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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ },
+ "node_modules/content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true
+ },
+ "node_modules/cookie": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
+ "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==",
+ "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/cors/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "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/cross-spawn/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/cross-spawn/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/css-select": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz",
+ "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==",
+ "dev": true,
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-what": "^6.1.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "nth-check": "^2.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/css-what": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz",
+ "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
+ },
+ "node_modules/custom-event": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz",
+ "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==",
+ "dev": true
+ },
+ "node_modules/date-format": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.14.tgz",
+ "integrity": "sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==",
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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-data-property": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz",
+ "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==",
+ "dev": true,
+ "dependencies": {
+ "get-intrinsic": "^1.2.1",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/define-properties": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
+ "dev": true,
+ "dependencies": {
+ "define-data-property": "^1.0.1",
+ "has-property-descriptors": "^1.0.0",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8",
+ "npm": "1.2.8000 || >= 1.4.16"
+ }
+ },
+ "node_modules/di": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz",
+ "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==",
+ "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": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==",
+ "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": "sha512-Yra4DbvoW7/Z6LBN560ZwXMjoNOSAN2wRsKFGc4iBeso+mpIA6qj1vfdf9HpMaKAqG6wXTy+1SYEzmNpKXOSsQ==",
+ "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": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dev": true,
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ]
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dev": true,
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.1.0.tgz",
+ "integrity": "sha512-H78uMmQtI2AhgDJjWeQmHwJJ2bLPD3GMmO7Zja/ZZh84wkm+4ut+IUnUdRa8uCGX88DiVx1j6FRe1XfxEgjEZA==",
+ "dev": true,
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "dev": true
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.4.629",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.629.tgz",
+ "integrity": "sha512-5UUkr3k3CZ/k+9Sw7vaaIMyOzMC0XbPyprKI3n0tbKDqkzTDOjK4izm7DxlkueRMim6ZZQ1ja9F7hoFVplHihA==",
+ "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": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/engine.io": {
+ "version": "6.5.4",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.4.tgz",
+ "integrity": "sha512-KdVSDKhVKyOi+r5uEabrDLZw2qXStVvCsEB/LN3mw4WFi6Gx50jTyuxYVCwAAC0U46FdnzP/ScKRBTXb/NiEOg==",
+ "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.2.1",
+ "ws": "~8.11.0"
+ },
+ "engines": {
+ "node": ">=10.2.0"
+ }
+ },
+ "node_modules/engine.io-parser": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.1.tgz",
+ "integrity": "sha512-9JktcM3u18nU9N2Lz3bWeBgxVgOKpw7yhRaoxQA3FUDZzzw+9WlA6p4G4u0RixNkg14fH7EfEc/RhpurtiROTQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/enhanced-resolve": {
+ "version": "5.15.0",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz",
+ "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==",
+ "dev": true,
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/ent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz",
+ "integrity": "sha512-GHrMyVZQWvTIdDtpiEXdHZnFQKzeO09apj8Cbl4pKWy4i0Oprcq17usfDt5aO63swf0JOeMWjWQE/LzgSRuWpA==",
+ "dev": true
+ },
+ "node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/envinfo": {
+ "version": "7.11.0",
+ "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.11.0.tgz",
+ "integrity": "sha512-G9/6xF1FPbIw0TtalAMaVPpiq2aDEuKLXM314jPVAO9r2fo2a4BLqMNkmRS7O/xPPZ+COAhGIz3ETvHEV3eUcg==",
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ },
+ "peerDependencies": {
+ "enzyme": "^3.0.0",
+ "react": "^16.0.0-0",
+ "react-dom": "^16.0.0-0"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "react": "^16.14.0"
+ }
+ },
+ "node_modules/enzyme-adapter-react-16/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/enzyme-adapter-utils": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-utils/-/enzyme-adapter-utils-1.14.1.tgz",
+ "integrity": "sha512-JZgMPF1QOI7IzBj24EZoDpaeG/p8Os7WeBZWTJydpsH7JRStc7jYbHE4CmNQaLqazaGFyLM8ALWA3IIZvxW3PQ==",
+ "dev": true,
+ "dependencies": {
+ "airbnb-prop-types": "^2.16.0",
+ "function.prototype.name": "^1.1.5",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.4",
+ "object.fromentries": "^2.0.5",
+ "prop-types": "^15.8.1",
+ "semver": "^5.7.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ },
+ "peerDependencies": {
+ "react": "0.13.x || 0.14.x || ^15.0.0-0 || ^16.0.0-0"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/prop-types": {
+ "version": "15.8.1",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "dev": true,
+ "dependencies": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.13.1"
+ }
+ },
+ "node_modules/enzyme-adapter-utils/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/enzyme-shallow-equal": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/enzyme-shallow-equal/-/enzyme-shallow-equal-1.0.5.tgz",
+ "integrity": "sha512-i6cwm7hN630JXenxxJFBKzgLC3hMTafFQXflvzHgPmDhOBhxUWDe8AeRv1qp2/uWJ2Y8z5yLWMzmAfkTOiOCZg==",
+ "dev": true,
+ "dependencies": {
+ "has": "^1.0.3",
+ "object-is": "^1.1.5"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.22.3",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.22.3.tgz",
+ "integrity": "sha512-eiiY8HQeYfYH2Con2berK+To6GrK2RxbPawDkGq4UiCQQfZHb6wX9qQqkbpPqaxQFcl8d9QzZqo0tGE0VcrdwA==",
+ "dev": true,
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.0",
+ "arraybuffer.prototype.slice": "^1.0.2",
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.5",
+ "es-set-tostringtag": "^2.0.1",
+ "es-to-primitive": "^1.2.1",
+ "function.prototype.name": "^1.1.6",
+ "get-intrinsic": "^1.2.2",
+ "get-symbol-description": "^1.0.0",
+ "globalthis": "^1.0.3",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0",
+ "has-proto": "^1.0.1",
+ "has-symbols": "^1.0.3",
+ "hasown": "^2.0.0",
+ "internal-slot": "^1.0.5",
+ "is-array-buffer": "^3.0.2",
+ "is-callable": "^1.2.7",
+ "is-negative-zero": "^2.0.2",
+ "is-regex": "^1.1.4",
+ "is-shared-array-buffer": "^1.0.2",
+ "is-string": "^1.0.7",
+ "is-typed-array": "^1.1.12",
+ "is-weakref": "^1.0.2",
+ "object-inspect": "^1.13.1",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.4",
+ "regexp.prototype.flags": "^1.5.1",
+ "safe-array-concat": "^1.0.1",
+ "safe-regex-test": "^1.0.0",
+ "string.prototype.trim": "^1.2.8",
+ "string.prototype.trimend": "^1.0.7",
+ "string.prototype.trimstart": "^1.0.7",
+ "typed-array-buffer": "^1.0.0",
+ "typed-array-byte-length": "^1.0.0",
+ "typed-array-byte-offset": "^1.0.0",
+ "typed-array-length": "^1.0.4",
+ "unbox-primitive": "^1.0.2",
+ "which-typed-array": "^1.1.13"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/es-array-method-boxes-properly": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz",
+ "integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==",
+ "dev": true
+ },
+ "node_modules/es-module-lexer": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.4.1.tgz",
+ "integrity": "sha512-cXLGjP0c4T3flZJKQSuziYoq7MlT+rnvfZjfp7h+I7K9BNX54kP9nyWvdbwjQ4u1iWbOL4u96fgeZLToQlZC7w==",
+ "dev": true
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.2.tgz",
+ "integrity": "sha512-BuDyupZt65P9D2D2vA/zqcI3G5xRsklm5N3xCwuiy+/vKy8i0ifdsQP1sLgO4tZDSCaQUSnmC48khknGMV3D2Q==",
+ "dev": true,
+ "dependencies": {
+ "get-intrinsic": "^1.2.2",
+ "has-tostringtag": "^1.0.0",
+ "hasown": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-shim-unscopables": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz",
+ "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==",
+ "dev": true,
+ "dependencies": {
+ "hasown": "^2.0.0"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "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": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "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/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/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"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/execa?sponsor=1"
+ }
+ },
+ "node_modules/execa/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/execa/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/execa/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/execa/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/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/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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ },
+ "node_modules/finalhandler/node_modules/on-finished": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
+ "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==",
+ "dev": true,
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/avajs/find-cache-dir?sponsor=1"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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": "3.2.9",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz",
+ "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==",
+ "dev": true
+ },
+ "node_modules/follow-redirects": {
+ "version": "1.15.5",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
+ "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/for-each": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
+ "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==",
+ "dev": true,
+ "dependencies": {
+ "is-callable": "^1.1.3"
+ }
+ },
+ "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/fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
+ "dev": true
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/function.prototype.name": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz",
+ "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "functions-have-names": "^1.2.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/functions-have-names": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",
+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.2",
+ "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz",
+ "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==",
+ "dev": true,
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz",
+ "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.2",
+ "has-proto": "^1.0.1",
+ "has-symbols": "^1.0.3",
+ "hasown": "^2.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/get-symbol-description": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz",
+ "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/glob": {
+ "version": "7.2.3",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
+ "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
+ "dev": true,
+ "dependencies": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.1.1",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "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/globalthis": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.3.tgz",
+ "integrity": "sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA==",
+ "dev": true,
+ "dependencies": {
+ "define-properties": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz",
+ "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==",
+ "dev": true,
+ "dependencies": {
+ "get-intrinsic": "^1.1.3"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
+ "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/has-bigints": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz",
+ "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/has-property-descriptors": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz",
+ "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==",
+ "dev": true,
+ "dependencies": {
+ "get-intrinsic": "^1.2.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz",
+ "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
+ "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz",
+ "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==",
+ "dev": true,
+ "dependencies": {
+ "has-symbols": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz",
+ "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==",
+ "dev": true,
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "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.3.1",
+ "resolved": "https://registry.npmjs.org/html-element-map/-/html-element-map-1.3.1.tgz",
+ "integrity": "sha512-6XMlxrAFX4UEEGxctfFnmrFaaZFNf9i5fNuV5wZ3WWQ4FVaNP1aX1LkX9j2mfEx1NpjeE/rL3nmgEn23GdFmrg==",
+ "dev": true,
+ "dependencies": {
+ "array.prototype.filter": "^1.0.0",
+ "call-bind": "^1.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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": "8.0.2",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
+ "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",
+ "dev": true,
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1",
+ "entities": "^4.4.0"
+ }
+ },
+ "node_modules/http-errors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
+ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
+ "dev": true,
+ "dependencies": {
+ "depd": "2.0.0",
+ "inherits": "2.0.4",
+ "setprototypeof": "1.2.0",
+ "statuses": "2.0.1",
+ "toidentifier": "1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/http-errors/node_modules/statuses": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
+ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "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,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "node_modules/import-local": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz",
+ "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==",
+ "dev": true,
+ "dependencies": {
+ "pkg-dir": "^4.2.0",
+ "resolve-cwd": "^3.0.0"
+ },
+ "bin": {
+ "import-local-fixture": "fixtures/cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
+ "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/internal-slot": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.6.tgz",
+ "integrity": "sha512-Xj6dv+PsbtwyPpEflsejS+oIZxmMlV44zAhG479uYu89MsjcYOhCFnNyKrkJrihbsiasQyY0afoCl/9BLR65bg==",
+ "dev": true,
+ "dependencies": {
+ "get-intrinsic": "^1.2.2",
+ "hasown": "^2.0.0",
+ "side-channel": "^1.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/interpret": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz",
+ "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-array-buffer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.2.tgz",
+ "integrity": "sha512-y+FyyR/w8vfIRq4eQcM1EYgSTnmHXPqaF+IgzgraytCFq5Xh8lllDVmAZolPJiZttZLeFSINPYMaEJ7/vWUa1w==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.0",
+ "is-typed-array": "^1.1.10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
+ "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
+ "dev": true
+ },
+ "node_modules/is-bigint": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz",
+ "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==",
+ "dev": true,
+ "dependencies": {
+ "has-bigints": "^1.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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/is-boolean-object": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz",
+ "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-callable": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-core-module": {
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz",
+ "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==",
+ "dev": true,
+ "dependencies": {
+ "hasown": "^2.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-date-object": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz",
+ "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==",
+ "dev": true,
+ "dependencies": {
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "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/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.2",
+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz",
+ "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.7",
+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz",
+ "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==",
+ "dev": true,
+ "dependencies": {
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.1.4",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz",
+ "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-shared-array-buffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz",
+ "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-string": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz",
+ "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==",
+ "dev": true,
+ "dependencies": {
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-subset": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-subset/-/is-subset-0.1.1.tgz",
+ "integrity": "sha512-6Ybun0IkarhmEqxXCNw/C0bna6Zb/TkfUX9UbwJtK6ObwAVCxmAP308WWTHviM/zAqXk05cdhYsUsZeGQh99iw==",
+ "dev": true
+ },
+ "node_modules/is-symbol": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz",
+ "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==",
+ "dev": true,
+ "dependencies": {
+ "has-symbols": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-typed-array": {
+ "version": "1.1.12",
+ "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.12.tgz",
+ "integrity": "sha512-Z14TF2JNG8Lss5/HMqt0//T9JeHXttXy5pH/DBU4vi98ozO2btxzq9MwYDZYnKwU8nRsz/+GVFVRDq3DkVuSPg==",
+ "dev": true,
+ "dependencies": {
+ "which-typed-array": "^1.1.11"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-weakref": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz",
+ "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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/isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true
+ },
+ "node_modules/isbinaryfile": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
+ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/gjtorikian/"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true
+ },
+ "node_modules/isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/istanbul-lib-coverage": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
+ "dev": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "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/istanbul-lib-report": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
+ "dev": true,
+ "dependencies": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^4.0.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "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/lru-cache": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
+ "dev": true,
+ "dependencies": {
+ "yallist": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/make-dir": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
+ "dev": true,
+ "dependencies": {
+ "semver": "^7.5.3"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/istanbul-lib-report/node_modules/semver": {
+ "version": "7.5.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
+ "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
+ "dev": true,
+ "dependencies": {
+ "lru-cache": "^6.0.0"
+ },
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "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-report/node_modules/yallist": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
+ "dev": true
+ },
+ "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/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/istanbul-lib-source-maps/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/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/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/istanbul-reports": {
+ "version": "3.1.6",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz",
+ "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==",
+ "dev": true,
+ "dependencies": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/jest-worker": {
+ "version": "27.5.1",
+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
+ "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/supports-color?sponsor=1"
+ }
+ },
+ "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/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/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/json-parse-even-better-errors": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
+ "dev": true
+ },
+ "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/json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true,
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
+ "dev": true,
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/just-extend": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz",
+ "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==",
+ "dev": true
+ },
+ "node_modules/karma": {
+ "version": "6.4.2",
+ "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.2.tgz",
+ "integrity": "sha512-C6SU/53LB31BEgRg+omznBEMY4SjHU3ricV6zBcAe1EeILKkeScr+fZXtaI5WyDbkVowJxxAI6h73NcFPmXolQ==",
+ "dev": true,
+ "dependencies": {
+ "@colors/colors": "1.5.0",
+ "body-parser": "^1.19.0",
+ "braces": "^3.0.2",
+ "chokidar": "^3.5.1",
+ "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.4.1",
+ "mime": "^2.5.2",
+ "minimatch": "^3.0.4",
+ "mkdirp": "^0.5.5",
+ "qjobs": "^1.2.0",
+ "range-parser": "^1.2.1",
+ "rimraf": "^3.0.2",
+ "socket.io": "^4.4.1",
+ "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": "sha512-mqKCkHwzPMhgTYca10S90aCEX9+HjVjjrBFAsw36Zj7BlQNbokXXCAe6Ji04VUMsxcY5RLP7YphpfO06XOubdg==",
+ "dev": true,
+ "peerDependencies": {
+ "chai": "*",
+ "karma": ">=0.10.9"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mattlewis92"
+ }
+ },
+ "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-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,
+ "peerDependencies": {
+ "karma": ">=0.9"
+ }
+ },
+ "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": "sha512-Hr6nhkIp0GIJJrvzY8JFeHpQZNseuIakGac4bpw8K1+5F0tLb6l7uvXRa8mt2Z+NVwYgCct4QAfp2R2QP6o00w==",
+ "dev": true,
+ "dependencies": {
+ "chalk": "^2.1.0",
+ "log-symbols": "^2.1.0",
+ "strip-ansi": "^4.0.0"
+ },
+ "peerDependencies": {
+ "karma": ">=0.13"
+ }
+ },
+ "node_modules/karma-sinon": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/karma-sinon/-/karma-sinon-1.0.5.tgz",
+ "integrity": "sha512-wrkyAxJmJbn75Dqy17L/8aILJWFm7znd1CE8gkyxTBFnjMSOe2XTJ3P30T8SkxWZHmoHX0SCaUJTDBEoXs25Og==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.10.0"
+ },
+ "peerDependencies": {
+ "karma": ">=0.10",
+ "sinon": "*"
+ }
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "webpack": "^5.0.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/load-json-file": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
+ "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==",
+ "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/loader-runner": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz",
+ "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.11.5"
+ }
+ },
+ "node_modules/loader-utils": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.1.tgz",
+ "integrity": "sha512-ZvFw1KWS3GVyYBYb7qkmRM/WwL2TQQBxgCK62rlvm4WpVQ23Nb4tYjApUlfjrEGvOs7KHEsmyUn75OHZrJMWPw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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": "sha512-nXEOnb/jK9g0DYMr1/Xvq6l5xMD7GDG55+GSYIYmS0G4tBk/hURD4JR9WCavs04t33WmJx9kCyp9vJ+mr4BOUw==",
+ "dev": true
+ },
+ "node_modules/lodash.flattendeep": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz",
+ "integrity": "sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==",
+ "dev": true
+ },
+ "node_modules/lodash.get": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
+ "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==",
+ "dev": true
+ },
+ "node_modules/lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "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.9.1",
+ "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.9.1.tgz",
+ "integrity": "sha512-1somDdy9sChrr9/f4UlzhdaGfDR2c/SaD2a4T7qEkG4jTS57/B3qmnjLYePwQ8cqWnUHZI0iAKxMBpCZICiZ2g==",
+ "dev": true,
+ "dependencies": {
+ "date-format": "^4.0.14",
+ "debug": "^4.3.4",
+ "flatted": "^3.2.7",
+ "rfdc": "^1.3.0",
+ "streamroller": "^3.1.5"
+ },
+ "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/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+ "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": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==",
+ "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-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.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dev": true,
+ "dependencies": {
+ "mime-db": "1.52.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.1.2",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "dev": true,
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "dev": true,
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
+ }
+ },
+ "node_modules/mocha": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.2.tgz",
+ "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==",
+ "dev": true,
+ "dependencies": {
+ "@ungap/promise-all-settled": "1.1.2",
+ "ansi-colors": "4.1.1",
+ "browser-stdout": "1.3.1",
+ "chokidar": "3.5.3",
+ "debug": "4.3.3",
+ "diff": "5.0.0",
+ "escape-string-regexp": "4.0.0",
+ "find-up": "5.0.0",
+ "glob": "7.2.0",
+ "growl": "1.10.5",
+ "he": "1.2.0",
+ "js-yaml": "4.1.0",
+ "log-symbols": "4.1.0",
+ "minimatch": "4.2.1",
+ "ms": "2.1.3",
+ "nanoid": "3.3.1",
+ "serialize-javascript": "6.0.0",
+ "strip-json-comments": "3.1.1",
+ "supports-color": "8.1.1",
+ "which": "2.0.2",
+ "workerpool": "6.2.0",
+ "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"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/mochajs"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "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.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
+ "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
+ "dev": true,
+ "dependencies": {
+ "ms": "2.1.2"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mocha/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": "*"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/mocha/node_modules/glob/node_modules/minimatch": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "dev": true,
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "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/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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mocha/node_modules/minimatch": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-4.2.1.tgz",
+ "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==",
+ "dev": true,
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "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/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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/supports-color?sponsor=1"
+ }
+ },
+ "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/moo": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz",
+ "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==",
+ "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.3.1",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz",
+ "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==",
+ "dev": true,
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/nearley": {
+ "version": "2.20.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",
+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",
+ "dev": true,
+ "dependencies": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6"
+ },
+ "bin": {
+ "nearley-railroad": "bin/nearley-railroad.js",
+ "nearley-test": "bin/nearley-test.js",
+ "nearley-unparse": "bin/nearley-unparse.js",
+ "nearleyc": "bin/nearleyc.js"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://nearley.js.org/#give-to-nearley"
+ }
+ },
+ "node_modules/negotiator": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
+ "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.7",
+ "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.7.tgz",
+ "integrity": "sha512-wWtNUhkT7k58uvWTB/Gy26eA/EJKtPZFVAhEilN5UYVmmGRYOURbejRUyKm0Uu9XVEW7K5nBOZfR8VMB4QR2RQ==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^3.0.0",
+ "@sinonjs/fake-timers": "^11.2.2",
+ "@sinonjs/text-encoding": "^0.7.2",
+ "just-extend": "^6.2.0",
+ "path-to-regexp": "^6.2.1"
+ }
+ },
+ "node_modules/nise/node_modules/@sinonjs/commons": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz",
+ "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==",
+ "dev": true,
+ "dependencies": {
+ "type-detect": "4.0.8"
+ }
+ },
+ "node_modules/nise/node_modules/@sinonjs/fake-timers": {
+ "version": "11.2.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz",
+ "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==",
+ "dev": true,
+ "dependencies": {
+ "@sinonjs/commons": "^3.0.0"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.14",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz",
+ "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
+ "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-package-data/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "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-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": "2.1.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
+ "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
+ "dev": true,
+ "dependencies": {
+ "boolbase": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz",
+ "integrity": "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.1",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz",
+ "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object-is": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz",
+ "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.5",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz",
+ "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.5",
+ "define-properties": "^1.2.1",
+ "has-symbols": "^1.0.3",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object.entries": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.7.tgz",
+ "integrity": "sha512-jCBs/0plmPsOnrKAfFQXRG2NFjlhZgjjcBLSmTnEhU8U6vVTsVe8ANeQJCHTl3gSsI4J+0emOoCgoKlmQPMgmA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.7.tgz",
+ "integrity": "sha512-UPbPHML6sL8PI/mOqPwsH4G6iyXcCGzLin8KvEPenOZN5lpCNBZZQ+V62vdjB1mQHrmqGQt5/OJzemUA+KJmEA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object.values": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.7.tgz",
+ "integrity": "sha512-aU6xnDFYT3x17e/f0IiiwlGPTy2jzMySGfUB4fq6z7CV8l85CWHDk5ErhyhpfDHhrOMwGFhSQkhMGHaIotA6Ng==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "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": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "dev": true,
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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/parse-json": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz",
+ "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==",
+ "dev": true,
+ "dependencies": {
+ "error-ex": "^1.3.1",
+ "json-parse-better-errors": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/parse5": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz",
+ "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==",
+ "dev": true,
+ "dependencies": {
+ "entities": "^4.4.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5-htmlparser2-tree-adapter": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz",
+ "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==",
+ "dev": true,
+ "dependencies": {
+ "domhandler": "^5.0.2",
+ "parse5": "^7.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "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": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
+ "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": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==",
+ "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": "6.2.1",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.1.tgz",
+ "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==",
+ "dev": true
+ },
+ "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/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": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
+ "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.1",
+ "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.1.tgz",
+ "integrity": "sha512-qQbW94hLHEqCg7nhby4yRC7G2+jYHY4Rguc2bjw7Uug4GIJuu1tvf2uHaZv5Q8zdt+WKJ6qK1FOI6amaWUo5FA==",
+ "dev": true,
+ "bin": {
+ "pidtree": "bin/pidtree.js"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/pify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz",
+ "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "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/pkg-dir/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/pkg-dir/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/pkg-dir/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/pkg-dir/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/postcss": {
+ "version": "8.4.33",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.33.tgz",
+ "integrity": "sha512-Kkpbhhdjw2qQs2O2DGX+8m5OVqEcbB9HRBvuYM9pgrjEFUg30A9LmXNlTAUj4S9kgtGyrMbTzVjH7E+s5Re2yg==",
+ "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.7",
+ "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.7",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz",
+ "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==",
+ "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/prop-types/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "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.11.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
+ "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
+ "dev": true,
+ "dependencies": {
+ "side-channel": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==",
+ "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.5.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
+ "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
+ "dev": true,
+ "dependencies": {
+ "bytes": "3.1.2",
+ "http-errors": "2.0.0",
+ "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"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ },
+ "peerDependencies": {
+ "webpack": "^4.0.0 || ^5.0.0"
+ }
+ },
+ "node_modules/raw-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/raw-loader/node_modules/schema-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "react": "^16.13.1"
+ }
+ },
+ "node_modules/react-dom/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "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=="
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "react": "^16.8.3 || ^17"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ },
+ "react-native": {
+ "optional": true
+ }
+ }
+ },
+ "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-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"
+ },
+ "peerDependencies": {
+ "react": ">=16.6.0",
+ "react-dom": ">=16.6.0"
+ }
+ },
+ "node_modules/react/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/read-pkg": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz",
+ "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==",
+ "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/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "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/rechoir": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz",
+ "integrity": "sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==",
+ "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": "sha512-qOLsBKHCpSOFKK1NUOCGC5VyeufB6lEsFe92AL2bhIJsacZS1qdoOZSbPk3MYKuT2cFlRDnulKXuuElIrMjGUg==",
+ "dev": true
+ },
+ "node_modules/regenerator-runtime": {
+ "version": "0.14.1",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
+ "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw=="
+ },
+ "node_modules/regexp.prototype.flags": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.1.tgz",
+ "integrity": "sha512-sy6TXMN+hnP/wMy+ISxg3krXx7BAtWVO4UouuCN/ziM9UEne0euamVNafDfvC83bRNr95y0V5iijeDQFUNpvrg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "set-function-name": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "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": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
+ "dev": true
+ },
+ "node_modules/resolve": {
+ "version": "1.22.8",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz",
+ "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==",
+ "dev": true,
+ "dependencies": {
+ "is-core-module": "^2.13.0",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ },
+ "bin": {
+ "resolve": "bin/resolve"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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-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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "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": "sha512-nDG1rZeP6oFTLN6yNDV/uiAvs1+FS/KlrEwh7+y7dpuApDBy6bI2HTBcc0/V8lv9OTqfyD34eF7au2pm8aBbhA==",
+ "dev": true,
+ "dependencies": {
+ "lodash.flattendeep": "^4.4.0",
+ "nearley": "^2.7.10"
+ }
+ },
+ "node_modules/safe-array-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.1.tgz",
+ "integrity": "sha512-6XbUAseYE2KtOuGueyeobCySj9L4+66Tn6KQMOPQJrAJEowYKW/YR/MGJZl7FdydUdaFu4LYyDZjxf4/Nmo23Q==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.1",
+ "has-symbols": "^1.0.3",
+ "isarray": "^2.0.5"
+ },
+ "engines": {
+ "node": ">=0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "node_modules/safe-regex-test": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.2.tgz",
+ "integrity": "sha512-83S9w6eFq12BBIJYvjMux6/dkirb8+4zJRA9cxNBVb7Wq5fJBW+Xze48WqR8pxua7bDuAaaAxtVVd4Idjp1dBQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.5",
+ "get-intrinsic": "^1.2.2",
+ "is-regex": "^1.1.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.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/scheduler/node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "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/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "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/set-function-length": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.1.1.tgz",
+ "integrity": "sha512-VoaqjbBJKiWtg4yRcKBQ7g7wnGnLV3M8oLvVWwOk2PdYY6PEFegR1vezXR0tw6fZGF9csVakIRjrJiy2veSBFQ==",
+ "dev": true,
+ "dependencies": {
+ "define-data-property": "^1.1.1",
+ "get-intrinsic": "^1.2.1",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/set-function-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.1.tgz",
+ "integrity": "sha512-tMNCiqYVkXIZgc2Hnoy2IvC/f8ezc5koaRFkCjrpWzGpCd3qbZXPzVy9MAZzK1ch/X0jvSkojys3oqJN0qCmdA==",
+ "dev": true,
+ "dependencies": {
+ "define-data-property": "^1.0.1",
+ "functions-have-names": "^1.2.3",
+ "has-property-descriptors": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "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": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==",
+ "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": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/shell-quote": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz",
+ "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==",
+ "dev": true,
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/shelljs": {
+ "version": "0.8.5",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.5.tgz",
+ "integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==",
+ "dev": true,
+ "dependencies": {
+ "glob": "^7.0.0",
+ "interpret": "^1.0.0",
+ "rechoir": "^0.6.2"
+ },
+ "bin": {
+ "shjs": "bin/shjs"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/side-channel": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
+ "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.0",
+ "get-intrinsic": "^1.0.2",
+ "object-inspect": "^1.9.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/signal-exit": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
+ "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==",
+ "deprecated": "16.1.1",
+ "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"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/sinon"
+ }
+ },
+ "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.7.4",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.4.tgz",
+ "integrity": "sha512-DcotgfP1Zg9iP/dH9zvAQcWrE0TtbMVwXmlV4T4mqsvY+gw+LqUGPfx2AoVyRk0FLME+GQhufDMyacFmw7ksqw==",
+ "dev": true,
+ "dependencies": {
+ "accepts": "~1.3.4",
+ "base64id": "~2.0.0",
+ "cors": "~2.8.5",
+ "debug": "~4.3.2",
+ "engine.io": "~6.5.2",
+ "socket.io-adapter": "~2.5.2",
+ "socket.io-parser": "~4.2.4"
+ },
+ "engines": {
+ "node": ">=10.2.0"
+ }
+ },
+ "node_modules/socket.io-adapter": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz",
+ "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==",
+ "dev": true,
+ "dependencies": {
+ "ws": "~8.11.0"
+ }
+ },
+ "node_modules/socket.io-parser": {
+ "version": "4.2.4",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
+ "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
+ "dev": true,
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.3.1"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "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/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/spdx-correct": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz",
+ "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==",
+ "dev": true,
+ "dependencies": {
+ "spdx-expression-parse": "^3.0.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "node_modules/spdx-exceptions": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz",
+ "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==",
+ "dev": true
+ },
+ "node_modules/spdx-expression-parse": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz",
+ "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==",
+ "dev": true,
+ "dependencies": {
+ "spdx-exceptions": "^2.1.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "node_modules/spdx-license-ids": {
+ "version": "3.0.16",
+ "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.16.tgz",
+ "integrity": "sha512-eWN+LnM3GR6gPu35WxNgbGl8rmY1AEmoMDvL/QD6zYmPWgywxWqJWNdLGT+ke8dKNWrcYgYjPpG5gbTfghP8rw==",
+ "dev": true
+ },
+ "node_modules/sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
+ "dev": true
+ },
+ "node_modules/statuses": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
+ "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==",
+ "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/streamroller": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.1.5.tgz",
+ "integrity": "sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==",
+ "dev": true,
+ "dependencies": {
+ "date-format": "^4.0.14",
+ "debug": "^4.3.4",
+ "fs-extra": "^8.1.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "dev": true,
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "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/string-width/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/string-width/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/string.prototype.padend": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.1.5.tgz",
+ "integrity": "sha512-DOB27b/2UTTD+4myKUFh+/fXWcu/UDyASIXfg+7VzoCNNGOfWvoyU/x5pvVHr++ztyt/oSYI1BcWBBG/hmlNjA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trim": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.8.tgz",
+ "integrity": "sha512-lfjY4HcixfQXOfaqCvcBuOIapyaroTXhbkfJN3gcB1OtyupngWK4sEET9Knd0cXd28kTUqu/kHoV4HKSJdnjiQ==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimend": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.7.tgz",
+ "integrity": "sha512-Ni79DqeB72ZFq1uH/L6zJ+DKZTkOtPIHovb3YZHQViE+HDouuU4mBrLOLDn5Dde3RF8qw5qVETEjhu9locMLvA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimstart": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.7.tgz",
+ "integrity": "sha512-NGhtDFu3jCEm7B4Fy0DpLewdJQOZcQ0rGbwQ/+stjnrp2i+rlKeCvos9hOIeCmqwratM47OBxY7uFZzjxHXmrg==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
+ "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/strip-bom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
+ "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "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/supports-preserve-symlinks-flag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "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.26.0",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.26.0.tgz",
+ "integrity": "sha512-dytTGoE2oHgbNV9nTzgBEPaqAWvcJNl66VZ0BkJqlvp71IjO8CxdBx/ykCNb47cLnCmCvRZ6ZR0tLkqvZCdVBQ==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/source-map": "^0.3.3",
+ "acorn": "^8.8.2",
+ "commander": "^2.20.0",
+ "source-map-support": "~0.5.20"
+ },
+ "bin": {
+ "terser": "bin/terser"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/terser-webpack-plugin": {
+ "version": "5.3.10",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.10.tgz",
+ "integrity": "sha512-BKFPWlPDndPs+NGGCr1U59t0XScL5317Y0UReNrHaw9/FwhPENlq6bfgs+4yPfyP51vqC1bQ4rp1EfXW5ZSH9w==",
+ "dev": true,
+ "dependencies": {
+ "@jridgewell/trace-mapping": "^0.3.20",
+ "jest-worker": "^27.4.5",
+ "schema-utils": "^3.1.1",
+ "serialize-javascript": "^6.0.1",
+ "terser": "^5.26.0"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ },
+ "peerDependencies": {
+ "webpack": "^5.1.0"
+ },
+ "peerDependenciesMeta": {
+ "@swc/core": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "uglify-js": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/terser-webpack-plugin/node_modules/schema-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
+ "node_modules/terser-webpack-plugin/node_modules/serialize-javascript": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
+ "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
+ "dev": true,
+ "dependencies": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "node_modules/terser/node_modules/acorn": {
+ "version": "8.11.3",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
+ "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
+ "dev": true,
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "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": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "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/toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "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/typed-array-buffer": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.0.tgz",
+ "integrity": "sha512-Y8KTSIglk9OZEr8zywiIHG/kmQ7KWyjseXs1CbSo8vC42w7hg2HgYTxSWwP0+is7bWDc1H+Fo026CpHFwm8tkw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.1",
+ "is-typed-array": "^1.1.10"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/typed-array-byte-length": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.0.tgz",
+ "integrity": "sha512-Or/+kvLxNpeQ9DtSydonMxCx+9ZXOswtwJn17SNLvhptaXYDJvkFFP5zbfU/uLmvnBJlI4yrnXRxpdWH/M5tNA==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "has-proto": "^1.0.1",
+ "is-typed-array": "^1.1.10"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-byte-offset": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.0.tgz",
+ "integrity": "sha512-RD97prjEt9EL8YgAgpOkf3O4IF9lhJFr9g0htQkm0rchFp/Vx7LW5Q8fSXXub7BXAODyUQohRMyOc3faCPd0hg==",
+ "dev": true,
+ "dependencies": {
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "has-proto": "^1.0.1",
+ "is-typed-array": "^1.1.10"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-length": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.4.tgz",
+ "integrity": "sha512-KjZypGq+I/H7HI5HlOoGHkWUUGq+Q0TPhQurLbyrVrvnKTBgzLhIJ7j6J/XTQOi0d1RjyZ0wdas8bKs2p0x3Ng==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "is-typed-array": "^1.1.9"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/ua-parser-js": {
+ "version": "0.7.37",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.37.tgz",
+ "integrity": "sha512-xV8kqRKM+jhMvcHWUKthV9fNebIzrNy//2O9ZwWcfiBFR5f25XVZPLlEajk/sf3Ra15V92isyQqnIEXRDaZWEA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ua-parser-js"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/faisalman"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/faisalman"
+ }
+ ],
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/unbox-primitive": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz",
+ "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "has-bigints": "^1.0.2",
+ "has-symbols": "^1.0.3",
+ "which-boxed-primitive": "^1.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "5.26.5",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
+ "dev": true
+ },
+ "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": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "dev": true,
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz",
+ "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "dependencies": {
+ "escalade": "^3.1.1",
+ "picocolors": "^1.0.0"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "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": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "dev": true
+ },
+ "node_modules/util/node_modules/inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==",
+ "dev": true
+ },
+ "node_modules/utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
+ "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": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "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": "sha512-qZKX4RnBzH2ugr8Lxa7x+0V6XD9Sb/ouARtiasEQCHB1EVU4NXtmHsDDrx1dO4ne5fc3J6EW05BP1Dl0z0iung==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/watchpack": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz",
+ "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==",
+ "dev": true,
+ "dependencies": {
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.1.2"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack": {
+ "version": "5.89.0",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.89.0.tgz",
+ "integrity": "sha512-qyfIC10pOr70V+jkmud8tMfajraGCZMBWJtrmuBymQKCrLTRejBI8STDp1MCyZu/QTdZSeacCQYpYNQVOzX5kw==",
+ "dev": true,
+ "dependencies": {
+ "@types/eslint-scope": "^3.7.3",
+ "@types/estree": "^1.0.0",
+ "@webassemblyjs/ast": "^1.11.5",
+ "@webassemblyjs/wasm-edit": "^1.11.5",
+ "@webassemblyjs/wasm-parser": "^1.11.5",
+ "acorn": "^8.7.1",
+ "acorn-import-assertions": "^1.9.0",
+ "browserslist": "^4.14.5",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^5.15.0",
+ "es-module-lexer": "^1.2.1",
+ "eslint-scope": "5.1.1",
+ "events": "^3.2.0",
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.2.9",
+ "json-parse-even-better-errors": "^2.3.1",
+ "loader-runner": "^4.2.0",
+ "mime-types": "^2.1.27",
+ "neo-async": "^2.6.2",
+ "schema-utils": "^3.2.0",
+ "tapable": "^2.1.1",
+ "terser-webpack-plugin": "^5.3.7",
+ "watchpack": "^2.4.0",
+ "webpack-sources": "^3.2.3"
+ },
+ "bin": {
+ "webpack": "bin/webpack.js"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ },
+ "peerDependenciesMeta": {
+ "webpack-cli": {
+ "optional": true
+ }
+ }
+ },
+ "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"
+ },
+ "peerDependencies": {
+ "webpack": "4.x.x || 5.x.x"
+ },
+ "peerDependenciesMeta": {
+ "@webpack-cli/generators": {
+ "optional": true
+ },
+ "@webpack-cli/migrate": {
+ "optional": true
+ },
+ "webpack-bundle-analyzer": {
+ "optional": true
+ },
+ "webpack-dev-server": {
+ "optional": true
+ }
+ }
+ },
+ "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.10.0",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.10.0.tgz",
+ "integrity": "sha512-+4zXKdx7UnO+1jaN4l2lHVD+mFvnlZQP/6ljaJVb4SZiwIKeUnrT5l0gkT8z+n4hKpC+jpOv6O9R+gLtag7pSA==",
+ "dev": true,
+ "dependencies": {
+ "clone-deep": "^4.0.1",
+ "flat": "^5.0.2",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz",
+ "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/webpack/node_modules/acorn": {
+ "version": "8.11.3",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
+ "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
+ "dev": true,
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/webpack/node_modules/schema-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "dev": true,
+ "dependencies": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ },
+ "engines": {
+ "node": ">= 10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
+ "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/which-boxed-primitive": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz",
+ "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==",
+ "dev": true,
+ "dependencies": {
+ "is-bigint": "^1.0.1",
+ "is-boolean-object": "^1.1.0",
+ "is-number-object": "^1.0.4",
+ "is-string": "^1.0.5",
+ "is-symbol": "^1.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-typed-array": {
+ "version": "1.1.13",
+ "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.13.tgz",
+ "integrity": "sha512-P5Nra0qjSncduVPEAr7xhoF5guty49ArDTwzJ/yNuPIbZppyRxFQsRCWrocxIY+CnMVG+qfbU2FmDKyvSGClow==",
+ "dev": true,
+ "dependencies": {
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.4",
+ "for-each": "^0.3.3",
+ "gopd": "^1.0.1",
+ "has-tostringtag": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/wildcard": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz",
+ "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==",
+ "dev": true
+ },
+ "node_modules/workerpool": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz",
+ "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==",
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "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"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "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/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": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "dev": true
+ },
+ "node_modules/ws": {
+ "version": "8.11.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
+ "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": "^5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "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/yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true
+ },
+ "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/yamljs/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/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/yamscripts/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/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.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/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/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"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ }
+ },
+ "dependencies": {
+ "@ampproject/remapping": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz",
+ "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/gen-mapping": "^0.3.0",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ }
+ },
+ "@babel/code-frame": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz",
+ "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==",
+ "dev": true,
+ "requires": {
+ "@babel/highlight": "^7.23.4",
+ "chalk": "^2.4.2"
+ }
+ },
+ "@babel/compat-data": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz",
+ "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==",
+ "dev": true
+ },
+ "@babel/core": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.5.tgz",
+ "integrity": "sha512-Cwc2XjUrG4ilcfOw4wBAK+enbdgwAcAJCfGUItPBKR7Mjw4aEfAFYrLxeRp4jWgtNIKn3n2AlBOfwwafl+42/g==",
+ "dev": true,
+ "requires": {
+ "@ampproject/remapping": "^2.2.0",
+ "@babel/code-frame": "^7.23.5",
+ "@babel/generator": "^7.23.5",
+ "@babel/helper-compilation-targets": "^7.22.15",
+ "@babel/helper-module-transforms": "^7.23.3",
+ "@babel/helpers": "^7.23.5",
+ "@babel/parser": "^7.23.5",
+ "@babel/template": "^7.22.15",
+ "@babel/traverse": "^7.23.5",
+ "@babel/types": "^7.23.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ }
+ },
+ "@babel/generator": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz",
+ "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.23.6",
+ "@jridgewell/gen-mapping": "^0.3.2",
+ "@jridgewell/trace-mapping": "^0.3.17",
+ "jsesc": "^2.5.1"
+ }
+ },
+ "@babel/helper-annotate-as-pure": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz",
+ "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.22.5"
+ }
+ },
+ "@babel/helper-compilation-targets": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz",
+ "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==",
+ "dev": true,
+ "requires": {
+ "@babel/compat-data": "^7.23.5",
+ "@babel/helper-validator-option": "^7.23.5",
+ "browserslist": "^4.22.2",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ }
+ },
+ "@babel/helper-environment-visitor": {
+ "version": "7.22.20",
+ "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz",
+ "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==",
+ "dev": true
+ },
+ "@babel/helper-function-name": {
+ "version": "7.23.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz",
+ "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==",
+ "dev": true,
+ "requires": {
+ "@babel/template": "^7.22.15",
+ "@babel/types": "^7.23.0"
+ }
+ },
+ "@babel/helper-hoist-variables": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz",
+ "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.22.5"
+ }
+ },
+ "@babel/helper-module-imports": {
+ "version": "7.22.15",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz",
+ "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.22.15"
+ }
+ },
+ "@babel/helper-module-transforms": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz",
+ "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-module-imports": "^7.22.15",
+ "@babel/helper-simple-access": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/helper-validator-identifier": "^7.22.20"
+ }
+ },
+ "@babel/helper-plugin-utils": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz",
+ "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==",
+ "dev": true
+ },
+ "@babel/helper-simple-access": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz",
+ "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.22.5"
+ }
+ },
+ "@babel/helper-split-export-declaration": {
+ "version": "7.22.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz",
+ "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.22.5"
+ }
+ },
+ "@babel/helper-string-parser": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz",
+ "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==",
+ "dev": true
+ },
+ "@babel/helper-validator-identifier": {
+ "version": "7.22.20",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
+ "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
+ "dev": true
+ },
+ "@babel/helper-validator-option": {
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz",
+ "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==",
+ "dev": true
+ },
+ "@babel/helpers": {
+ "version": "7.23.8",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.8.tgz",
+ "integrity": "sha512-KDqYz4PiOWvDFrdHLPhKtCThtIcKVy6avWD2oG4GEvyQ+XDZwHD4YQd+H2vNMnq2rkdxsDkU82T+Vk8U/WXHRQ==",
+ "dev": true,
+ "requires": {
+ "@babel/template": "^7.22.15",
+ "@babel/traverse": "^7.23.7",
+ "@babel/types": "^7.23.6"
+ }
+ },
+ "@babel/highlight": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz",
+ "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "chalk": "^2.4.2",
+ "js-tokens": "^4.0.0"
+ }
+ },
+ "@babel/parser": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz",
+ "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==",
+ "dev": true
+ },
+ "@babel/plugin-syntax-jsx": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.23.3.tgz",
+ "integrity": "sha512-EB2MELswq55OHUoRZLGg/zC7QWUKfNLpE57m/S2yr1uEneIgsTgrSzXP3NXEsMkVn76OlaVVnzN+ugObuYGwhg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.22.5"
+ }
+ },
+ "@babel/plugin-transform-react-display-name": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.23.3.tgz",
+ "integrity": "sha512-GnvhtVfA2OAtzdX58FJxU19rhoGeQzyVndw3GgtdECQvQFXPEZIOVULHVZGAYmOgmqjXpVpfocAbSjh99V/Fqw==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.22.5"
+ }
+ },
+ "@babel/plugin-transform-react-jsx": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.23.4.tgz",
+ "integrity": "sha512-5xOpoPguCZCRbo/JeHlloSkTA8Bld1J/E1/kLfD1nsuiW1m8tduTA1ERCgIZokDflX/IBzKcqR3l7VlRgiIfHA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-annotate-as-pure": "^7.22.5",
+ "@babel/helper-module-imports": "^7.22.15",
+ "@babel/helper-plugin-utils": "^7.22.5",
+ "@babel/plugin-syntax-jsx": "^7.23.3",
+ "@babel/types": "^7.23.4"
+ }
+ },
+ "@babel/plugin-transform-react-jsx-development": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.22.5.tgz",
+ "integrity": "sha512-bDhuzwWMuInwCYeDeMzyi7TaBgRQei6DqxhbyniL7/VG4RSS7HtSL2QbY4eESy1KJqlWt8g3xeEBGPuo+XqC8A==",
+ "dev": true,
+ "requires": {
+ "@babel/plugin-transform-react-jsx": "^7.22.5"
+ }
+ },
+ "@babel/plugin-transform-react-pure-annotations": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.23.3.tgz",
+ "integrity": "sha512-qMFdSS+TUhB7Q/3HVPnEdYJDQIk57jkntAwSuz9xfSE4n+3I+vHYCli3HoHawN1Z3RfCz/y1zXA/JXjG6cVImQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-annotate-as-pure": "^7.22.5",
+ "@babel/helper-plugin-utils": "^7.22.5"
+ }
+ },
+ "@babel/preset-react": {
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.23.3.tgz",
+ "integrity": "sha512-tbkHOS9axH6Ysf2OUEqoSZ6T3Fa2SrNH6WTWSPBboxKzdxNc9qOICeLXkNG0ZEwbQ1HY8liwOce4aN/Ceyuq6w==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.22.5",
+ "@babel/helper-validator-option": "^7.22.15",
+ "@babel/plugin-transform-react-display-name": "^7.23.3",
+ "@babel/plugin-transform-react-jsx": "^7.22.15",
+ "@babel/plugin-transform-react-jsx-development": "^7.22.5",
+ "@babel/plugin-transform-react-pure-annotations": "^7.23.3"
+ }
+ },
+ "@babel/runtime": {
+ "version": "7.23.8",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.8.tgz",
+ "integrity": "sha512-Y7KbAP984rn1VGMbGqKmBLio9V7y5Je9GvU4rQPCPinCyNfUcToxIXl06d59URp/F3LwinvODxab5N/G6qggkw==",
+ "requires": {
+ "regenerator-runtime": "^0.14.0"
+ }
+ },
+ "@babel/template": {
+ "version": "7.22.15",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz",
+ "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.22.13",
+ "@babel/parser": "^7.22.15",
+ "@babel/types": "^7.22.15"
+ }
+ },
+ "@babel/traverse": {
+ "version": "7.23.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz",
+ "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.23.5",
+ "@babel/generator": "^7.23.6",
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-function-name": "^7.23.0",
+ "@babel/helper-hoist-variables": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/parser": "^7.23.6",
+ "@babel/types": "^7.23.6",
+ "debug": "^4.3.1",
+ "globals": "^11.1.0"
+ }
+ },
+ "@babel/types": {
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz",
+ "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-string-parser": "^7.23.4",
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "@colors/colors": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
+ "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
+ "dev": true
+ },
+ "@discoveryjs/json-ext": {
+ "version": "0.5.7",
+ "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz",
+ "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==",
+ "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"
+ }
+ },
+ "@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
+ },
+ "@jridgewell/gen-mapping": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
+ "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/set-array": "^1.0.1",
+ "@jridgewell/sourcemap-codec": "^1.4.10",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ }
+ },
+ "@jridgewell/resolve-uri": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz",
+ "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==",
+ "dev": true
+ },
+ "@jridgewell/set-array": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
+ "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
+ "dev": true
+ },
+ "@jridgewell/source-map": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz",
+ "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/gen-mapping": "^0.3.0",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ }
+ },
+ "@jridgewell/sourcemap-codec": {
+ "version": "1.4.15",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
+ "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
+ "dev": true
+ },
+ "@jridgewell/trace-mapping": {
+ "version": "0.3.21",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz",
+ "integrity": "sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "@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": {
+ "convert-source-map": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
+ "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
+ "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"
+ }
+ }
+ }
+ },
+ "@sinonjs/commons": {
+ "version": "1.8.6",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.6.tgz",
+ "integrity": "sha512-Ky+XkAkqPZSm3NLBeUng77EBQl3cmeJhITaGHdYH8kjVB+aun3S4XBRti2zt17mtt0mIUDiNxYeoJm6drVvBJQ==",
+ "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.1.3",
+ "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.1.3.tgz",
+ "integrity": "sha512-nhOb2dWPeb1sd3IQXL/dVPnKHDOAFfvichtBf4xV00/rU1QbPCQqKMbvIheIjqwVjh7qIgf2AHTHi391yMOMpQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.6.0",
+ "lodash.get": "^4.4.2",
+ "type-detect": "^4.0.8"
+ }
+ },
+ "@sinonjs/text-encoding": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz",
+ "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==",
+ "dev": true
+ },
+ "@socket.io/component-emitter": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz",
+ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==",
+ "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.17",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz",
+ "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==",
+ "dev": true,
+ "requires": {
+ "@types/node": "*"
+ }
+ },
+ "@types/eslint": {
+ "version": "8.56.2",
+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.2.tgz",
+ "integrity": "sha512-uQDwm1wFHmbBbCZCqAlq6Do9LYwByNZHWzXppSnay9SuwJ+VRbjkbLABer54kcPnMSlG6Fdiy2yaFXm/z9Z5gw==",
+ "dev": true,
+ "requires": {
+ "@types/estree": "*",
+ "@types/json-schema": "*"
+ }
+ },
+ "@types/eslint-scope": {
+ "version": "3.7.7",
+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz",
+ "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==",
+ "dev": true,
+ "requires": {
+ "@types/eslint": "*",
+ "@types/estree": "*"
+ }
+ },
+ "@types/estree": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz",
+ "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==",
+ "dev": true
+ },
+ "@types/hoist-non-react-statics": {
+ "version": "3.3.5",
+ "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.5.tgz",
+ "integrity": "sha512-SbcrWzkKBw2cdwRTwQAswfpB9g9LJWfjtUeW/jvNwbhC8cpmmNYVePa+ncbUe0rGTQ7G3Ff6mYUN2VMfLVr+Sg==",
+ "requires": {
+ "@types/react": "*",
+ "hoist-non-react-statics": "^3.3.0"
+ }
+ },
+ "@types/json-schema": {
+ "version": "7.0.15",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+ "dev": true
+ },
+ "@types/node": {
+ "version": "20.11.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.0.tgz",
+ "integrity": "sha512-o9bjXmDNcF7GbM4CNQpmi+TutCgap/K3w1JyKgxAjqx41zp9qlIAVFi0IhCNsJcXolEqLWhbFbEeL0PvYm4pcQ==",
+ "dev": true,
+ "requires": {
+ "undici-types": "~5.26.4"
+ }
+ },
+ "@types/prop-types": {
+ "version": "15.7.11",
+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.11.tgz",
+ "integrity": "sha512-ga8y9v9uyeiLdpKddhxYQkxNDrfvuPrlFb0N1qnZZByvcElJaXthF1UhvCh9TLWJBEHeNtdnbysW7Y6Uq8CVng=="
+ },
+ "@types/react": {
+ "version": "18.2.47",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.2.47.tgz",
+ "integrity": "sha512-xquNkkOirwyCgoClNk85BjP+aqnIS+ckAJ8i37gAbDs14jfW/J23f2GItAf33oiUPQnqNMALiFeoM9Y5mbjpVQ==",
+ "requires": {
+ "@types/prop-types": "*",
+ "@types/scheduler": "*",
+ "csstype": "^3.0.2"
+ }
+ },
+ "@types/react-redux": {
+ "version": "7.1.33",
+ "resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.33.tgz",
+ "integrity": "sha512-NF8m5AjWCkert+fosDsN3hAlHzpjSiXlVy9EgQEmLoBhaNXbmyeGs/aj5dQzKuF+/q+S7JQagorGDW8pJ28Hmg==",
+ "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.8",
+ "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.8.tgz",
+ "integrity": "sha512-WZLiwShhwLRmeV6zH+GkbOFT6Z6VklCItrDioxUnv+u4Ll+8vKeFySoFyK/0ctcRpOmwAicELfmys1sDc/Rw+A=="
+ },
+ "@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.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz",
+ "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/helper-numbers": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6"
+ }
+ },
+ "@webassemblyjs/floating-point-hex-parser": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz",
+ "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-api-error": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz",
+ "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-buffer": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz",
+ "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-numbers": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz",
+ "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/floating-point-hex-parser": "1.11.6",
+ "@webassemblyjs/helper-api-error": "1.11.6",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/helper-wasm-bytecode": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz",
+ "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-wasm-section": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz",
+ "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6"
+ }
+ },
+ "@webassemblyjs/ieee754": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz",
+ "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==",
+ "dev": true,
+ "requires": {
+ "@xtuc/ieee754": "^1.2.0"
+ }
+ },
+ "@webassemblyjs/leb128": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz",
+ "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==",
+ "dev": true,
+ "requires": {
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/utf8": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz",
+ "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==",
+ "dev": true
+ },
+ "@webassemblyjs/wasm-edit": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz",
+ "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/helper-wasm-section": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6",
+ "@webassemblyjs/wasm-opt": "1.11.6",
+ "@webassemblyjs/wasm-parser": "1.11.6",
+ "@webassemblyjs/wast-printer": "1.11.6"
+ }
+ },
+ "@webassemblyjs/wasm-gen": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz",
+ "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/ieee754": "1.11.6",
+ "@webassemblyjs/leb128": "1.11.6",
+ "@webassemblyjs/utf8": "1.11.6"
+ }
+ },
+ "@webassemblyjs/wasm-opt": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz",
+ "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-buffer": "1.11.6",
+ "@webassemblyjs/wasm-gen": "1.11.6",
+ "@webassemblyjs/wasm-parser": "1.11.6"
+ }
+ },
+ "@webassemblyjs/wasm-parser": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz",
+ "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@webassemblyjs/helper-api-error": "1.11.6",
+ "@webassemblyjs/helper-wasm-bytecode": "1.11.6",
+ "@webassemblyjs/ieee754": "1.11.6",
+ "@webassemblyjs/leb128": "1.11.6",
+ "@webassemblyjs/utf8": "1.11.6"
+ }
+ },
+ "@webassemblyjs/wast-printer": {
+ "version": "1.11.6",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz",
+ "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.11.6",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webpack-cli/configtest": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz",
+ "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==",
+ "dev": true,
+ "requires": {}
+ },
+ "@webpack-cli/info": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz",
+ "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==",
+ "dev": true,
+ "requires": {
+ "envinfo": "^7.7.3"
+ }
+ },
+ "@webpack-cli/serve": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz",
+ "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==",
+ "dev": true,
+ "requires": {}
+ },
+ "@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.8",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
+ "dev": true,
+ "requires": {
+ "mime-types": "~2.1.34",
+ "negotiator": "0.6.3"
+ }
+ },
+ "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.9.0",
+ "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz",
+ "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==",
+ "dev": true,
+ "requires": {}
+ },
+ "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"
+ }
+ },
+ "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,
+ "requires": {}
+ },
+ "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-regex": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz",
+ "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
+ "dev": true,
+ "requires": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ }
+ },
+ "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
+ },
+ "array-buffer-byte-length": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.0.tgz",
+ "integrity": "sha512-LPuwb2P+NrQw3XhxGc36+XSvuBPopovXYTR9Ew++Du9Yb/bx5AzBfrIsBoj0EZUifjQU+sHL21sseZ3jerWO/A==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "is-array-buffer": "^3.0.1"
+ }
+ },
+ "array.prototype.filter": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/array.prototype.filter/-/array.prototype.filter-1.0.3.tgz",
+ "integrity": "sha512-VizNcj/RGJiUyQBgzwxzE5oHdeuXY5hSbbmKMlphj1cy1Vl7Pn2asCGbSrru6hSQjmCzqTBPVWAF/whmEOVHbw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-array-method-boxes-properly": "^1.0.0",
+ "is-string": "^1.0.7"
+ }
+ },
+ "array.prototype.find": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/array.prototype.find/-/array.prototype.find-2.2.2.tgz",
+ "integrity": "sha512-DRumkfW97iZGOfn+lIXbkVrXL04sfYKX+EfOodo8XboR5sxPDVvOjZTF/rysusa9lmhmSOeD6Vp6RKQP+eP4Tg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-shim-unscopables": "^1.0.0"
+ }
+ },
+ "array.prototype.flat": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz",
+ "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "es-shim-unscopables": "^1.0.0"
+ }
+ },
+ "arraybuffer.prototype.slice": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.2.tgz",
+ "integrity": "sha512-yMBKppFur/fbHu9/6USUe03bZ4knMYiwFBcyiaXB8Go0qNehwX6inYPzK9U0NeQvGxKthcmHcaR8P5MStSRBAw==",
+ "dev": true,
+ "requires": {
+ "array-buffer-byte-length": "^1.0.0",
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "get-intrinsic": "^1.2.1",
+ "is-array-buffer": "^3.0.2",
+ "is-shared-array-buffer": "^1.0.2"
+ }
+ },
+ "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
+ },
+ "available-typed-arrays": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz",
+ "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==",
+ "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": {
+ "json5": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",
+ "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.0"
+ }
+ },
+ "loader-utils": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz",
+ "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==",
+ "dev": true,
+ "requires": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^3.0.0",
+ "json5": "^1.0.1"
+ }
+ }
+ }
+ },
+ "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.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "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
+ },
+ "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
+ },
+ "body-parser": {
+ "version": "1.20.2",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz",
+ "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==",
+ "dev": true,
+ "requires": {
+ "bytes": "3.1.2",
+ "content-type": "~1.0.5",
+ "debug": "2.6.9",
+ "depd": "2.0.0",
+ "destroy": "1.2.0",
+ "http-errors": "2.0.0",
+ "iconv-lite": "0.4.24",
+ "on-finished": "2.4.1",
+ "qs": "6.11.0",
+ "raw-body": "2.5.2",
+ "type-is": "~1.6.18",
+ "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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ }
+ }
+ },
+ "boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
+ "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.22.2",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.2.tgz",
+ "integrity": "sha512-0UgcrvQmBDvZHFGdYUehrCNIazki7/lUP3kkoi/r3YB2amZbFM9J43ZRkJTXBUZK4gmx56+Sqk9+Vs9mwZx9+A==",
+ "dev": true,
+ "requires": {
+ "caniuse-lite": "^1.0.30001565",
+ "electron-to-chromium": "^1.4.601",
+ "node-releases": "^2.0.14",
+ "update-browserslist-db": "^1.0.13"
+ }
+ },
+ "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.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "dev": true
+ },
+ "bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "dev": true
+ },
+ "cached-iterable": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/cached-iterable/-/cached-iterable-0.3.0.tgz",
+ "integrity": "sha512-MDqM6TpBVebZD4UDtmlFp8EjVtRcsB6xt9aRdWymjk0fWVUUGgmt/V7o0H0gkI2Tkvv8B0ucjidZm4mLosdlWw=="
+ },
+ "call-bind": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz",
+ "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.2",
+ "get-intrinsic": "^1.2.1",
+ "set-function-length": "^1.1.1"
+ }
+ },
+ "camelcase": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
+ "dev": true
+ },
+ "caniuse-lite": {
+ "version": "1.0.30001576",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001576.tgz",
+ "integrity": "sha512-ff5BdakGe2P3SQsMsiqmt1Lc8221NR1VzHj5jXN5vBny9A6fpze94HiVV/n7XRosOlsShJcvMv5mdnpjOGCEgg==",
+ "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"
+ }
+ },
+ "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.3",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz",
+ "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==",
+ "dev": true,
+ "requires": {
+ "get-func-name": "^2.0.2"
+ }
+ },
+ "cheerio": {
+ "version": "1.0.0-rc.12",
+ "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz",
+ "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==",
+ "dev": true,
+ "requires": {
+ "cheerio-select": "^2.1.0",
+ "dom-serializer": "^2.0.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1",
+ "htmlparser2": "^8.0.1",
+ "parse5": "^7.0.0",
+ "parse5-htmlparser2-tree-adapter": "^7.0.0"
+ }
+ },
+ "cheerio-select": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
+ "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
+ "dev": true,
+ "requires": {
+ "boolbase": "^1.0.0",
+ "css-select": "^5.1.0",
+ "css-what": "^6.1.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1"
+ }
+ },
+ "chokidar": {
+ "version": "3.5.3",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
+ "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
+ "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"
+ }
+ },
+ "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
+ },
+ "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": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "dev": true
+ },
+ "colorette": {
+ "version": "2.0.20",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
+ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "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": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==",
+ "dev": true
+ },
+ "concat-map": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+ "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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ }
+ }
+ },
+ "content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "dev": true
+ },
+ "convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true
+ },
+ "cookie": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
+ "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==",
+ "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"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true
+ }
+ }
+ },
+ "cross-spawn": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
+ "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
+ "dev": true,
+ "requires": {
+ "nice-try": "^1.0.4",
+ "path-key": "^2.0.1",
+ "semver": "^5.5.0",
+ "shebang-command": "^1.2.0",
+ "which": "^1.2.9"
+ },
+ "dependencies": {
+ "semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "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"
+ }
+ }
+ }
+ },
+ "css-select": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz",
+ "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==",
+ "dev": true,
+ "requires": {
+ "boolbase": "^1.0.0",
+ "css-what": "^6.1.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "nth-check": "^2.0.1"
+ }
+ },
+ "css-what": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz",
+ "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==",
+ "dev": true
+ },
+ "csstype": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
+ },
+ "custom-event": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz",
+ "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==",
+ "dev": true
+ },
+ "date-format": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.14.tgz",
+ "integrity": "sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==",
+ "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-data-property": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz",
+ "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==",
+ "dev": true,
+ "requires": {
+ "get-intrinsic": "^1.2.1",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0"
+ }
+ },
+ "define-properties": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
+ "dev": true,
+ "requires": {
+ "define-data-property": "^1.0.1",
+ "has-property-descriptors": "^1.0.0",
+ "object-keys": "^1.1.1"
+ }
+ },
+ "depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "dev": true
+ },
+ "destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+ "dev": true
+ },
+ "di": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz",
+ "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==",
+ "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": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==",
+ "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": "sha512-Yra4DbvoW7/Z6LBN560ZwXMjoNOSAN2wRsKFGc4iBeso+mpIA6qj1vfdf9HpMaKAqG6wXTy+1SYEzmNpKXOSsQ==",
+ "dev": true,
+ "requires": {
+ "custom-event": "~1.0.0",
+ "ent": "~2.2.0",
+ "extend": "^3.0.0",
+ "void-elements": "^2.0.0"
+ }
+ },
+ "dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ }
+ },
+ "domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "dev": true
+ },
+ "domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "^2.3.0"
+ }
+ },
+ "domutils": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.1.0.tgz",
+ "integrity": "sha512-H78uMmQtI2AhgDJjWeQmHwJJ2bLPD3GMmO7Zja/ZZh84wkm+4ut+IUnUdRa8uCGX88DiVx1j6FRe1XfxEgjEZA==",
+ "dev": true,
+ "requires": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ }
+ },
+ "ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "dev": true
+ },
+ "electron-to-chromium": {
+ "version": "1.4.629",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.629.tgz",
+ "integrity": "sha512-5UUkr3k3CZ/k+9Sw7vaaIMyOzMC0XbPyprKI3n0tbKDqkzTDOjK4izm7DxlkueRMim6ZZQ1ja9F7hoFVplHihA==",
+ "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": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
+ "dev": true
+ },
+ "engine.io": {
+ "version": "6.5.4",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.4.tgz",
+ "integrity": "sha512-KdVSDKhVKyOi+r5uEabrDLZw2qXStVvCsEB/LN3mw4WFi6Gx50jTyuxYVCwAAC0U46FdnzP/ScKRBTXb/NiEOg==",
+ "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.2.1",
+ "ws": "~8.11.0"
+ }
+ },
+ "engine.io-parser": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.1.tgz",
+ "integrity": "sha512-9JktcM3u18nU9N2Lz3bWeBgxVgOKpw7yhRaoxQA3FUDZzzw+9WlA6p4G4u0RixNkg14fH7EfEc/RhpurtiROTQ==",
+ "dev": true
+ },
+ "enhanced-resolve": {
+ "version": "5.15.0",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz",
+ "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.2.0"
+ }
+ },
+ "ent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz",
+ "integrity": "sha512-GHrMyVZQWvTIdDtpiEXdHZnFQKzeO09apj8Cbl4pKWy4i0Oprcq17usfDt5aO63swf0JOeMWjWQE/LzgSRuWpA==",
+ "dev": true
+ },
+ "entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "dev": true
+ },
+ "envinfo": {
+ "version": "7.11.0",
+ "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.11.0.tgz",
+ "integrity": "sha512-G9/6xF1FPbIw0TtalAMaVPpiq2aDEuKLXM314jPVAO9r2fo2a4BLqMNkmRS7O/xPPZ+COAhGIz3ETvHEV3eUcg==",
+ "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": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "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"
+ }
+ },
+ "semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true
+ }
+ }
+ },
+ "enzyme-adapter-utils": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-utils/-/enzyme-adapter-utils-1.14.1.tgz",
+ "integrity": "sha512-JZgMPF1QOI7IzBj24EZoDpaeG/p8Os7WeBZWTJydpsH7JRStc7jYbHE4CmNQaLqazaGFyLM8ALWA3IIZvxW3PQ==",
+ "dev": true,
+ "requires": {
+ "airbnb-prop-types": "^2.16.0",
+ "function.prototype.name": "^1.1.5",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.4",
+ "object.fromentries": "^2.0.5",
+ "prop-types": "^15.8.1",
+ "semver": "^5.7.1"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true
+ },
+ "prop-types": {
+ "version": "15.8.1",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "dev": true,
+ "requires": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.13.1"
+ }
+ },
+ "semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true
+ }
+ }
+ },
+ "enzyme-shallow-equal": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/enzyme-shallow-equal/-/enzyme-shallow-equal-1.0.5.tgz",
+ "integrity": "sha512-i6cwm7hN630JXenxxJFBKzgLC3hMTafFQXflvzHgPmDhOBhxUWDe8AeRv1qp2/uWJ2Y8z5yLWMzmAfkTOiOCZg==",
+ "dev": true,
+ "requires": {
+ "has": "^1.0.3",
+ "object-is": "^1.1.5"
+ }
+ },
+ "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.22.3",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.22.3.tgz",
+ "integrity": "sha512-eiiY8HQeYfYH2Con2berK+To6GrK2RxbPawDkGq4UiCQQfZHb6wX9qQqkbpPqaxQFcl8d9QzZqo0tGE0VcrdwA==",
+ "dev": true,
+ "requires": {
+ "array-buffer-byte-length": "^1.0.0",
+ "arraybuffer.prototype.slice": "^1.0.2",
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.5",
+ "es-set-tostringtag": "^2.0.1",
+ "es-to-primitive": "^1.2.1",
+ "function.prototype.name": "^1.1.6",
+ "get-intrinsic": "^1.2.2",
+ "get-symbol-description": "^1.0.0",
+ "globalthis": "^1.0.3",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0",
+ "has-proto": "^1.0.1",
+ "has-symbols": "^1.0.3",
+ "hasown": "^2.0.0",
+ "internal-slot": "^1.0.5",
+ "is-array-buffer": "^3.0.2",
+ "is-callable": "^1.2.7",
+ "is-negative-zero": "^2.0.2",
+ "is-regex": "^1.1.4",
+ "is-shared-array-buffer": "^1.0.2",
+ "is-string": "^1.0.7",
+ "is-typed-array": "^1.1.12",
+ "is-weakref": "^1.0.2",
+ "object-inspect": "^1.13.1",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.4",
+ "regexp.prototype.flags": "^1.5.1",
+ "safe-array-concat": "^1.0.1",
+ "safe-regex-test": "^1.0.0",
+ "string.prototype.trim": "^1.2.8",
+ "string.prototype.trimend": "^1.0.7",
+ "string.prototype.trimstart": "^1.0.7",
+ "typed-array-buffer": "^1.0.0",
+ "typed-array-byte-length": "^1.0.0",
+ "typed-array-byte-offset": "^1.0.0",
+ "typed-array-length": "^1.0.4",
+ "unbox-primitive": "^1.0.2",
+ "which-typed-array": "^1.1.13"
+ }
+ },
+ "es-array-method-boxes-properly": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz",
+ "integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==",
+ "dev": true
+ },
+ "es-module-lexer": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.4.1.tgz",
+ "integrity": "sha512-cXLGjP0c4T3flZJKQSuziYoq7MlT+rnvfZjfp7h+I7K9BNX54kP9nyWvdbwjQ4u1iWbOL4u96fgeZLToQlZC7w==",
+ "dev": true
+ },
+ "es-set-tostringtag": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.2.tgz",
+ "integrity": "sha512-BuDyupZt65P9D2D2vA/zqcI3G5xRsklm5N3xCwuiy+/vKy8i0ifdsQP1sLgO4tZDSCaQUSnmC48khknGMV3D2Q==",
+ "dev": true,
+ "requires": {
+ "get-intrinsic": "^1.2.2",
+ "has-tostringtag": "^1.0.0",
+ "hasown": "^2.0.0"
+ }
+ },
+ "es-shim-unscopables": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz",
+ "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==",
+ "dev": true,
+ "requires": {
+ "hasown": "^2.0.0"
+ }
+ },
+ "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": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "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": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "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"
+ }
+ },
+ "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": {
+ "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"
+ }
+ },
+ "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
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "dev": true
+ },
+ "on-finished": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
+ "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==",
+ "dev": true,
+ "requires": {
+ "ee-first": "1.1.1"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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": "3.2.9",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz",
+ "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==",
+ "dev": true
+ },
+ "follow-redirects": {
+ "version": "1.15.5",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
+ "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
+ "dev": true
+ },
+ "for-each": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
+ "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==",
+ "dev": true,
+ "requires": {
+ "is-callable": "^1.1.3"
+ }
+ },
+ "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"
+ }
+ },
+ "fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
+ "dev": true
+ },
+ "fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "optional": true
+ },
+ "function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true
+ },
+ "function.prototype.name": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz",
+ "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1",
+ "functions-have-names": "^1.2.3"
+ }
+ },
+ "functions-have-names": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",
+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
+ "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.2",
+ "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz",
+ "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==",
+ "dev": true
+ },
+ "get-intrinsic": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz",
+ "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.2",
+ "has-proto": "^1.0.1",
+ "has-symbols": "^1.0.3",
+ "hasown": "^2.0.0"
+ }
+ },
+ "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
+ },
+ "get-symbol-description": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz",
+ "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.1.1"
+ }
+ },
+ "glob": {
+ "version": "7.2.3",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
+ "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
+ "dev": true,
+ "requires": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.1.1",
+ "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
+ },
+ "globalthis": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.3.tgz",
+ "integrity": "sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3"
+ }
+ },
+ "gopd": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz",
+ "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==",
+ "dev": true,
+ "requires": {
+ "get-intrinsic": "^1.1.3"
+ }
+ },
+ "graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
+ "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==",
+ "dev": true
+ },
+ "has-bigints": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz",
+ "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==",
+ "dev": true
+ },
+ "has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "dev": true
+ },
+ "has-property-descriptors": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz",
+ "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==",
+ "dev": true,
+ "requires": {
+ "get-intrinsic": "^1.2.2"
+ }
+ },
+ "has-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz",
+ "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==",
+ "dev": true
+ },
+ "has-symbols": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
+ "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==",
+ "dev": true
+ },
+ "has-tostringtag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz",
+ "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==",
+ "dev": true,
+ "requires": {
+ "has-symbols": "^1.0.2"
+ }
+ },
+ "hasown": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz",
+ "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.2"
+ }
+ },
+ "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.3.1",
+ "resolved": "https://registry.npmjs.org/html-element-map/-/html-element-map-1.3.1.tgz",
+ "integrity": "sha512-6XMlxrAFX4UEEGxctfFnmrFaaZFNf9i5fNuV5wZ3WWQ4FVaNP1aX1LkX9j2mfEx1NpjeE/rL3nmgEn23GdFmrg==",
+ "dev": true,
+ "requires": {
+ "array.prototype.filter": "^1.0.0",
+ "call-bind": "^1.0.2"
+ }
+ },
+ "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": "8.0.2",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
+ "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1",
+ "entities": "^4.4.0"
+ }
+ },
+ "http-errors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
+ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
+ "dev": true,
+ "requires": {
+ "depd": "2.0.0",
+ "inherits": "2.0.4",
+ "setprototypeof": "1.2.0",
+ "statuses": "2.0.1",
+ "toidentifier": "1.0.1"
+ },
+ "dependencies": {
+ "statuses": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
+ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
+ "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.1.0",
+ "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz",
+ "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==",
+ "dev": true,
+ "requires": {
+ "pkg-dir": "^4.2.0",
+ "resolve-cwd": "^3.0.0"
+ }
+ },
+ "inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
+ "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
+ },
+ "internal-slot": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.6.tgz",
+ "integrity": "sha512-Xj6dv+PsbtwyPpEflsejS+oIZxmMlV44zAhG479uYu89MsjcYOhCFnNyKrkJrihbsiasQyY0afoCl/9BLR65bg==",
+ "dev": true,
+ "requires": {
+ "get-intrinsic": "^1.2.2",
+ "hasown": "^2.0.0",
+ "side-channel": "^1.0.4"
+ }
+ },
+ "interpret": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz",
+ "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==",
+ "dev": true
+ },
+ "is-array-buffer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.2.tgz",
+ "integrity": "sha512-y+FyyR/w8vfIRq4eQcM1EYgSTnmHXPqaF+IgzgraytCFq5Xh8lllDVmAZolPJiZttZLeFSINPYMaEJ7/vWUa1w==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.0",
+ "is-typed-array": "^1.1.10"
+ }
+ },
+ "is-arrayish": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
+ "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
+ "dev": true
+ },
+ "is-bigint": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz",
+ "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==",
+ "dev": true,
+ "requires": {
+ "has-bigints": "^1.0.1"
+ }
+ },
+ "is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "requires": {
+ "binary-extensions": "^2.0.0"
+ }
+ },
+ "is-boolean-object": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz",
+ "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "is-callable": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
+ "dev": true
+ },
+ "is-core-module": {
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz",
+ "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==",
+ "dev": true,
+ "requires": {
+ "hasown": "^2.0.0"
+ }
+ },
+ "is-date-object": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz",
+ "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==",
+ "dev": true,
+ "requires": {
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "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": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+ "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
+ },
+ "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.2",
+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz",
+ "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==",
+ "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.7",
+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz",
+ "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==",
+ "dev": true,
+ "requires": {
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "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.1.4",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz",
+ "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "is-shared-array-buffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz",
+ "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2"
+ }
+ },
+ "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.7",
+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz",
+ "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==",
+ "dev": true,
+ "requires": {
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "is-subset": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-subset/-/is-subset-0.1.1.tgz",
+ "integrity": "sha512-6Ybun0IkarhmEqxXCNw/C0bna6Zb/TkfUX9UbwJtK6ObwAVCxmAP308WWTHviM/zAqXk05cdhYsUsZeGQh99iw==",
+ "dev": true
+ },
+ "is-symbol": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz",
+ "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==",
+ "dev": true,
+ "requires": {
+ "has-symbols": "^1.0.2"
+ }
+ },
+ "is-typed-array": {
+ "version": "1.1.12",
+ "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.12.tgz",
+ "integrity": "sha512-Z14TF2JNG8Lss5/HMqt0//T9JeHXttXy5pH/DBU4vi98ozO2btxzq9MwYDZYnKwU8nRsz/+GVFVRDq3DkVuSPg==",
+ "dev": true,
+ "requires": {
+ "which-typed-array": "^1.1.11"
+ }
+ },
+ "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-weakref": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz",
+ "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2"
+ }
+ },
+ "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"
+ }
+ },
+ "isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true
+ },
+ "isbinaryfile": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
+ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",
+ "dev": true
+ },
+ "isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",
+ "dev": true
+ },
+ "istanbul-lib-coverage": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
+ "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"
+ }
+ },
+ "istanbul-lib-report": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
+ "dev": true,
+ "requires": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^4.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
+ },
+ "lru-cache": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
+ "dev": true,
+ "requires": {
+ "yallist": "^4.0.0"
+ }
+ },
+ "make-dir": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
+ "dev": true,
+ "requires": {
+ "semver": "^7.5.3"
+ }
+ },
+ "semver": {
+ "version": "7.5.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
+ "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
+ "dev": true,
+ "requires": {
+ "lru-cache": "^6.0.0"
+ }
+ },
+ "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"
+ }
+ },
+ "yallist": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
+ "dev": true
+ }
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "pify": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
+ "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==",
+ "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"
+ }
+ },
+ "semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true
+ }
+ }
+ },
+ "istanbul-reports": {
+ "version": "3.1.6",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz",
+ "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==",
+ "dev": true,
+ "requires": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ }
+ },
+ "jest-worker": {
+ "version": "27.5.1",
+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
+ "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
+ "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=="
+ },
+ "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"
+ }
+ },
+ "jsesc": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz",
+ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==",
+ "dev": true
+ },
+ "json-parse-better-errors": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz",
+ "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==",
+ "dev": true
+ },
+ "json-parse-even-better-errors": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
+ "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
+ },
+ "json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true
+ },
+ "jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "just-extend": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz",
+ "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==",
+ "dev": true
+ },
+ "karma": {
+ "version": "6.4.2",
+ "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.2.tgz",
+ "integrity": "sha512-C6SU/53LB31BEgRg+omznBEMY4SjHU3ricV6zBcAe1EeILKkeScr+fZXtaI5WyDbkVowJxxAI6h73NcFPmXolQ==",
+ "dev": true,
+ "requires": {
+ "@colors/colors": "1.5.0",
+ "body-parser": "^1.19.0",
+ "braces": "^3.0.2",
+ "chokidar": "^3.5.1",
+ "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.4.1",
+ "mime": "^2.5.2",
+ "minimatch": "^3.0.4",
+ "mkdirp": "^0.5.5",
+ "qjobs": "^1.2.0",
+ "range-parser": "^1.2.1",
+ "rimraf": "^3.0.2",
+ "socket.io": "^4.4.1",
+ "source-map": "^0.6.1",
+ "tmp": "^0.2.1",
+ "ua-parser-js": "^0.7.30",
+ "yargs": "^16.1.1"
+ }
+ },
+ "karma-chai": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/karma-chai/-/karma-chai-0.1.0.tgz",
+ "integrity": "sha512-mqKCkHwzPMhgTYca10S90aCEX9+HjVjjrBFAsw36Zj7BlQNbokXXCAe6Ji04VUMsxcY5RLP7YphpfO06XOubdg==",
+ "dev": true,
+ "requires": {}
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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,
+ "requires": {}
+ },
+ "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"
+ }
+ },
+ "karma-mocha-reporter": {
+ "version": "2.2.5",
+ "resolved": "https://registry.npmjs.org/karma-mocha-reporter/-/karma-mocha-reporter-2.2.5.tgz",
+ "integrity": "sha512-Hr6nhkIp0GIJJrvzY8JFeHpQZNseuIakGac4bpw8K1+5F0tLb6l7uvXRa8mt2Z+NVwYgCct4QAfp2R2QP6o00w==",
+ "dev": true,
+ "requires": {
+ "chalk": "^2.1.0",
+ "log-symbols": "^2.1.0",
+ "strip-ansi": "^4.0.0"
+ }
+ },
+ "karma-sinon": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/karma-sinon/-/karma-sinon-1.0.5.tgz",
+ "integrity": "sha512-wrkyAxJmJbn75Dqy17L/8aILJWFm7znd1CE8gkyxTBFnjMSOe2XTJ3P30T8SkxWZHmoHX0SCaUJTDBEoXs25Og==",
+ "dev": true,
+ "requires": {}
+ },
+ "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
+ },
+ "load-json-file": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
+ "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "parse-json": "^4.0.0",
+ "pify": "^3.0.0",
+ "strip-bom": "^3.0.0"
+ }
+ },
+ "loader-runner": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz",
+ "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==",
+ "dev": true
+ },
+ "loader-utils": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.1.tgz",
+ "integrity": "sha512-ZvFw1KWS3GVyYBYb7qkmRM/WwL2TQQBxgCK62rlvm4WpVQ23Nb4tYjApUlfjrEGvOs7KHEsmyUn75OHZrJMWPw==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "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": "sha512-nXEOnb/jK9g0DYMr1/Xvq6l5xMD7GDG55+GSYIYmS0G4tBk/hURD4JR9WCavs04t33WmJx9kCyp9vJ+mr4BOUw==",
+ "dev": true
+ },
+ "lodash.flattendeep": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz",
+ "integrity": "sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==",
+ "dev": true
+ },
+ "lodash.get": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
+ "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==",
+ "dev": true
+ },
+ "lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "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.9.1",
+ "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.9.1.tgz",
+ "integrity": "sha512-1somDdy9sChrr9/f4UlzhdaGfDR2c/SaD2a4T7qEkG4jTS57/B3qmnjLYePwQ8cqWnUHZI0iAKxMBpCZICiZ2g==",
+ "dev": true,
+ "requires": {
+ "date-format": "^4.0.14",
+ "debug": "^4.3.4",
+ "flatted": "^3.2.7",
+ "rfdc": "^1.3.0",
+ "streamroller": "^3.1.5"
+ }
+ },
+ "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"
+ }
+ },
+ "lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "requires": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "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"
+ }
+ },
+ "media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+ "dev": true
+ },
+ "memorystream": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
+ "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==",
+ "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"
+ }
+ },
+ "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.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "dev": true
+ },
+ "mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dev": true,
+ "requires": {
+ "mime-db": "1.52.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.1.2",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "dev": true,
+ "requires": {
+ "brace-expansion": "^1.1.7"
+ }
+ },
+ "minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "dev": true
+ },
+ "mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.6"
+ }
+ },
+ "mocha": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.2.tgz",
+ "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==",
+ "dev": true,
+ "requires": {
+ "@ungap/promise-all-settled": "1.1.2",
+ "ansi-colors": "4.1.1",
+ "browser-stdout": "1.3.1",
+ "chokidar": "3.5.3",
+ "debug": "4.3.3",
+ "diff": "5.0.0",
+ "escape-string-regexp": "4.0.0",
+ "find-up": "5.0.0",
+ "glob": "7.2.0",
+ "growl": "1.10.5",
+ "he": "1.2.0",
+ "js-yaml": "4.1.0",
+ "log-symbols": "4.1.0",
+ "minimatch": "4.2.1",
+ "ms": "2.1.3",
+ "nanoid": "3.3.1",
+ "serialize-javascript": "6.0.0",
+ "strip-json-comments": "3.1.1",
+ "supports-color": "8.1.1",
+ "which": "2.0.2",
+ "workerpool": "6.2.0",
+ "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"
+ }
+ },
+ "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.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
+ "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
+ "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
+ },
+ "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"
+ },
+ "dependencies": {
+ "minimatch": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "dev": true,
+ "requires": {
+ "brace-expansion": "^1.1.7"
+ }
+ }
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "minimatch": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-4.2.1.tgz",
+ "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==",
+ "dev": true,
+ "requires": {
+ "brace-expansion": "^1.1.7"
+ }
+ },
+ "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
+ },
+ "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"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "moo": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz",
+ "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==",
+ "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.3.1",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz",
+ "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==",
+ "dev": true
+ },
+ "nearley": {
+ "version": "2.20.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",
+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",
+ "dev": true,
+ "requires": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6"
+ }
+ },
+ "negotiator": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
+ "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.7",
+ "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.7.tgz",
+ "integrity": "sha512-wWtNUhkT7k58uvWTB/Gy26eA/EJKtPZFVAhEilN5UYVmmGRYOURbejRUyKm0Uu9XVEW7K5nBOZfR8VMB4QR2RQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^3.0.0",
+ "@sinonjs/fake-timers": "^11.2.2",
+ "@sinonjs/text-encoding": "^0.7.2",
+ "just-extend": "^6.2.0",
+ "path-to-regexp": "^6.2.1"
+ },
+ "dependencies": {
+ "@sinonjs/commons": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz",
+ "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==",
+ "dev": true,
+ "requires": {
+ "type-detect": "4.0.8"
+ }
+ },
+ "@sinonjs/fake-timers": {
+ "version": "11.2.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz",
+ "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^3.0.0"
+ }
+ }
+ }
+ },
+ "node-releases": {
+ "version": "2.0.14",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz",
+ "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
+ "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"
+ },
+ "dependencies": {
+ "semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true
+ }
+ }
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "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": "2.1.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
+ "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
+ "dev": true,
+ "requires": {
+ "boolbase": "^1.0.0"
+ }
+ },
+ "object-assign": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz",
+ "integrity": "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ==",
+ "dev": true
+ },
+ "object-inspect": {
+ "version": "1.13.1",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz",
+ "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==",
+ "dev": true
+ },
+ "object-is": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz",
+ "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.1.3"
+ }
+ },
+ "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.5",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz",
+ "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.5",
+ "define-properties": "^1.2.1",
+ "has-symbols": "^1.0.3",
+ "object-keys": "^1.1.1"
+ }
+ },
+ "object.entries": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.7.tgz",
+ "integrity": "sha512-jCBs/0plmPsOnrKAfFQXRG2NFjlhZgjjcBLSmTnEhU8U6vVTsVe8ANeQJCHTl3gSsI4J+0emOoCgoKlmQPMgmA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "object.fromentries": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.7.tgz",
+ "integrity": "sha512-UPbPHML6sL8PI/mOqPwsH4G6iyXcCGzLin8KvEPenOZN5lpCNBZZQ+V62vdjB1mQHrmqGQt5/OJzemUA+KJmEA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "object.values": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.7.tgz",
+ "integrity": "sha512-aU6xnDFYT3x17e/f0IiiwlGPTy2jzMySGfUB4fq6z7CV8l85CWHDk5ErhyhpfDHhrOMwGFhSQkhMGHaIotA6Ng==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "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": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "dev": true,
+ "requires": {
+ "wrappy": "1"
+ }
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "parse-json": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz",
+ "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==",
+ "dev": true,
+ "requires": {
+ "error-ex": "^1.3.1",
+ "json-parse-better-errors": "^1.0.1"
+ }
+ },
+ "parse5": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz",
+ "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==",
+ "dev": true,
+ "requires": {
+ "entities": "^4.4.0"
+ }
+ },
+ "parse5-htmlparser2-tree-adapter": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz",
+ "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==",
+ "dev": true,
+ "requires": {
+ "domhandler": "^5.0.2",
+ "parse5": "^7.0.0"
+ }
+ },
+ "parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "dev": true
+ },
+ "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": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
+ "dev": true
+ },
+ "path-key": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
+ "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==",
+ "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": "6.2.1",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.1.tgz",
+ "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==",
+ "dev": true
+ },
+ "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"
+ }
+ },
+ "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": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
+ "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.1",
+ "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.1.tgz",
+ "integrity": "sha512-qQbW94hLHEqCg7nhby4yRC7G2+jYHY4Rguc2bjw7Uug4GIJuu1tvf2uHaZv5Q8zdt+WKJ6qK1FOI6amaWUo5FA==",
+ "dev": true
+ },
+ "pify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz",
+ "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==",
+ "dev": true
+ },
+ "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"
+ },
+ "dependencies": {
+ "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"
+ }
+ },
+ "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"
+ }
+ },
+ "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"
+ }
+ }
+ }
+ },
+ "postcss": {
+ "version": "8.4.33",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.33.tgz",
+ "integrity": "sha512-Kkpbhhdjw2qQs2O2DGX+8m5OVqEcbB9HRBvuYM9pgrjEFUg30A9LmXNlTAUj4S9kgtGyrMbTzVjH7E+s5Re2yg==",
+ "dev": true,
+ "peer": true,
+ "requires": {
+ "nanoid": "^3.3.7",
+ "picocolors": "^1.0.0",
+ "source-map-js": "^1.0.2"
+ },
+ "dependencies": {
+ "nanoid": {
+ "version": "3.3.7",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz",
+ "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==",
+ "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"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
+ }
+ }
+ },
+ "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.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "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.11.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
+ "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
+ "dev": true,
+ "requires": {
+ "side-channel": "^1.0.4"
+ }
+ },
+ "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": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==",
+ "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.5.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
+ "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
+ "dev": true,
+ "requires": {
+ "bytes": "3.1.2",
+ "http-errors": "2.0.0",
+ "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": {
+ "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": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.8",
+ "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"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
+ }
+ }
+ },
+ "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": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
+ }
+ }
+ },
+ "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=="
+ },
+ "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": {
+ "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-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"
+ }
+ },
+ "read-pkg": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz",
+ "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==",
+ "dev": true,
+ "requires": {
+ "load-json-file": "^4.0.0",
+ "normalize-package-data": "^2.3.2",
+ "path-type": "^3.0.0"
+ }
+ },
+ "readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ }
+ },
+ "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"
+ }
+ },
+ "rechoir": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz",
+ "integrity": "sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==",
+ "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": "sha512-qOLsBKHCpSOFKK1NUOCGC5VyeufB6lEsFe92AL2bhIJsacZS1qdoOZSbPk3MYKuT2cFlRDnulKXuuElIrMjGUg==",
+ "dev": true
+ },
+ "regenerator-runtime": {
+ "version": "0.14.1",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
+ "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw=="
+ },
+ "regexp.prototype.flags": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.1.tgz",
+ "integrity": "sha512-sy6TXMN+hnP/wMy+ISxg3krXx7BAtWVO4UouuCN/ziM9UEne0euamVNafDfvC83bRNr95y0V5iijeDQFUNpvrg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "set-function-name": "^2.0.0"
+ }
+ },
+ "require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "dev": true
+ },
+ "requires-port": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
+ "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
+ "dev": true
+ },
+ "resolve": {
+ "version": "1.22.8",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz",
+ "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==",
+ "dev": true,
+ "requires": {
+ "is-core-module": "^2.13.0",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ }
+ },
+ "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"
+ }
+ },
+ "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": "sha512-nDG1rZeP6oFTLN6yNDV/uiAvs1+FS/KlrEwh7+y7dpuApDBy6bI2HTBcc0/V8lv9OTqfyD34eF7au2pm8aBbhA==",
+ "dev": true,
+ "requires": {
+ "lodash.flattendeep": "^4.4.0",
+ "nearley": "^2.7.10"
+ }
+ },
+ "safe-array-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.1.tgz",
+ "integrity": "sha512-6XbUAseYE2KtOuGueyeobCySj9L4+66Tn6KQMOPQJrAJEowYKW/YR/MGJZl7FdydUdaFu4LYyDZjxf4/Nmo23Q==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.1",
+ "has-symbols": "^1.0.3",
+ "isarray": "^2.0.5"
+ }
+ },
+ "safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "dev": true
+ },
+ "safe-regex-test": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.2.tgz",
+ "integrity": "sha512-83S9w6eFq12BBIJYvjMux6/dkirb8+4zJRA9cxNBVb7Wq5fJBW+Xze48WqR8pxua7bDuAaaAxtVVd4Idjp1dBQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.5",
+ "get-intrinsic": "^1.2.2",
+ "is-regex": "^1.1.4"
+ }
+ },
+ "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.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"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
+ }
+ }
+ },
+ "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.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "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"
+ }
+ },
+ "set-function-length": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.1.1.tgz",
+ "integrity": "sha512-VoaqjbBJKiWtg4yRcKBQ7g7wnGnLV3M8oLvVWwOk2PdYY6PEFegR1vezXR0tw6fZGF9csVakIRjrJiy2veSBFQ==",
+ "dev": true,
+ "requires": {
+ "define-data-property": "^1.1.1",
+ "get-intrinsic": "^1.2.1",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.0"
+ }
+ },
+ "set-function-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.1.tgz",
+ "integrity": "sha512-tMNCiqYVkXIZgc2Hnoy2IvC/f8ezc5koaRFkCjrpWzGpCd3qbZXPzVy9MAZzK1ch/X0jvSkojys3oqJN0qCmdA==",
+ "dev": true,
+ "requires": {
+ "define-data-property": "^1.0.1",
+ "functions-have-names": "^1.2.3",
+ "has-property-descriptors": "^1.0.0"
+ }
+ },
+ "setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "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": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==",
+ "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": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==",
+ "dev": true
+ },
+ "shell-quote": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz",
+ "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==",
+ "dev": true
+ },
+ "shelljs": {
+ "version": "0.8.5",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.5.tgz",
+ "integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.0.0",
+ "interpret": "^1.0.0",
+ "rechoir": "^0.6.2"
+ }
+ },
+ "side-channel": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
+ "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.0",
+ "get-intrinsic": "^1.0.2",
+ "object-inspect": "^1.9.0"
+ }
+ },
+ "signal-exit": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
+ "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.7.4",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.4.tgz",
+ "integrity": "sha512-DcotgfP1Zg9iP/dH9zvAQcWrE0TtbMVwXmlV4T4mqsvY+gw+LqUGPfx2AoVyRk0FLME+GQhufDMyacFmw7ksqw==",
+ "dev": true,
+ "requires": {
+ "accepts": "~1.3.4",
+ "base64id": "~2.0.0",
+ "cors": "~2.8.5",
+ "debug": "~4.3.2",
+ "engine.io": "~6.5.2",
+ "socket.io-adapter": "~2.5.2",
+ "socket.io-parser": "~4.2.4"
+ }
+ },
+ "socket.io-adapter": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz",
+ "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==",
+ "dev": true,
+ "requires": {
+ "ws": "~8.11.0"
+ }
+ },
+ "socket.io-parser": {
+ "version": "4.2.4",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
+ "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
+ "dev": true,
+ "requires": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.3.1"
+ }
+ },
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ },
+ "source-map-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"
+ }
+ },
+ "spdx-correct": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz",
+ "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==",
+ "dev": true,
+ "requires": {
+ "spdx-expression-parse": "^3.0.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "spdx-exceptions": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz",
+ "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==",
+ "dev": true
+ },
+ "spdx-expression-parse": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz",
+ "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==",
+ "dev": true,
+ "requires": {
+ "spdx-exceptions": "^2.1.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "spdx-license-ids": {
+ "version": "3.0.16",
+ "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.16.tgz",
+ "integrity": "sha512-eWN+LnM3GR6gPu35WxNgbGl8rmY1AEmoMDvL/QD6zYmPWgywxWqJWNdLGT+ke8dKNWrcYgYjPpG5gbTfghP8rw==",
+ "dev": true
+ },
+ "sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
+ "dev": true
+ },
+ "statuses": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
+ "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==",
+ "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"
+ }
+ },
+ "streamroller": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.1.5.tgz",
+ "integrity": "sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==",
+ "dev": true,
+ "requires": {
+ "date-format": "^4.0.14",
+ "debug": "^4.3.4",
+ "fs-extra": "^8.1.0"
+ }
+ },
+ "string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "dev": true,
+ "requires": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "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"
+ },
+ "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
+ },
+ "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"
+ }
+ }
+ }
+ },
+ "string.prototype.padend": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.1.5.tgz",
+ "integrity": "sha512-DOB27b/2UTTD+4myKUFh+/fXWcu/UDyASIXfg+7VzoCNNGOfWvoyU/x5pvVHr++ztyt/oSYI1BcWBBG/hmlNjA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "string.prototype.trim": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.8.tgz",
+ "integrity": "sha512-lfjY4HcixfQXOfaqCvcBuOIapyaroTXhbkfJN3gcB1OtyupngWK4sEET9Knd0cXd28kTUqu/kHoV4HKSJdnjiQ==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "string.prototype.trimend": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.7.tgz",
+ "integrity": "sha512-Ni79DqeB72ZFq1uH/L6zJ+DKZTkOtPIHovb3YZHQViE+HDouuU4mBrLOLDn5Dde3RF8qw5qVETEjhu9locMLvA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "string.prototype.trimstart": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.7.tgz",
+ "integrity": "sha512-NGhtDFu3jCEm7B4Fy0DpLewdJQOZcQ0rGbwQ/+stjnrp2i+rlKeCvos9hOIeCmqwratM47OBxY7uFZzjxHXmrg==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.2.0",
+ "es-abstract": "^1.22.1"
+ }
+ },
+ "strip-ansi": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
+ "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^3.0.0"
+ }
+ },
+ "strip-bom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
+ "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",
+ "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"
+ }
+ },
+ "supports-preserve-symlinks-flag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
+ "dev": true
+ },
+ "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.26.0",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.26.0.tgz",
+ "integrity": "sha512-dytTGoE2oHgbNV9nTzgBEPaqAWvcJNl66VZ0BkJqlvp71IjO8CxdBx/ykCNb47cLnCmCvRZ6ZR0tLkqvZCdVBQ==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/source-map": "^0.3.3",
+ "acorn": "^8.8.2",
+ "commander": "^2.20.0",
+ "source-map-support": "~0.5.20"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "8.11.3",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
+ "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
+ "dev": true
+ }
+ }
+ },
+ "terser-webpack-plugin": {
+ "version": "5.3.10",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.10.tgz",
+ "integrity": "sha512-BKFPWlPDndPs+NGGCr1U59t0XScL5317Y0UReNrHaw9/FwhPENlq6bfgs+4yPfyP51vqC1bQ4rp1EfXW5ZSH9w==",
+ "dev": true,
+ "requires": {
+ "@jridgewell/trace-mapping": "^0.3.20",
+ "jest-worker": "^27.4.5",
+ "schema-utils": "^3.1.1",
+ "serialize-javascript": "^6.0.1",
+ "terser": "^5.26.0"
+ },
+ "dependencies": {
+ "schema-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "dev": true,
+ "requires": {
+ "@types/json-schema": "^7.0.8",
+ "ajv": "^6.12.5",
+ "ajv-keywords": "^3.5.2"
+ }
+ },
+ "serialize-javascript": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
+ "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
+ "dev": true,
+ "requires": {
+ "randombytes": "^2.1.0"
+ }
+ }
+ }
+ },
+ "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": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
+ "dev": true
+ },
+ "to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "requires": {
+ "is-number": "^7.0.0"
+ }
+ },
+ "toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "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"
+ }
+ },
+ "typed-array-buffer": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.0.tgz",
+ "integrity": "sha512-Y8KTSIglk9OZEr8zywiIHG/kmQ7KWyjseXs1CbSo8vC42w7hg2HgYTxSWwP0+is7bWDc1H+Fo026CpHFwm8tkw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "get-intrinsic": "^1.2.1",
+ "is-typed-array": "^1.1.10"
+ }
+ },
+ "typed-array-byte-length": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.0.tgz",
+ "integrity": "sha512-Or/+kvLxNpeQ9DtSydonMxCx+9ZXOswtwJn17SNLvhptaXYDJvkFFP5zbfU/uLmvnBJlI4yrnXRxpdWH/M5tNA==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "has-proto": "^1.0.1",
+ "is-typed-array": "^1.1.10"
+ }
+ },
+ "typed-array-byte-offset": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.0.tgz",
+ "integrity": "sha512-RD97prjEt9EL8YgAgpOkf3O4IF9lhJFr9g0htQkm0rchFp/Vx7LW5Q8fSXXub7BXAODyUQohRMyOc3faCPd0hg==",
+ "dev": true,
+ "requires": {
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "has-proto": "^1.0.1",
+ "is-typed-array": "^1.1.10"
+ }
+ },
+ "typed-array-length": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.4.tgz",
+ "integrity": "sha512-KjZypGq+I/H7HI5HlOoGHkWUUGq+Q0TPhQurLbyrVrvnKTBgzLhIJ7j6J/XTQOi0d1RjyZ0wdas8bKs2p0x3Ng==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "for-each": "^0.3.3",
+ "is-typed-array": "^1.1.9"
+ }
+ },
+ "ua-parser-js": {
+ "version": "0.7.37",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.37.tgz",
+ "integrity": "sha512-xV8kqRKM+jhMvcHWUKthV9fNebIzrNy//2O9ZwWcfiBFR5f25XVZPLlEajk/sf3Ra15V92isyQqnIEXRDaZWEA==",
+ "dev": true
+ },
+ "unbox-primitive": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz",
+ "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==",
+ "dev": true,
+ "requires": {
+ "call-bind": "^1.0.2",
+ "has-bigints": "^1.0.2",
+ "has-symbols": "^1.0.3",
+ "which-boxed-primitive": "^1.0.2"
+ }
+ },
+ "undici-types": {
+ "version": "5.26.5",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
+ "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": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "dev": true
+ },
+ "update-browserslist-db": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz",
+ "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==",
+ "dev": true,
+ "requires": {
+ "escalade": "^3.1.1",
+ "picocolors": "^1.0.0"
+ }
+ },
+ "uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "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": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==",
+ "dev": true
+ }
+ }
+ },
+ "util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "dev": true
+ },
+ "utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
+ "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": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "dev": true
+ },
+ "void-elements": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz",
+ "integrity": "sha512-qZKX4RnBzH2ugr8Lxa7x+0V6XD9Sb/ouARtiasEQCHB1EVU4NXtmHsDDrx1dO4ne5fc3J6EW05BP1Dl0z0iung==",
+ "dev": true
+ },
+ "watchpack": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz",
+ "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==",
+ "dev": true,
+ "requires": {
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.1.2"
+ }
+ },
+ "webpack": {
+ "version": "5.89.0",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.89.0.tgz",
+ "integrity": "sha512-qyfIC10pOr70V+jkmud8tMfajraGCZMBWJtrmuBymQKCrLTRejBI8STDp1MCyZu/QTdZSeacCQYpYNQVOzX5kw==",
+ "dev": true,
+ "requires": {
+ "@types/eslint-scope": "^3.7.3",
+ "@types/estree": "^1.0.0",
+ "@webassemblyjs/ast": "^1.11.5",
+ "@webassemblyjs/wasm-edit": "^1.11.5",
+ "@webassemblyjs/wasm-parser": "^1.11.5",
+ "acorn": "^8.7.1",
+ "acorn-import-assertions": "^1.9.0",
+ "browserslist": "^4.14.5",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^5.15.0",
+ "es-module-lexer": "^1.2.1",
+ "eslint-scope": "5.1.1",
+ "events": "^3.2.0",
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.2.9",
+ "json-parse-even-better-errors": "^2.3.1",
+ "loader-runner": "^4.2.0",
+ "mime-types": "^2.1.27",
+ "neo-async": "^2.6.2",
+ "schema-utils": "^3.2.0",
+ "tapable": "^2.1.1",
+ "terser-webpack-plugin": "^5.3.7",
+ "watchpack": "^2.4.0",
+ "webpack-sources": "^3.2.3"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "8.11.3",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
+ "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
+ "dev": true
+ },
+ "schema-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz",
+ "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==",
+ "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.10.0",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.10.0.tgz",
+ "integrity": "sha512-+4zXKdx7UnO+1jaN4l2lHVD+mFvnlZQP/6ljaJVb4SZiwIKeUnrT5l0gkT8z+n4hKpC+jpOv6O9R+gLtag7pSA==",
+ "dev": true,
+ "requires": {
+ "clone-deep": "^4.0.1",
+ "flat": "^5.0.2",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz",
+ "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==",
+ "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"
+ }
+ },
+ "which-boxed-primitive": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz",
+ "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==",
+ "dev": true,
+ "requires": {
+ "is-bigint": "^1.0.1",
+ "is-boolean-object": "^1.1.0",
+ "is-number-object": "^1.0.4",
+ "is-string": "^1.0.5",
+ "is-symbol": "^1.0.3"
+ }
+ },
+ "which-typed-array": {
+ "version": "1.1.13",
+ "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.13.tgz",
+ "integrity": "sha512-P5Nra0qjSncduVPEAr7xhoF5guty49ArDTwzJ/yNuPIbZppyRxFQsRCWrocxIY+CnMVG+qfbU2FmDKyvSGClow==",
+ "dev": true,
+ "requires": {
+ "available-typed-arrays": "^1.0.5",
+ "call-bind": "^1.0.4",
+ "for-each": "^0.3.3",
+ "gopd": "^1.0.1",
+ "has-tostringtag": "^1.0.0"
+ }
+ },
+ "wildcard": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz",
+ "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==",
+ "dev": true
+ },
+ "workerpool": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz",
+ "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==",
+ "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
+ },
+ "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": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "dev": true
+ },
+ "ws": {
+ "version": "8.11.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
+ "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
+ "dev": true,
+ "requires": {}
+ },
+ "y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "dev": true
+ },
+ "yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "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"
+ },
+ "dependencies": {
+ "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"
+ }
+ }
+ }
+ },
+ "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"
+ },
+ "dependencies": {
+ "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"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ },
+ "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
+ },
+ "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..b878deb975
--- /dev/null
+++ b/browser/components/newtab/package.json
@@ -0,0 +1,115 @@
+{
+ "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.23.5",
+ "@babel/preset-react": "7.23.3",
+ "@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",
+ "enzyme": "3.11.0",
+ "enzyme-adapter-react-16": "1.15.6",
+ "joi-browser": "13.4.0",
+ "karma": "6.4.2",
+ "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.1",
+ "lodash": "4.17.21",
+ "mocha": "9.2.2",
+ "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",
+ "rimraf": "3.0.2",
+ "sass": "1.43.4",
+ "shelljs": "0.8.5",
+ "sinon": "12.0.1",
+ "stream-browserify": "3.0.0",
+ "util": "0.10.4",
+ "webpack": "5.89.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: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",
+ "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",
+ "try": "node ./bin/try-runner.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..f23bc84833
--- /dev/null
+++ b/browser/components/newtab/pings.yaml
@@ -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/.
+
+---
+$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
+
+top-sites:
+ description: |
+ A ping representing a single event happening with or to a TopSite.
+ Distinguishable by its `ping_type`.
+ Does not contain a `client_id`, preferring a `context_id` instead.
+ include_client_id: false
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1836283
+ notification_emails:
+ - najiang@mozilla.com
+
+spoc:
+ description: |
+ A ping for submitting the pocket sponsored content's `shim`.
+ Does not contain a `client_id`.
+ include_client_id: false
+ reasons:
+ impression: A sponsored story was impressed upon the client.
+ click: A sponsored story was clicked.
+ save: A sponsored story was saved to Pocket.
+ bugs:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1862670
+ notification_emails:
+ - najiang@mozilla.com
+ - chutten@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..b87303eb58
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-debug.html
@@ -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/. -->
+
+<!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://global/skin/design-system/tokens-brand.css"
+ />
+ <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>
+ <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>
+ <script
+ async
+ type="module"
+ src="chrome://global/content/elements/moz-toggle.mjs"
+ ></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..8186565ef3
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-noscripts.html
@@ -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/. -->
+
+<!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://global/skin/design-system/tokens-brand.css"
+ />
+ <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>
+ <script
+ async
+ type="module"
+ src="chrome://global/content/elements/moz-toggle.mjs"
+ ></script>
+ </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..86e7f292d8
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream.html
@@ -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/. -->
+
+<!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://global/skin/design-system/tokens-brand.css"
+ />
+ <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>
+ <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>
+ <script
+ async
+ type="module"
+ src="chrome://global/content/elements/moz-toggle.mjs"
+ ></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser.toml b/browser/components/newtab/test/browser/abouthomecache/browser.toml
new file mode 100644
index 0000000000..1994415d9a
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser.toml
@@ -0,0 +1,52 @@
+[DEFAULT]
+support-files = [
+ "head.js",
+ "../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.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..d3bfa383c2
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js
@@ -0,0 +1,82 @@
+/* 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;
+
+ // eslint-disable-next-line @microsoft/sdl/no-insecure-url
+ 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..b1600bfe00
--- /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.importESModule(
+ "resource:///modules/AboutNewTabService.sys.mjs"
+ );
+ 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..5599b2bd10
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/head.js
@@ -0,0 +1,365 @@
+/* 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"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+const { DiscoveryStreamFeed } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/DiscoveryStreamFeed.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.importESModule(
+ "resource://activity-stream/lib/ActivityStream.sys.mjs"
+ );
+
+ let defaultDSConfig = JSON.parse(
+ PREFS_CONFIG.get("discoverystream.config").getValue({
+ geo: "US",
+ locale: "en-US",
+ })
+ );
+
+ // 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(defaultDSConfig)
+ );
+}
+
+/**
+ * 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}
+ */
+function withFullyLoadedAboutHome(taskFn) {
+ const sandbox = sinon.createSandbox();
+ sandbox
+ .stub(DiscoveryStreamFeed.prototype, "generateFeedUrl")
+ .returns(
+ "https://example.com/browser/browser/components/newtab/test/browser/topstories.json"
+ );
+
+ 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);
+ sandbox.restore();
+ });
+}
+
+/**
+ * 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.
+ */
+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.importESModule(
+ "resource:///modules/AboutNewTabService.sys.mjs"
+ );
+ 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.importESModule(
+ "resource:///modules/AboutNewTabService.sys.mjs"
+ );
+ 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.startLoadingURIString(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.
+ */
+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.
+ */
+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.
+ */
+async function ensureCachedAboutHome(browser) {
+ await SpecialPowers.spawn(browser, [], async () => {
+ let syncScripts = Array.from(
+ content.document.querySelectorAll("script:not([type='module'])")
+ );
+ Assert.ok(!!syncScripts.length, "There should be page scripts.");
+ let [lastSyncScript] = syncScripts.reverse();
+ Assert.equal(
+ lastSyncScript.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.
+ */
+async function ensureDynamicAboutHome(browser, expectedResultScalar) {
+ await SpecialPowers.spawn(browser, [], async () => {
+ let syncScripts = Array.from(
+ content.document.querySelectorAll("script:not([type='module'])")
+ );
+ Assert.equal(syncScripts.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.toml b/browser/components/newtab/test/browser/browser.toml
new file mode 100644
index 0000000000..f9c9611c2e
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser.toml
@@ -0,0 +1,81 @@
+[DEFAULT]
+support-files = [
+ "blue_page.html",
+ "red_page.html",
+ "annotation_first.html",
+ "annotation_second.html",
+ "annotation_third.html",
+ "head.js",
+ "redirect_to.sjs",
+ "topstories.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",
+]
+
+["browser_as_load_location.js"]
+
+["browser_as_render.js"]
+
+["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_enabled_newtabpage.js"]
+
+["browser_foxdoodle_set_default.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_glean.js"]
+
+["browser_newtab_header.js"]
+
+["browser_newtab_last_LinkMenu.js"]
+
+["browser_newtab_overrides.js"]
+
+["browser_newtab_ping.js"]
+
+["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' && debug", # Bug 1785005
+ "os == 'linux' && asan", # Bug 1785005
+]
+
+["browser_topsites_contextMenu_options.js"]
+
+["browser_topsites_section.js"]
+
+["browser_trigger_messagesLoaded.js"]
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_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..ba83f1ff0a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_content.js
@@ -0,0 +1,219 @@
+"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() {
+ function getSection(sectionIdentifier) {
+ return content.document.querySelector(
+ `section[data-section-id="${sectionIdentifier}"]`
+ );
+ }
+ function promiseSectionShown(sectionIdentifier) {
+ return ContentTaskUtils.waitForMutationCondition(
+ content.document.querySelector("main"),
+ { childList: true, subtree: true },
+ () => getSection(sectionIdentifier)
+ );
+ }
+ 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.
+ //
+ // We waive XRay wrappers because we want to call the click()
+ // method defined on the toggle from this context.
+ let shortcutsSwitch = Cu.waiveXrays(
+ content.document.querySelector("#shortcuts-section moz-toggle")
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(TOPSITES_PREF),
+ "Topsites are turned off"
+ );
+ Assert.ok(!getSection("topsites"), "Shortcuts section is not rendered");
+
+ let sectionShownPromise = promiseSectionShown("topsites");
+ shortcutsSwitch.click();
+ await sectionShownPromise;
+
+ Assert.ok(getSection("topsites"), "Shortcuts section is rendered");
+
+ // Test that clicking the pocket toggle will make the pocket section
+ // appear on the newtab page
+ //
+ // We waive XRay wrappers because we want to call the click()
+ // method defined on the toggle from this context.
+ let pocketSwitch = Cu.waiveXrays(
+ content.document.querySelector("#pocket-section moz-toggle")
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(TOPSTORIES_PREF),
+ "Pocket pref is turned off"
+ );
+ Assert.ok(!getSection("topstories"), "Pocket section is not rendered");
+
+ sectionShownPromise = promiseSectionShown("topstories");
+ pocketSwitch.click();
+ await sectionShownPromise;
+
+ Assert.ok(getSection("topstories"), "Pocket section is rendered");
+
+ // Test that clicking the recent activity toggle will make the
+ // recent activity section appear on the newtab page.
+ //
+ // We waive XRay wrappers because we want to call the click()
+ // method defined on the toggle from this context.
+ let highlightsSwitch = Cu.waiveXrays(
+ content.document.querySelector("#recent-section moz-toggle")
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(HIGHLIGHTS_PREF),
+ "Highlights pref is turned off"
+ );
+ Assert.ok(!getSection("highlights"), "Highlights section is not rendered");
+
+ sectionShownPromise = promiseSectionShown("highlights");
+ highlightsSwitch.click();
+ await sectionShownPromise;
+
+ Assert.ok(getSection("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..6ebd0de7d1
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_render.js
@@ -0,0 +1,28 @@
+"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)";
+ Assert.notStrictEqual(
+ 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..fa90682089
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_discovery_card.js
@@ -0,0 +1,49 @@
+// If this fails it could be because of schema changes.
+// `topstories.json` defines the stories shown
+test_newtab({
+ async before({ pushPrefs }) {
+ sinon
+ .stub(DiscoveryStreamFeed.prototype, "generateFeedUrl")
+ .returns(
+ "https://example.com/browser/browser/components/newtab/test/browser/topstories.json"
+ );
+ await pushPrefs(
+ [
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ api_key_pref: "extensions.pocket.oAuthConsumerKey",
+ collapsible: true,
+ enabled: true,
+ personalized: true,
+ }),
+ ],
+ [
+ "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 cardPublisher = content.document.querySelector(
+ "[data-section-id='topstories'] .source"
+ ).innerText;
+ is(
+ cardPublisher,
+ "bbc",
+ `Card publisher is ${cardPublisher} instead of bbc`
+ );
+ },
+ async after() {
+ sinon.restore();
+ },
+});
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..44ca5b466a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_discovery_render.js
@@ -0,0 +1,31 @@
+"use strict";
+
+async function before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ collapsible: true,
+ enabled: 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_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_foxdoodle_set_default.js b/browser/components/newtab/test/browser/browser_foxdoodle_set_default.js
new file mode 100644
index 0000000000..7c53ba6b9a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_foxdoodle_set_default.js
@@ -0,0 +1,69 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { ASRouter } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ASRouter.sys.mjs"
+);
+
+const { ASRouterTargeting } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ASRouterTargeting.sys.mjs"
+);
+
+const { OnboardingMessageProvider } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/OnboardingMessageProvider.sys.mjs"
+);
+
+async function waitForClick(selector, win) {
+ await TestUtils.waitForCondition(() => win.document.querySelector(selector));
+ win.document.querySelector(selector).click();
+}
+add_task(async function test_foxdoodle_spotlight() {
+ const sandbox = sinon.createSandbox();
+
+ let promise = TestUtils.topicObserved("subdialog-loaded");
+ let message = (await OnboardingMessageProvider.getMessages()).find(
+ m => m.id === "FOX_DOODLE_SET_DEFAULT"
+ );
+
+ Assert.ok(message, "Message exists.");
+
+ let routedMessage = ASRouter.routeCFRMessage(
+ message,
+ gBrowser,
+ undefined,
+ false
+ );
+
+ Assert.ok(
+ JSON.stringify(routedMessage) === JSON.stringify({ message: {} }),
+ "Message is not routed when skipInTests is truthy and ID is not present in messagesEnabledInAutomation"
+ );
+
+ sandbox
+ .stub(ASRouter, "messagesEnabledInAutomation")
+ .value(["FOX_DOODLE_SET_DEFAULT"]);
+
+ routedMessage = ASRouter.routeCFRMessage(message, gBrowser, undefined, false);
+ Assert.ok(
+ JSON.stringify(routedMessage.message) === JSON.stringify(message),
+ "Message is routed when skipInTests is truthy and ID is present in messagesEnabledInAutomation"
+ );
+
+ delete message.skipInTests;
+ let unskippedRoutedMessage = ASRouter.routeCFRMessage(
+ message,
+ gBrowser,
+ undefined,
+ false
+ );
+ Assert.ok(
+ unskippedRoutedMessage,
+ "Message is routed when skipInTests property is falsy"
+ );
+ let [win] = await promise;
+ await waitForClick("button.dismiss-button", win);
+ win.close();
+ 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..43e5ec4655
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_getScreenshots.js
@@ -0,0 +1,88 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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";
+
+const { Screenshots } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/Screenshots.sys.mjs"
+);
+
+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..96f655b668
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_multistage_spotlight.js
@@ -0,0 +1,90 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { Spotlight } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/Spotlight.sys.mjs"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/PanelTestProvider.sys.mjs"
+);
+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() {
+ const sandbox = sinon.createSandbox();
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "MULTISTAGE_SPOTLIGHT_MESSAGE"
+ );
+ let dispatchStub = sandbox.stub();
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let specialActionStub = sandbox.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"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_embedded_import() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.migrate.internal-testing.enabled", true]],
+ });
+ let message = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "IMPORT_SETTINGS_EMBEDDED"
+ );
+ let browser = BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
+ let win = await showDialog({ message, browser });
+ let migrationWizardReady = BrowserTestUtils.waitForEvent(
+ win,
+ "MigrationWizard:Ready"
+ );
+
+ await TestUtils.waitForCondition(() =>
+ win.document.querySelector("migration-wizard")
+ );
+ Assert.ok(
+ win.document.querySelector("migration-wizard"),
+ "Migration Wizard rendered"
+ );
+
+ await migrationWizardReady;
+
+ let panelList = win.document
+ .querySelector("migration-wizard")
+ .openOrClosedShadowRoot.querySelector("panel-list");
+ Assert.equal(panelList.tagName, "PANEL-LIST");
+ Assert.equal(panelList.firstChild.tagName, "PANEL-ITEM");
+
+ win.close();
+ await SpecialPowers.popPrefEnv();
+});
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..03eb6caddd
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_multistage_spotlight_telemetry.js
@@ -0,0 +1,141 @@
+"use strict";
+
+const { Spotlight } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/Spotlight.sys.mjs"
+);
+const { PanelTestProvider } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/PanelTestProvider.sys.mjs"
+);
+
+const { AboutWelcomeTelemetry } = ChromeUtils.importESModule(
+ "resource:///modules/aboutwelcome/AboutWelcomeTelemetry.sys.mjs"
+);
+
+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();
+ });
+
+ // Let's collect all "messaging-system" pings submitted in this test.
+ let pingContents = [];
+ let onSubmit = () => {
+ pingContents.push({
+ messageId: Glean.messagingSystem.messageId.testGetValue(),
+ event: Glean.messagingSystem.event.testGetValue(),
+ });
+ GleanPings.messagingSystem.testBeforeNextSubmit(onSubmit);
+ };
+ GleanPings.messagingSystem.testBeforeNextSubmit(onSubmit);
+
+ 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();
+ let spy = sandbox.spy(AboutWelcomeTelemetry.prototype, "sendTelemetry");
+ // send without a dispatch function so that default is used
+ await showAndWaitForDialog({ message, browser }, async win => {
+ await waitForClick("button.dismiss-button", win);
+ await win.close();
+ });
+
+ 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.greater(
+ pingContents.length,
+ 0,
+ "Glean 'messaging-system' pings were submitted."
+ );
+ Assert.ok(
+ pingContents.some(ping => {
+ return ping.messageId === messageId && ping.event === "DISMISS";
+ }),
+ "A Glean 'messaging-system' ping was sent for the correct message+event."
+ );
+
+ // Tidy up by removing the self-referential test callback.
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {});
+ 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_glean.js b/browser/components/newtab/test/browser/browser_newtab_glean.js
new file mode 100644
index 0000000000..7d40868f2c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_glean.js
@@ -0,0 +1,28 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+requestLongerTimeout(10);
+
+const TELEMETRY_PREF =
+ "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar";
+
+add_task(async function test_newtab_handoff_performance_telemetry() {
+ await SpecialPowers.pushPrefEnv({
+ set: [[TELEMETRY_PREF, true]],
+ });
+
+ Services.fog.testResetFOG();
+ let TelemetryFeed =
+ AboutNewTab.activityStream.store.feeds.get("feeds.telemetry");
+ TelemetryFeed.init(); // INIT action doesn't happen by default.
+
+ Assert.equal(true, Glean.newtabHandoffPreference.enabled.testGetValue());
+
+ await SpecialPowers.pushPrefEnv({
+ set: [[TELEMETRY_PREF, false]],
+ });
+ Assert.equal(false, Glean.newtabHandoffPreference.enabled.testGetValue());
+ await SpecialPowers.popPrefEnv();
+});
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..d9264fdf7c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_last_LinkMenu.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function setupPrefs() {
+ sinon
+ .stub(DiscoveryStreamFeed.prototype, "generateFeedUrl")
+ .returns(
+ "https://example.com/browser/browser/components/newtab/test/browser/topstories.json"
+ );
+ await setDefaultTopSites();
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ api_key_pref: "extensions.pocket.oAuthConsumerKey",
+ collapsible: true,
+ enabled: true,
+ personalized: false,
+ }),
+ ],
+ [
+ "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);
+ sinon.restore();
+});
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..1d4a0c36e3
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_overrides.js
@@ -0,0 +1,134 @@
+"use strict";
+
+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..009305eb7a
--- /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";
+requestLongerTimeout(5);
+
+const { ASRouter } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ASRouter.sys.mjs"
+);
+
+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());
+ // Sponsored topsites are turned off in tests to avoid making remote requests.
+ 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());
+ // Sponsored topsites are turned off in tests to avoid making remote requests.
+ 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.startLoadingURIString(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.startLoadingURIString(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..b18da77ec6
--- /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.importESModule(
+ "resource:///modules/asrouter/ASRouter.sys.mjs"
+);
+
+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..265d713371
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_open_tab_focus.js
@@ -0,0 +1,38 @@
+/* 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
+ );
+
+ Assert.strictEqual(
+ 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..5c919357f4
--- /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:///modules/asrouter/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..df569628d1
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_section.js
@@ -0,0 +1,304 @@
+"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");
+ Assert.greaterOrEqual(
+ 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");
+ Assert.greaterOrEqual(
+ 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_messagesLoaded.js b/browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js
new file mode 100644
index 0000000000..a076f9178e
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_trigger_messagesLoaded.js
@@ -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/. */
+
+const { ASRouter } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ASRouter.sys.mjs"
+);
+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://activity-stream/content/data/content/assets/glyph-webextension-16.svg",
+ icon_dark_theme:
+ "chrome://activity-stream/content/data/content/assets/glyph-webextension-16.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/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..1dbae8af02
--- /dev/null
+++ b/browser/components/newtab/test/browser/head.js
@@ -0,0 +1,244 @@
+"use strict";
+
+ChromeUtils.defineESModuleGetters(this, {
+ ASRouter: "resource:///modules/asrouter/ASRouter.sys.mjs",
+
+ DiscoveryStreamFeed:
+ "resource://activity-stream/lib/DiscoveryStreamFeed.sys.mjs",
+
+ FeatureCallout: "resource:///modules/asrouter/FeatureCallout.sys.mjs",
+
+ FeatureCalloutBroker:
+ "resource:///modules/asrouter/FeatureCalloutBroker.sys.mjs",
+
+ FeatureCalloutMessages:
+ "resource:///modules/asrouter/FeatureCalloutMessages.sys.mjs",
+
+ ObjectUtils: "resource://gre/modules/ObjectUtils.sys.mjs",
+ PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
+ QueryCache: "resource:///modules/asrouter/ASRouterTargeting.sys.mjs",
+});
+
+// We import sinon here to make it available across all mochitest test files
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+
+function popPrefs() {
+ return SpecialPowers.popPrefEnv();
+}
+function pushPrefs(...prefs) {
+ return SpecialPowers.pushPrefEnv({ set: prefs });
+}
+
+// Toggle the feed off and on as a workaround to read the new prefs.
+async function toggleTopsitesPref() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.feeds.system.topsites",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.feeds.system.topsites",
+ true,
+ ]);
+}
+
+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,
+ ]);
+}
+
+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();
+}
+
+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 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.
+ */
+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
+ */
+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
+ BrowserTestUtils.removeTab(tab);
+ await scopedPopPrefs();
+ }
+ };
+
+ // 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/topstories.json b/browser/components/newtab/test/browser/topstories.json
new file mode 100644
index 0000000000..0c27dfe1a2
--- /dev/null
+++ b/browser/components/newtab/test/browser/topstories.json
@@ -0,0 +1,11 @@
+{
+ "data": [
+ {
+ "tileId": 53093,
+ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA/UlEQVR4nO3RMQ0AMAzAsPIn3d5DsBw2gkiZJWV+B/AyJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQmAP4K6zWNUjE4wAAAABJRU5ErkJggg==",
+ "publisher": "bbc",
+ "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."
+ }
+ ]
+}
diff --git a/browser/components/newtab/test/schemas/asrouter_event_ping.schema.json b/browser/components/newtab/test/schemas/asrouter_event_ping.schema.json
new file mode 100644
index 0000000000..6ad4f86541
--- /dev/null
+++ b/browser/components/newtab/test/schemas/asrouter_event_ping.schema.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "browser/components/newtab/test/schemas/asrouter_event_ping.schema.json",
+ "title": "ASRouter event PingCentre ping",
+ "type": "object",
+ "properties": {
+ "addon_version": {
+ "type": "string"
+ },
+ "locale": {
+ "type": "string"
+ },
+ "message_id": {
+ "type": "string"
+ },
+ "event": {
+ "type": "string"
+ },
+ "client_id": {
+ "type": "string"
+ },
+ "impression_id": {
+ "type": "string"
+ }
+ },
+ "required": ["addon_version", "locale", "message_id", "event"],
+ "additionalProperties": false,
+ "anyOf": [
+ {
+ "required": ["client_id"]
+ },
+ {
+ "required": ["impression_id"]
+ }
+ ]
+}
diff --git a/browser/components/newtab/test/schemas/base_ping.schema.json b/browser/components/newtab/test/schemas/base_ping.schema.json
new file mode 100644
index 0000000000..bf355b0c16
--- /dev/null
+++ b/browser/components/newtab/test/schemas/base_ping.schema.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "browser/components/newtab/test/schemas/base_ping.schema.json",
+ "title": "Base PingCentre ping",
+ "type": "object",
+ "properties": {
+ "client_id": {
+ "type": "string"
+ },
+ "addon_version": {
+ "type": "string"
+ },
+ "locale": {
+ "type": "string"
+ },
+ "session_id": {
+ "type": "string"
+ },
+ "page": {
+ "type": ["array", "boolean", "number", "object", "string", "null"],
+ "enum": ["about:home", "about:newtab", "about:welcome", "both", "unknown"]
+ },
+ "user_prefs": {
+ "type": "integer"
+ }
+ },
+ "required": ["addon_version", "locale", "user_prefs"],
+ "additionalProperties": true
+}
diff --git a/browser/components/newtab/test/schemas/pings.js b/browser/components/newtab/test/schemas/pings.js
new file mode 100644
index 0000000000..825083066e
--- /dev/null
+++ b/browser/components/newtab/test/schemas/pings.js
@@ -0,0 +1,181 @@
+import {
+ CONTENT_MESSAGE_TYPE,
+ MAIN_MESSAGE_TYPE,
+} from "common/Actions.sys.mjs";
+import Joi from "joi-browser";
+
+export const baseKeys = {
+ 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 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 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 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/schemas/session_ping.schema.json b/browser/components/newtab/test/schemas/session_ping.schema.json
new file mode 100644
index 0000000000..23e418fff7
--- /dev/null
+++ b/browser/components/newtab/test/schemas/session_ping.schema.json
@@ -0,0 +1,122 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "browser/components/newtab/test/schemas/session_ping.schema.json",
+ "title": "Session PingCentre ping",
+ "type": "object",
+ "properties": {
+ "client_id": {
+ "type": "string"
+ },
+ "addon_version": {
+ "type": "string"
+ },
+ "locale": {
+ "type": "string"
+ },
+ "session_id": {
+ "type": "string"
+ },
+ "page": {
+ "type": "string",
+ "enum": ["about:home", "about:newtab", "about:welcome", "both", "unknown"]
+ },
+ "user_prefs": {
+ "type": "integer"
+ },
+ "session_duration": {
+ "type": "integer"
+ },
+ "action": {
+ "type": "string",
+ "enum": ["activity_stream_session"]
+ },
+ "profile_creation_date": {
+ "type": "integer"
+ },
+ "perf": {
+ "type": "object",
+ "properties": {
+ "highlights_data_late_by_ms": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "description": "How long it took in ms for data to be ready for display."
+ },
+ "load_trigger_ts": {
+ "type": "integer",
+ "description": "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_type": {
+ "type": "string",
+ "enum": [
+ "first_window_opened",
+ "menu_plus_or_keyboard",
+ "unexpected"
+ ],
+ "description": "What was the perceived trigger of the load action? Not required at least for the error cases where the observer event doesn't fire."
+ },
+ "topsites_data_late_by_ms": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "description": "How long it took in ms for data to be ready for display."
+ },
+ "topsites_first_painted_ts": {
+ "type": "integer",
+ "description": "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_icon_stats": {
+ "type": "object",
+ "properties": {
+ "custom_screenshot": {
+ "type": "number"
+ },
+ "rich_icon": {
+ "type": "number"
+ },
+ "screenshot": {
+ "type": "number"
+ },
+ "screenshot_with_icon": {
+ "type": "number"
+ },
+ "tippytop": {
+ "type": "number"
+ },
+ "no_image": {
+ "type": "number"
+ }
+ },
+ "additionalProperties": false,
+ "description": "Information about the quality of TopSites images and icons."
+ },
+ "topsites_pinned": {
+ "type": "number",
+ "description": "The count of pinned Top Sites."
+ },
+ "topsites_search_shortcuts": {
+ "type": "number",
+ "description": "The count of search shortcut Top Sites."
+ },
+ "visibility_event_rcvd_ts": {
+ "type": "integer",
+ "description": "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)."
+ },
+ "is_preloaded": {
+ "type": "boolean",
+ "description": "The boolean to signify whether the page is preloaded or not."
+ }
+ },
+ "required": ["load_trigger_type", "is_preloaded"],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "addon_version",
+ "locale",
+ "session_id",
+ "page",
+ "user_prefs",
+ "action",
+ "perf"
+ ],
+ "additionalProperties": false
+}
diff --git a/browser/components/newtab/test/schemas/user_event_ping.schema.json b/browser/components/newtab/test/schemas/user_event_ping.schema.json
new file mode 100644
index 0000000000..5b39006b85
--- /dev/null
+++ b/browser/components/newtab/test/schemas/user_event_ping.schema.json
@@ -0,0 +1,75 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "browser/components/newtab/test/schemas/user_event_ping.schema.json",
+ "title": "User event PingCentre ping",
+ "type": "object",
+ "properties": {
+ "client_id": {
+ "type": "string"
+ },
+ "addon_version": {
+ "type": "string"
+ },
+ "locale": {
+ "type": "string"
+ },
+ "session_id": {
+ "type": "string"
+ },
+ "page": {
+ "type": "string",
+ "enum": ["about:home", "about:newtab", "about:welcome", "both", "unknown"]
+ },
+ "user_prefs": {
+ "type": "integer"
+ },
+ "source": {
+ "type": "string"
+ },
+ "event": {
+ "type": "string"
+ },
+ "action": {
+ "type": "string",
+ "enum": ["activity_stream_user_event"]
+ },
+ "metadata_source": {
+ "type": "string"
+ },
+ "highlight_type": {
+ "type": "string",
+ "enum": ["bookmarks", "recommendation", "history"]
+ },
+ "recommender_type": {
+ "type": "string"
+ },
+ "value": {
+ "type": "object",
+ "properties": {
+ "newtab_url_category": {
+ "type": "string"
+ },
+ "newtab_extension_id": {
+ "type": "string"
+ },
+ "home_url_category": {
+ "type": "string"
+ },
+ "home_extension_id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "addon_version",
+ "locale",
+ "session_id",
+ "page",
+ "user_prefs",
+ "event",
+ "action"
+ ],
+ "additionalProperties": false
+}
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..7343fc6224
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Reducers.test.js
@@ -0,0 +1,1525 @@
+import { INITIAL_STATE, insertPinned, reducers } from "common/Reducers.sys.mjs";
+const {
+ TopSites,
+ App,
+ 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 set sov positions and state", () => {
+ const positions = [
+ { position: 0, assignedPartner: "amp" },
+ { position: 1, assignedPartner: "moz-sales" },
+ ];
+ const nextState = TopSites(undefined, {
+ type: at.SOV_UPDATED,
+ data: { ready: true, positions },
+ });
+ assert.equal(nextState.sov.ready, true);
+ assert.equal(nextState.sov.positions, positions);
+ });
+ });
+ 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]);
+ });
+ });
+ 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("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"] },
+ });
+ assert.equal(state.layout[0], "test");
+ });
+ 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/Base.test.jsx b/browser/components/newtab/test/unit/content-src/components/Base.test.jsx
new file mode 100644
index 0000000000..c764348006
--- /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 { DiscoveryStreamAdmin } from "content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin";
+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 DiscoveryStreamAdmin if the devtools pref is true", () => {
+ const wrapper = shallow(
+ <Base
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { "asrouter.devtoolsEnabled": true } }}
+ />
+ );
+ assert.lengthOf(wrapper.find(DiscoveryStreamAdmin), 1);
+ });
+
+ it("should not render an DiscoveryStreamAdmin if the devtools pref is false", () => {
+ const wrapper = shallow(
+ <Base
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { "asrouter.devtoolsEnabled": false } }}
+ />
+ );
+ assert.lengthOf(wrapper.find(DiscoveryStreamAdmin), 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..e1f84f7d84
--- /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 a data-eventSource attribute and dispatch an event for INPUT", () => {
+ wrapper.instance().onPreferenceSelect({
+ target: {
+ nodeName: "INPUT",
+ checked: true,
+ dataset: { preference: "foo", eventSource: "bar" },
+ },
+ });
+
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch,
+ ac.UserEvent({
+ event: "PREF_CHANGED",
+ source: "bar",
+ value: { status: true, menu_source: "CUSTOMIZE_MENU" },
+ })
+ );
+ assert.calledWith(DEFAULT_PROPS.setPref, "foo", true);
+ wrapper.unmount();
+ });
+
+ it("should have data-eventSource attributes on relevent pref changing inputs", () => {
+ wrapper = mount(<ContentSection {...DEFAULT_PROPS} />);
+ assert.equal(
+ wrapper.find("#shortcuts-toggle").prop("data-eventSource"),
+ "TOP_SITES"
+ );
+ assert.equal(
+ wrapper.find("#sponsored-shortcuts").prop("data-eventSource"),
+ "SPONSORED_TOP_SITES"
+ );
+ assert.equal(
+ wrapper.find("#pocket-toggle").prop("data-eventSource"),
+ "TOP_STORIES"
+ );
+ assert.equal(
+ wrapper.find("#sponsored-pocket").prop("data-eventSource"),
+ "POCKET_SPOCS"
+ );
+ assert.equal(
+ wrapper.find("#highlights-toggle").prop("data-eventSource"),
+ "HIGHLIGHTS"
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamAdmin.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamAdmin.test.jsx
new file mode 100644
index 0000000000..41849fba3e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamAdmin.test.jsx
@@ -0,0 +1,267 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import {
+ DiscoveryStreamAdminInner,
+ CollapseToggle,
+ DiscoveryStreamAdminUI,
+ Personalization,
+ ToggleStoryButton,
+} from "content-src/components/DiscoveryStreamAdmin/DiscoveryStreamAdmin";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("DiscoveryStreamAdmin", () => {
+ let sandbox;
+ let wrapper;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ wrapper = shallow(
+ <DiscoveryStreamAdminInner
+ collapsed={false}
+ location={{ routes: [""] }}
+ Prefs={{}}
+ />
+ );
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should render DiscoveryStreamAdmin component", () => {
+ assert.ok(wrapper.exists());
+ });
+ it("should set a .collapsed class on the outer div if props.collapsed is true", () => {
+ wrapper.setProps({ collapsed: true });
+ assert.isTrue(wrapper.find(".discoverystream-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(".discoverystream-admin").hasClass("expanded"));
+ assert.isFalse(
+ wrapper.find(".discoverystream-admin").hasClass("collapsed")
+ );
+ });
+ it("should render a DS section", () => {
+ assert.equal(wrapper.find("h1").at(0).text(), "Discovery Stream Admin");
+ });
+
+ describe("#DiscoveryStream", () => {
+ let state = {};
+ let dispatch;
+ beforeEach(() => {
+ dispatch = sandbox.stub();
+ state = {
+ config: {
+ enabled: true,
+ },
+ layout: [],
+ spocs: {
+ frequency_caps: [],
+ },
+ feeds: {
+ data: {},
+ },
+ };
+ wrapper = shallow(
+ <DiscoveryStreamAdminUI
+ dispatch={dispatch}
+ otherPrefs={{}}
+ state={{
+ DiscoveryStream: state,
+ }}
+ />
+ );
+ });
+ it("should render a DiscoveryStreamAdminUI component", () => {
+ assert.equal(wrapper.find("h3").at(0).text(), "Layout");
+ });
+ it("should render a spoc in DiscoveryStreamAdminUI component", () => {
+ state.spocs = {
+ frequency_caps: [],
+ data: {
+ spocs: {
+ items: [
+ {
+ id: 12345,
+ },
+ ],
+ },
+ },
+ };
+ wrapper = shallow(
+ <DiscoveryStreamAdminUI
+ 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 },
+ })
+ );
+ });
+ 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 DiscoveryStreamAdminInner for about:newtab (no hash)", () => {
+ wrapper.setProps({ location: { hash: "", routes: [""] } });
+ assert.lengthOf(wrapper.find(DiscoveryStreamAdminInner), 0);
+ });
+
+ it("should render DiscoveryStreamAdminInner for about:newtab#devtools and subroutes", () => {
+ wrapper.setProps({ location: { hash: "#devtools", routes: [""] } });
+ assert.lengthOf(wrapper.find(DiscoveryStreamAdminInner), 1);
+
+ wrapper.setProps({ location: { hash: "#devtools-foo", routes: [""] } });
+ assert.lengthOf(wrapper.find(DiscoveryStreamAdminInner), 1);
+ });
+ });
+});
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..10b06cab9d
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx
@@ -0,0 +1,138 @@
+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");
+ let expected = ["123", "456", "789"].map(url => ({
+ url,
+ pocket_id: undefined,
+ isSponsoredTopSite: undefined,
+ position: 0,
+ is_pocket_card: false,
+ }));
+
+ assert.deepEqual(firstCall.args[0].data, expected);
+
+ 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..dad4d19fa5
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx
@@ -0,0 +1,582 @@
+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",
+ recommendation_id: undefined,
+ tile_id: "fooidx",
+ },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [
+ {
+ id: "fooidx",
+ pos: 1,
+ type: "organic",
+ recommendation_id: undefined,
+ },
+ ],
+ 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",
+ recommendation_id: undefined,
+ tile_id: "fooidx",
+ },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [
+ {
+ id: "fooidx",
+ pos: 1,
+ type: "spoc",
+ recommendation_id: undefined,
+ },
+ ],
+ 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",
+ recommendation_id: undefined,
+ tile_id: "fooidx",
+ shim: "click shim",
+ },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [
+ {
+ id: "fooidx",
+ pos: 1,
+ shim: "click shim",
+ type: "organic",
+ recommendation_id: undefined,
+ },
+ ],
+ 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",
+ recommendation_id: undefined,
+ tile_id: "fooidx",
+ },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ source: "CARDGRID_HOVER",
+ pocket: 0,
+ tiles: [
+ {
+ id: "fooidx",
+ pos: 1,
+ recommendation_id: undefined,
+ },
+ ],
+ })
+ );
+ });
+ });
+
+ 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..0748ff701a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx
@@ -0,0 +1,96 @@
+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,
+ position: 0,
+ is_pocket_card: false,
+ },
+ ]);
+
+ 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..4926cc6c70
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx
@@ -0,0 +1,276 @@
+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", recommendation_id: undefined },
+ { id: 2, pos: 1, type: "organic", recommendation_id: undefined },
+ { id: 3, pos: 2, type: "organic", recommendation_id: undefined },
+ ]);
+ });
+ 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", recommendation_id: undefined },
+ { id: 2, pos: 1, type: "organic", recommendation_id: undefined },
+ { id: 3, pos: 2, type: "organic", recommendation_id: undefined },
+ ]);
+ });
+ 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/LinkMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx
new file mode 100644
index 0000000000..be7ac219d6
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx
@@ -0,0 +1,667 @@
+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,
+ position: 3,
+ tile_id: 12345,
+ is_pocket_card: false,
+ },
+ ],
+ 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,
+ });
+ });
+ it(`should create a proper BLOCK_URL action for a sponsored tile`, () => {
+ const site = {
+ hostname: "foo",
+ path: "foo",
+ referrer: "https://foo.com/ref",
+ title: "bar",
+ type: "bookmark",
+ typedBonus: true,
+ url: "https://foo.com",
+ sponsored_position: 1,
+ };
+ const { options: blockOptions } = shallow(
+ <LinkMenu
+ site={site}
+ siteInfo={{ value: { card_type: site.type } }}
+ dispatch={dispatch}
+ index={FAKE_INDEX}
+ isPrivateBrowsingEnabled={true}
+ platform={"default"}
+ options={["BlockUrl"]}
+ source={FAKE_SOURCE}
+ shouldSendImpressionStats={true}
+ />
+ )
+ .find(ContextMenu)
+ .props();
+ const [blockUrlOption] = blockOptions;
+
+ blockUrlOption.onClick(FAKE_EVENT);
+
+ assert.calledThrice(dispatch);
+ assert.ok(dispatch.firstCall.calledWith(blockUrlOption.action));
+ const expected = {
+ url: site.url,
+ pocket_id: undefined,
+ advertiser_name: site.hostname,
+ isSponsoredTopSite: 1,
+ position: 3,
+ is_pocket_card: false,
+ };
+ assert.deepEqual(blockUrlOption.action.data[0], expected);
+ });
+ it(`should create a proper BLOCK_URL action for a pocket item`, () => {
+ const site = {
+ hostname: "foo",
+ path: "foo",
+ referrer: "https://foo.com/ref",
+ title: "bar",
+ type: "CardGrid",
+ typedBonus: true,
+ url: "https://foo.com",
+ };
+ const { options: blockOptions } = shallow(
+ <LinkMenu
+ site={site}
+ siteInfo={{ value: { card_type: site.type } }}
+ dispatch={dispatch}
+ index={FAKE_INDEX}
+ isPrivateBrowsingEnabled={true}
+ platform={"default"}
+ options={["BlockUrl"]}
+ source={FAKE_SOURCE}
+ shouldSendImpressionStats={true}
+ />
+ )
+ .find(ContextMenu)
+ .props();
+ const [blockUrlOption] = blockOptions;
+
+ blockUrlOption.onClick(FAKE_EVENT);
+
+ assert.calledThrice(dispatch);
+ assert.ok(dispatch.firstCall.calledWith(blockUrlOption.action));
+ const expected = {
+ url: site.url,
+ pocket_id: undefined,
+ isSponsoredTopSite: undefined,
+ position: 3,
+ is_pocket_card: true,
+ };
+ assert.deepEqual(blockUrlOption.action.data[0], expected);
+ });
+ });
+});
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..1977066f0d
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx
@@ -0,0 +1,1930 @@
+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",
+ shim: { click: "shim_click_id" },
+ };
+ 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");
+
+ [action] = dispatch.getCall(3).args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_USER_EVENT);
+
+ assert.propertyVal(action.data, "event", "CLICK");
+ assert.propertyVal(action.data, "action_position", 1);
+ assert.propertyVal(action.data, "source", "TOP_SITES");
+ assert.propertyVal(action.data.value, "card_type", "spoc");
+ assert.propertyVal(action.data.value, "tile_id", 1);
+ assert.propertyVal(action.data.value, "shim", "shim_click_id");
+
+ // Topsite SPOC click event.
+ [action] = dispatch.getCall(4).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..3f7e725de0
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites/TopSiteImpressionWrapper.test.jsx
@@ -0,0 +1,148 @@
+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/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..0dd510ef1a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/init-store.test.js
@@ -0,0 +1,155 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { addNumberReducer, GlobalOverrider } from "test/unit/utils";
+import {
+ INCOMING_MESSAGE_NAME,
+ initStore,
+ MERGE_STORE_ACTION,
+ OUTGOING_MESSAGE_NAME,
+ 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);
+ });
+ });
+});
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..7438d8247c
--- /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.sys.mjs";
+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..c127060021
--- /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.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+
+import { DEFAULT_SITES } from "lib/DefaultSites.sys.mjs";
+import { AboutPreferences } from "lib/AboutPreferences.sys.mjs";
+import { DefaultPrefs } from "lib/ActivityStreamPrefs.sys.mjs";
+import { NewTabInit } from "lib/NewTabInit.sys.mjs";
+import { SectionsFeed } from "lib/SectionsManager.sys.mjs";
+import { RecommendationProvider } from "lib/RecommendationProvider.sys.mjs";
+import { PlacesFeed } from "lib/PlacesFeed.sys.mjs";
+import { PrefsFeed } from "lib/PrefsFeed.sys.mjs";
+import { SystemTickFeed } from "lib/SystemTickFeed.sys.mjs";
+import { TelemetryFeed } from "lib/TelemetryFeed.sys.mjs";
+import { FaviconFeed } from "lib/FaviconFeed.sys.mjs";
+import { TopSitesFeed } from "lib/TopSitesFeed.sys.mjs";
+import { TopStoriesFeed } from "lib/TopStoriesFeed.sys.mjs";
+import { HighlightsFeed } from "lib/HighlightsFeed.sys.mjs";
+import { DiscoveryStreamFeed } from "lib/DiscoveryStreamFeed.sys.mjs";
+
+import { LinksCache } from "lib/LinksCache.sys.mjs";
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+import { DownloadsManager } from "lib/DownloadsManager.sys.mjs";
+
+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..4bea86331d
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js
@@ -0,0 +1,445 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import {
+ ActivityStreamMessageChannel,
+ DEFAULT_OPTIONS,
+} from "lib/ActivityStreamMessageChannel.sys.mjs";
+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() {} });
+ globals.set("AboutNewTabParent", {
+ flushQueuedMessagesFromContent: globals.sandbox.stub(),
+ });
+
+ 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);
+ });
+ it("should flush queued messages from content when doing the simulation", () => {
+ assert.notCalled(
+ global.AboutNewTabParent.flushQueuedMessagesFromContent
+ );
+ mm.simulateMessagesForExistingTabs();
+ assert.calledOnce(
+ global.AboutNewTabParent.flushQueuedMessagesFromContent
+ );
+ });
+ });
+ });
+ 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..bff1708ef7
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamPrefs.test.js
@@ -0,0 +1,113 @@
+import { DefaultPrefs, Prefs } from "lib/ActivityStreamPrefs.sys.mjs";
+
+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..0b8baef762
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamStorage.test.js
@@ -0,0 +1,161 @@
+import { ActivityStreamStorage } from "lib/ActivityStreamStorage.sys.mjs";
+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..92e10facb3
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js
@@ -0,0 +1,3523 @@
+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.sys.mjs";
+import { RecommendationProvider } from "lib/RecommendationProvider.sys.mjs";
+import { reducers } from "common/Reducers.sys.mjs";
+
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+
+const CONFIG_PREF_NAME = "discoverystream.config";
+const ENDPOINTS_PREF_NAME = "discoverystream.endpoints";
+const DUMMY_ENDPOINT = "https://getpocket.cdn.mozilla.net/dummy";
+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,
+ });
+
+ 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,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ "system.showSponsored": false,
+ },
+ },
+ });
+ 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 use local basic layout with hardcoded_basic_layout being true", async () => {
+ feed.config.hardcoded_basic_layout = true;
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ 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.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.region-basic-layout": true,
+ "system.showSponsored": false,
+ },
+ },
+ });
+
+ 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.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.region-basic-layout": false,
+ "system.showSponsored": false,
+ },
+ },
+ });
+
+ 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 FF pref hardcoded_basic_layout", async () => {
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: false,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.hardcoded-basic-layout": true,
+ "system.showSponsored": false,
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ 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,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.spocs-endpoint":
+ "https://spocs.getpocket.com/spocs2",
+ "system.showSponsored": false,
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs2"
+ );
+ });
+ it("should return enough stories to fill a four card layout", async () => {
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: { fourCardLayout: true },
+ },
+ },
+ });
+
+ 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.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.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.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ spocTopsitesPlacementEnabled: true,
+ 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.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, "system.showSponsored": 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,
+ "system.showSponsored": 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("#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: [], personalized: false }));
+ 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: [], personalized: false }));
+ 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("#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.calledWith(feed.cache.set, "spocs", { lastUpdated: 0, spocs: {} });
+ });
+ 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: {
+ personalized: false,
+ 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 dispatch DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE with feature_flags", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.spy(feed.store, "dispatch");
+ 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.calledWith(
+ feed.store.dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE,
+ data: {
+ override: true,
+ },
+ })
+ );
+ });
+ 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: {
+ personalized: false,
+ 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: {
+ personalized: false,
+ title: "title",
+ context: "context",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "data", score: 1 }],
+ },
+ });
+ });
+ describe("test SOV behaviour", () => {
+ beforeEach(() => {
+ globals.set("NimbusFeatures", {
+ pocketNewtab: {
+ getVariable: sandbox.stub(),
+ },
+ });
+ global.NimbusFeatures.pocketNewtab.getVariable
+ .withArgs("topSitesContileSovEnabled")
+ .returns(true);
+ // We don't need this for just this test, we are setting placements
+ // manually.
+ feed.getPlacements.restore();
+ Object.defineProperty(feed, "showSponsoredStories", {
+ get: () => true,
+ });
+ const fakeComponents = {
+ components: [
+ { placement: { name: "sponsored-topsites" }, spocs: {} },
+ { placement: { name: "spocs" }, spocs: {} },
+ ],
+ };
+ feed.updatePlacements(feed.store.dispatch, [fakeComponents]);
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ spocs: [{ id: "spoc1" }],
+ "sponsored-topsites": [{ id: "topsite1" }],
+ });
+ });
+ it("should use topsites placement by default if there is no SOV", async () => {
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[1].body,
+ JSON.stringify({
+ pocket_id: "{foo-123-foo}",
+ version: 2,
+ placements: [
+ {
+ name: "sponsored-topsites",
+ },
+ {
+ name: "spocs",
+ },
+ ],
+ })
+ );
+ });
+ it("should use cache if cache is available and SOV is not ready", async () => {
+ const cache = {
+ sov: [{ assignedPartner: "amp" }],
+ };
+ feed.cache.get.resolves(cache);
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[1].body,
+ JSON.stringify({
+ pocket_id: "{foo-123-foo}",
+ version: 2,
+ placements: [
+ {
+ name: "spocs",
+ },
+ ],
+ })
+ );
+ });
+ it("should properly set placements", async () => {
+ sandbox.spy(feed.cache, "set");
+
+ // Testing only 1 placement type.
+ feed.store.dispatch(
+ ac.OnlyToMain({
+ type: at.SOV_UPDATED,
+ data: {
+ ready: true,
+ positions: [
+ {
+ position: 1,
+ assignedPartner: "amp",
+ },
+ {
+ position: 2,
+ assignedPartner: "amp",
+ },
+ ],
+ },
+ })
+ );
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ const firstCall = feed.cache.set.getCall(0);
+ assert.deepEqual(firstCall.args[0], "sov");
+ assert.deepEqual(firstCall.args[1], [
+ {
+ position: 1,
+ assignedPartner: "amp",
+ },
+ {
+ position: 2,
+ assignedPartner: "amp",
+ },
+ ]);
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[1].body,
+ JSON.stringify({
+ pocket_id: "{foo-123-foo}",
+ version: 2,
+ placements: [
+ {
+ name: "spocs",
+ },
+ ],
+ })
+ );
+
+ // Testing 2 placement types.
+ feed.store.dispatch(
+ ac.OnlyToMain({
+ type: at.SOV_UPDATED,
+ data: {
+ ready: true,
+ positions: [
+ {
+ position: 1,
+ assignedPartner: "amp",
+ },
+ {
+ position: 2,
+ assignedPartner: "moz-sales",
+ },
+ ],
+ },
+ })
+ );
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ const secondCall = feed.cache.set.getCall(2);
+ assert.deepEqual(secondCall.args[0], "sov");
+ assert.deepEqual(secondCall.args[1], [
+ {
+ position: 1,
+ assignedPartner: "amp",
+ },
+ {
+ position: 2,
+ assignedPartner: "moz-sales",
+ },
+ ]);
+ assert.equal(
+ feed.fetchFromEndpoint.secondCall.args[1].body,
+ JSON.stringify({
+ pocket_id: "{foo-123-foo}",
+ version: 2,
+ placements: [
+ {
+ name: "sponsored-topsites",
+ },
+ {
+ name: "spocs",
+ },
+ ],
+ })
+ );
+ });
+ });
+ });
+
+ 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, "system.showSponsored": true },
+ },
+ });
+
+ assert.isFalse(feed.showSponsoredStories);
+ });
+ it("should return false from showSponsoredStories if DiscoveryStream pref system.showSponsored is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: { showSponsored: true, "system.showSponsored": false },
+ },
+ });
+
+ assert.isFalse(feed.showSponsoredStories);
+ });
+ it("should return true from showSponsoredStories if both prefs are true", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: { showSponsored: true, "system.showSponsored": 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(() => {
+ 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,
+ "system.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: { PREF_SPOCS_CLEAR_ENDPOINT: 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);
+ });
+ });
+
+ describe("#resetCache", () => {
+ it("should set .feeds .spocs and .sov to {}", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.resetCache();
+
+ assert.callCount(feed.cache.set, 3);
+ const firstCall = feed.cache.set.getCall(0);
+ const secondCall = feed.cache.set.getCall(1);
+ const thirdCall = feed.cache.set.getCall(2);
+ assert.deepEqual(firstCall.args, ["feeds", {}]);
+ assert.deepEqual(secondCall.args, ["spocs", {}]);
+ assert.deepEqual(thirdCall.args, ["sov", {}]);
+ });
+ });
+
+ 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: "api_key_pref", value: "foo" },
+ });
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: CONFIG_PREF_NAME,
+ value: JSON.stringify({
+ enabled: true,
+ other: "value",
+ api_key_pref: "foo",
+ }),
+ },
+ 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,
+ api_key_pref: "foo",
+ });
+
+ assert.deepEqual(feed.store.getState().DiscoveryStream.config, {
+ enabled: true,
+ api_key_pref: "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);
+ });
+ it("shoud update allowlist", async () => {
+ assert.equal(
+ feed.store.getState().Prefs.values[ENDPOINTS_PREF_NAME],
+ DUMMY_ENDPOINT
+ );
+ setPref(ENDPOINTS_PREF_NAME, "sick-kickflip.mozilla.net");
+ assert.equal(
+ feed.store.getState().Prefs.values[ENDPOINTS_PREF_NAME],
+ "sick-kickflip.mozilla.net"
+ );
+ });
+ });
+
+ 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("#enable", () => {
+ it("should pass along proper options to refreshAll from enable", async () => {
+ sandbox.stub(feed, "refreshAll");
+ await feed.enable();
+ assert.calledWith(feed.refreshAll, {});
+ await feed.enable({ updateOpenTabs: true });
+ assert.calledWith(feed.refreshAll, { updateOpenTabs: true });
+ await feed.enable({ isStartup: true });
+ assert.calledWith(feed.refreshAll, { isStartup: true });
+ await feed.enable({ updateOpenTabs: true, isStartup: true });
+ assert.calledWith(feed.refreshAll, {
+ updateOpenTabs: true,
+ isStartup: true,
+ });
+ });
+ });
+
+ 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);
+ });
+ it("should update open tabs but not startup with onPrefChange", async () => {
+ sandbox.stub(feed, "refreshAll");
+ feed._prefCache.config = {
+ enabled: true,
+ };
+ await feed.onPrefChange();
+ assert.calledWith(feed.refreshAll, { updateOpenTabs: true });
+ });
+ });
+
+ 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_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 spocs on startup for content under 1 week", () => {
+ const spocs = { lastUpdated: Date.now() };
+ const result = feed.isExpired({
+ cachedData: { spocs },
+ key: "spocs",
+ isStartup: true,
+ });
+
+ assert.isFalse(result);
+ });
+ it("should return true for spocs for isStartup=false after 30 mins", () => {
+ const spocs = { lastUpdated: Date.now() };
+ clock.tick(THIRTY_MINUTES + 1);
+ const result = feed.isExpired({ cachedData: { spocs }, key: "spocs" });
+
+ assert.isTrue(result);
+ });
+ it("should return true for spocs on startup for content over 1 week", () => {
+ const spocs = { lastUpdated: Date.now() };
+ clock.tick(ONE_WEEK + 1);
+ const result = feed.isExpired({
+ cachedData: { spocs },
+ key: "spocs",
+ isStartup: true,
+ });
+
+ assert.isTrue(result);
+ });
+ });
+
+ describe("#checkIfAnyCacheExpired", () => {
+ let cache;
+ beforeEach(() => {
+ cache = {
+ 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 .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.spocs.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.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 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() },
+ });
+ clock.tick(THIRTY_MINUTES + 1);
+
+ await feed.refreshAll({ isStartup: true });
+
+ // 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: [], personalized: false }));
+ 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", () => {
+ beforeEach(() => {
+ sandbox.stub(feed.cache, "set").resolves();
+ sandbox.spy(feed.store, "dispatch");
+ });
+ it("should score feeds and set cache, and dispatch", async () => {
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": false,
+ },
+ },
+ Personalization: {
+ initialized: true,
+ },
+ DiscoveryStream: {
+ spocs: {
+ placements: [
+ { name: "placement1" },
+ { name: "placement2" },
+ { name: "placement3" },
+ ],
+ },
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ 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": {
+ personalized: true,
+ 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": {
+ personalized: true,
+ 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"],
+ });
+ });
+
+ it("should skip already personalized feeds", async () => {
+ sandbox.spy(feed, "scoreItems");
+ const recsExpireTime = 5600;
+ const fakeFeeds = {
+ data: {
+ "https://foo.com": {
+ personalized: true,
+ data: {
+ recommendations: [
+ {
+ id: "first",
+ item_score: 0.7,
+ },
+ {
+ id: "second",
+ item_score: 0.6,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ },
+ };
+
+ await feed.scoreFeeds(fakeFeeds);
+
+ assert.notCalled(feed.scoreItems);
+ });
+ });
+
+ describe("#scoreSpocs", () => {
+ beforeEach(() => {
+ sandbox.stub(feed.cache, "set").resolves();
+ sandbox.spy(feed.store, "dispatch");
+ });
+ it("should score spocs and set cache, dispatch", async () => {
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": false,
+ },
+ },
+ Personalization: {
+ initialized: true,
+ },
+ 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: {
+ personalized: true,
+ items: [
+ {
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ score: 0.6,
+ item_score: 0.6,
+ },
+ {
+ score: 0.4,
+ item_score: 0.4,
+ },
+ ],
+ },
+ placement2: {
+ personalized: true,
+ 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
+ );
+ });
+
+ it("should skip already personalized spocs", async () => {
+ sandbox.spy(feed, "scoreItems");
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": false,
+ },
+ },
+ Personalization: {
+ initialized: true,
+ },
+ DiscoveryStream: {
+ spocs: {
+ placements: [{ name: "placement1" }],
+ },
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ const fakeSpocs = {
+ lastUpdated: 1234,
+ data: {
+ placement1: {
+ personalized: true,
+ items: [
+ {
+ item_score: 0.6,
+ },
+ {
+ item_score: 0.4,
+ },
+ {
+ item_score: 0.8,
+ },
+ ],
+ },
+ },
+ };
+
+ await feed.scoreSpocs(fakeSpocs);
+
+ assert.notCalled(feed.scoreItems);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_PERSONALIZATION_UPDATED", () => {
+ it("should call scoreFeeds and scoreSpocs if loaded", async () => {
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ pocketConfig: {
+ recsPersonalized: true,
+ spocsPersonalized: true,
+ },
+ },
+ },
+ DiscoveryStream: {
+ feeds: { loaded: false },
+ spocs: { loaded: false },
+ },
+ };
+
+ sandbox.stub(feed, "scoreFeeds").resolves();
+ sandbox.stub(feed, "scoreSpocs").resolves();
+ Object.defineProperty(feed, "personalized", { get: () => true });
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
+ });
+
+ assert.notCalled(feed.scoreFeeds);
+ assert.notCalled(feed.scoreSpocs);
+
+ fakeDiscoveryStream.DiscoveryStream.feeds.loaded = true;
+ fakeDiscoveryStream.DiscoveryStream.spocs.loaded = true;
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
+ });
+
+ assert.calledOnce(feed.scoreFeeds);
+ assert.calledOnce(feed.scoreSpocs);
+ });
+ });
+
+ describe("#observe", () => {
+ 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("#scoreItem", () => {
+ it("should call calculateItemRelevanceScore with recommendationProvider with initial score", async () => {
+ const item = {
+ item_score: 0.6,
+ };
+ feed.recommendationProvider.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: [], personalized: false }));
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ data: [
+ {
+ recommendationId: "decaf-c0ff33",
+ tileId: 1234,
+ url: "url",
+ title: "title",
+ excerpt: "excerpt",
+ publisher: "publisher",
+ timeToRead: "timeToRead",
+ imageUrl: "imageUrl",
+ },
+ ],
+ });
+
+ const feedData = await feed.getComponentFeed("url");
+ assert.deepEqual(feedData, {
+ lastUpdated: 0,
+ personalized: false,
+ data: {
+ settings: {},
+ recommendations: [
+ {
+ id: 1234,
+ url: "url",
+ title: "title",
+ excerpt: "excerpt",
+ publisher: "publisher",
+ time_to_read: "timeToRead",
+ raw_image_src: "imageUrl",
+ recommendation_id: "decaf-c0ff33",
+ },
+ ],
+ 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..ac262baf90
--- /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.sys.mjs";
+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..e9be9b86ba
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/FaviconFeed.test.js
@@ -0,0 +1,233 @@
+"use strict";
+import { FaviconFeed, fetchIconFromRedirects } from "lib/FaviconFeed.sys.mjs";
+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..0e98a0d006
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/FilterAdult.test.js
@@ -0,0 +1,112 @@
+import { FilterAdult } from "lib/FilterAdult.sys.mjs";
+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/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/NewTabInit.test.js b/browser/components/newtab/test/unit/lib/NewTabInit.test.js
new file mode 100644
index 0000000000..68ab9d7821
--- /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.sys.mjs";
+
+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..18c634d43d
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js
@@ -0,0 +1,95 @@
+import { NaiveBayesTextTagger } from "lib/PersonalityProvider/NaiveBayesTextTagger.mjs";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.mjs";
+
+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..aae070b305
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js
@@ -0,0 +1,479 @@
+import { NmfTextTagger } from "lib/PersonalityProvider/NmfTextTagger.mjs";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.mjs";
+
+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..0058fd7c76
--- /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.sys.mjs";
+
+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..da6454c6d6
--- /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.mjs";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.mjs";
+import { RecipeExecutor } from "lib/PersonalityProvider/RecipeExecutor.mjs";
+import { NmfTextTagger } from "lib/PersonalityProvider/NmfTextTagger.mjs";
+import { NaiveBayesTextTagger } from "lib/PersonalityProvider/NaiveBayesTextTagger.mjs";
+
+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..fdbcae9613
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js
@@ -0,0 +1,1543 @@
+import { RecipeExecutor } from "lib/PersonalityProvider/RecipeExecutor.mjs";
+import { tokenize } from "lib/PersonalityProvider/Tokenize.mjs";
+
+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..19e738d451
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js
@@ -0,0 +1,134 @@
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.mjs";
+
+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/PrefsFeed.test.js b/browser/components/newtab/test/unit/lib/PrefsFeed.test.js
new file mode 100644
index 0000000000..498c7198ab
--- /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.sys.mjs";
+
+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..9e68f4869a
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/RecommendationProvider.test.js
@@ -0,0 +1,331 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+} from "common/Actions.sys.mjs";
+import { RecommendationProvider } from "lib/RecommendationProvider.sys.mjs";
+import { combineReducers, createStore } from "redux";
+import { reducers } from "common/Reducers.sys.mjs";
+import { GlobalOverrider } from "test/unit/utils";
+
+import { PersonalityProvider } from "lib/PersonalityProvider/PersonalityProvider.sys.mjs";
+import { PersistentCache } from "lib/PersistentCache.sys.mjs";
+
+const PREF_PERSONALIZATION_ENABLED = "discoverystream.personalization.enabled";
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+describe("RecommendationProvider", () => {
+ let feed;
+ let sandbox;
+ let clock;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set({
+ PersistentCache,
+ PersonalityProvider,
+ });
+
+ sandbox = sinon.createSandbox();
+ clock = sinon.useFakeTimers();
+ feed = new RecommendationProvider();
+ feed.store = createStore(combineReducers(reducers), {});
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ clock.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("#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 ", () => {
+ sandbox.stub(global.Services.obs, "removeObserver").returns();
+ feed.loaded = true;
+ feed.provider = {
+ teardown: sandbox.stub().resolves(),
+ };
+ feed.teardown();
+ assert.calledOnce(feed.provider.teardown);
+ assert.calledOnce(global.Services.obs.removeObserver);
+ assert.calledWith(global.Services.obs.removeObserver, feed, "idle-daily");
+ });
+ });
+
+ 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("#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("#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: INIT", () => {
+ it("should ", async () => {
+ sandbox.stub(feed, "enable").returns();
+ await feed.onAction({
+ type: at.INIT,
+ });
+ assert.calledOnce(feed.enable);
+ assert.calledWith(feed.enable, true);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE", () => {
+ it("should ", async () => {
+ sandbox.stub(feed, "personalizationOverride").returns();
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE,
+ data: { override: true },
+ });
+ assert.calledOnce(feed.personalizationOverride);
+ assert.calledWith(feed.personalizationOverride, true);
+ });
+ });
+
+ describe("#loadPersonalizationScoresCache", () => {
+ it("should create a personalization provider from cached scores", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ sandbox.spy(feed.cache, "set");
+ feed.provider = {
+ init: async () => {},
+ getScores: () => "scores",
+ };
+ 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("#updatePersonalizationScores", () => {
+ beforeEach(() => {
+ sandbox.spy(feed.store, "dispatch");
+ sandbox.spy(feed.cache, "set");
+ sandbox.spy(feed, "setProvider");
+ feed.provider = {
+ init: async () => {},
+ getScores: () => "scores",
+ };
+ });
+ it("should update provider 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,
+ },
+ },
+ });
+
+ await feed.updatePersonalizationScores();
+
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: 0,
+ },
+ })
+ );
+ assert.calledWith(feed.cache.set, "personalization", {
+ scores: "scores",
+ _timestamp: 0,
+ });
+ });
+ it("should not update provider on updatePersonalizationScores", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ "discoverystream.personalization.enabled": false,
+ },
+ },
+ });
+ await feed.updatePersonalizationScores();
+
+ assert.notCalled(feed.setProvider);
+ });
+ });
+
+ 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)
+ );
+ });
+ });
+
+ describe("#observe", () => {
+ it("should call updatePersonalizationScores on idle daily", async () => {
+ sandbox.stub(feed, "updatePersonalizationScores").returns();
+ feed.observe(null, "idle-daily");
+ assert.calledOnce(feed.updatePersonalizationScores);
+ });
+ });
+});
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..a03f06890d
--- /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.sys.mjs";
+
+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..b3a9abd70c
--- /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.sys.mjs";
+
+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..201e5226fd
--- /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.sys.mjs";
+
+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..cd97707e9b
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SiteClassifier.test.js
@@ -0,0 +1,252 @@
+import { classifySite } from "lib/SiteClassifier.sys.mjs";
+
+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/SystemTickFeed.test.js b/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js
new file mode 100644
index 0000000000..a0789b182e
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js
@@ -0,0 +1,79 @@
+import {
+ SYSTEM_TICK_INTERVAL,
+ SystemTickFeed,
+} from "lib/SystemTickFeed.sys.mjs";
+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/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/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..5b32269ca8
--- /dev/null
+++ b/browser/components/newtab/test/unit/unit-entry.js
@@ -0,0 +1,733 @@
+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 enzyme from "enzyme";
+
+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);
+
+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: {
+ defineLazyGetter(object, name, f) {
+ updateGlobalOrObject(object)[name] = f();
+ },
+ 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() {},
+ },
+ },
+ 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: {
+ defineLazyGlobalGetters: 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() {},
+ },
+ sovAllocation: {
+ set() {},
+ },
+ },
+ newtabSearch: {
+ enabled: {
+ set() {},
+ },
+ },
+ newtabHandoffPreference: {
+ enabled: {
+ set() {},
+ },
+ },
+ pocket: {
+ enabled: {
+ set() {},
+ },
+ impression: {
+ record() {},
+ },
+ isSignedIn: {
+ set() {},
+ },
+ sponsoredStoriesEnabled: {
+ set() {},
+ },
+ click: {
+ record() {},
+ },
+ save: {
+ record() {},
+ },
+ topicClick: {
+ record() {},
+ },
+ shim: {
+ set() {},
+ },
+ },
+ topsites: {
+ enabled: {
+ set() {},
+ },
+ sponsoredEnabled: {
+ set() {},
+ },
+ impression: {
+ record() {},
+ },
+ click: {
+ record() {},
+ },
+ rows: {
+ set() {},
+ },
+ showPrivacyClick: {
+ record() {},
+ },
+ dismiss: {
+ record() {},
+ },
+ prefChanged: {
+ record() {},
+ },
+ sponsoredTilesConfigured: {
+ set() {},
+ },
+ sponsoredTilesReceived: {
+ set() {},
+ },
+ },
+ topSites: {
+ pingType: {
+ set() {},
+ },
+ position: {
+ set() {},
+ },
+ source: {
+ set() {},
+ },
+ tileId: {
+ set() {},
+ },
+ reportingUrl: {
+ set() {},
+ },
+ advertiser: {
+ set() {},
+ },
+ contextId: {
+ set() {},
+ },
+ },
+ },
+ GleanPings: {
+ newtab: {
+ submit() {},
+ },
+ topSites: {
+ submit() {},
+ },
+ spoc: {
+ 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/test_AboutHomeStartupCacheChild.js b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js
new file mode 100644
index 0000000000..ce1ee48caa
--- /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.importESModule(
+ "resource:///modules/AboutNewTabService.sys.mjs"
+);
+
+/**
+ * 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..d1f75b78bf
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js
@@ -0,0 +1,255 @@
+/* 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"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+const { DiscoveryStreamFeed } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/DiscoveryStreamFeed.sys.mjs"
+);
+
+SearchTestUtils.init(this);
+AddonTestUtils.init(this);
+AddonTestUtils.createAppInfo(
+ "xpcshell@tests.mozilla.org",
+ "XPCShell",
+ "42",
+ "42"
+);
+
+const { AboutNewTab } = ChromeUtils.importESModule(
+ "resource:///modules/AboutNewTab.sys.mjs"
+);
+const { PREFS_CONFIG } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/ActivityStream.sys.mjs"
+);
+
+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",
+ })
+ );
+
+ const sandbox = sinon.createSandbox();
+ sandbox
+ .stub(DiscoveryStreamFeed.prototype, "generateFeedUrl")
+ .returns("http://example.com/topstories.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(defaultDSConfig)
+ );
+
+ // 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
+ );
+
+ // 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 20 placeholders.
+ equal(
+ Array.from(root.querySelectorAll(".ds-card")).length,
+ 21,
+ "There are 21 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, 20, "There should be 20 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..1eb8081d25
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutNewTab.js
@@ -0,0 +1,363 @@
+/* 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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+);
+const { AboutNewTab } = ChromeUtils.importESModule(
+ "resource:///modules/AboutNewTab.sys.mjs"
+);
+
+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..3d83f473d5
--- /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.importESModule(
+ "resource:///modules/aboutwelcome/AboutWelcomeDefaults.sys.mjs"
+);
+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..b8339fb39f
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js
@@ -0,0 +1,90 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AboutWelcomeTelemetry } = ChromeUtils.importESModule(
+ "resource:///modules/aboutwelcome/AboutWelcomeTelemetry.sys.mjs"
+);
+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();
+ 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();
+
+ 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..5191f05d04
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry_glean.js
@@ -0,0 +1,238 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AboutWelcomeTelemetry } = ChromeUtils.importESModule(
+ "resource:///modules/aboutwelcome/AboutWelcomeTelemetry.sys.mjs"
+);
+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",
+ screen_family: "family",
+ screen_id: "screen_id",
+ screen_index: 0,
+ screen_initlals: "screen_initials",
+ };
+ 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.eventScreenFamily.testGetValue(),
+ eventContext.screen_family,
+ "event_context.screen_family also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenId.testGetValue(),
+ eventContext.screen_id,
+ "event_context.screen_id also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenIndex.testGetValue(),
+ eventContext.screen_index,
+ "event_context.screen_index also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenInitials.testGetValue(),
+ eventContext.screen_initials,
+ "event_context.screen_initials 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.eventScreenFamily.testGetValue(),
+ eventContext.screen_family,
+ "event_context.screen_family also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenId.testGetValue(),
+ eventContext.screen_id,
+ "event_context.screen_id also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenIndex.testGetValue(),
+ eventContext.screen_index,
+ "event_context.screen_index also in own metric."
+ );
+ Assert.equal(
+ Glean.messagingSystem.eventScreenInitials.testGetValue(),
+ eventContext.screen_initials,
+ "event_context.screen_initials 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");
+});
+
+// For event_context to be more useful, we want to make sure we don't error
+// in cases where it doesn't make much sense, such as a plain string that
+// doesnt attempt to represent a valid object.
+add_task(function test_context_errors() {
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(TELEMETRY_PREF);
+ });
+ Services.prefs.setBoolPref(TELEMETRY_PREF, true);
+
+ const AWTelemetry = new AboutWelcomeTelemetry();
+
+ let weird_context_ping = {
+ event_context: "oops, this string isn't a valid JS object!",
+ };
+
+ let pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.eventContextParseError.testGetValue(),
+ undefined,
+ "this poorly formed context shouldn't register because it was not an object!"
+ );
+ });
+
+ AWTelemetry.submitGleanPingForPing(weird_context_ping);
+
+ Assert.ok(pingSubmitted, "Ping with unknown keys was submitted");
+
+ weird_context_ping = {
+ event_context:
+ "{oops : {'this string isn't a valid JS object, but it sure looks like one!}}'",
+ };
+
+ pingSubmitted = false;
+ GleanPings.messagingSystem.testBeforeNextSubmit(() => {
+ pingSubmitted = true;
+ Assert.equal(
+ Glean.messagingSystem.eventContextParseError.testGetValue(),
+ 1,
+ "this poorly formed context should register because it was not an object!"
+ );
+ });
+
+ AWTelemetry.submitGleanPingForPing(weird_context_ping);
+
+ Assert.ok(pingSubmitted, "Ping with unknown keys was submitted");
+});
diff --git a/browser/components/newtab/test/xpcshell/test_HighlightsFeed.js b/browser/components/newtab/test/xpcshell/test_HighlightsFeed.js
new file mode 100644
index 0000000000..233eb6df73
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_HighlightsFeed.js
@@ -0,0 +1,1402 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+ChromeUtils.defineESModuleGetters(this, {
+ FilterAdult: "resource://activity-stream/lib/FilterAdult.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+ Screenshots: "resource://activity-stream/lib/Screenshots.sys.mjs",
+ SectionsManager: "resource://activity-stream/lib/SectionsManager.sys.mjs",
+ shortURL: "resource://activity-stream/lib/ShortURL.sys.mjs",
+ sinon: "resource://testing-common/Sinon.sys.mjs",
+});
+
+const {
+ HighlightsFeed,
+ SYNC_BOOKMARKS_FINISHED_EVENT,
+ BOOKMARKS_RESTORE_SUCCESS_EVENT,
+ BOOKMARKS_RESTORE_FAILED_EVENT,
+ SECTION_ID,
+} = ChromeUtils.import("resource://activity-stream/lib/HighlightsFeed.jsm");
+
+const FAKE_LINKS = new Array(20)
+ .fill(null)
+ .map((v, i) => ({ url: `http://www.site${i}.com` }));
+const FAKE_IMAGE = "data123";
+const FAKE_URL = "https://mozilla.org";
+const FAKE_IMAGE_URL = "https://mozilla.org/preview.jpg";
+
+function getHighlightsFeedForTest(sandbox) {
+ let feed = new HighlightsFeed();
+ feed.store = {
+ dispatch: sandbox.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: sandbox.stub().callsFake(cb => {
+ cb();
+ return () => {};
+ }),
+ };
+
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "getHighlights")
+ .resolves(FAKE_LINKS);
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "deletePocketEntry")
+ .resolves({});
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "archivePocketEntry")
+ .resolves({});
+ sandbox
+ .stub(NewTabUtils.activityStreamProvider, "_processHighlights")
+ .callsFake(l => l.slice(0, 1));
+
+ return feed;
+}
+
+async function fetchHighlightsRows(feed, options) {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(SectionsManager, "updateSection");
+ await feed.fetchHighlights(options);
+ let [, { rows }] = SectionsManager.updateSection.firstCall.args;
+
+ sandbox.restore();
+ return rows;
+}
+
+function fetchImage(feed, page) {
+ return feed.fetchImage(
+ Object.assign({ __sharedCache: { updateLink() {} } }, page)
+ );
+}
+
+add_task(function test_construction() {
+ info("HighlightsFeed construction should work");
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(PageThumbs, "addExpirationFilter");
+
+ let feed = getHighlightsFeedForTest(sandbox);
+ Assert.ok(feed, "Was able to create a HighlightsFeed");
+
+ info("HighlightsFeed construction should add a PageThumbs expiration filter");
+ Assert.ok(
+ PageThumbs.addExpirationFilter.calledOnce,
+ "PageThumbs.addExpirationFilter was called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(function test_init_action() {
+ let sandbox = sinon.createSandbox();
+
+ let countObservers = topic => {
+ return [...Services.obs.enumerateObservers(topic)].length;
+ };
+
+ const INITIAL_SYNC_BOOKMARKS_FINISHED_EVENT_COUNT = countObservers(
+ SYNC_BOOKMARKS_FINISHED_EVENT
+ );
+ const INITIAL_BOOKMARKS_RESTORE_SUCCESS_EVENT_COUNT = countObservers(
+ BOOKMARKS_RESTORE_SUCCESS_EVENT
+ );
+ const INITIAL_BOOKMARKS_RESTORE_FAILED_EVENT_COUNT = countObservers(
+ BOOKMARKS_RESTORE_FAILED_EVENT
+ );
+
+ sandbox
+ .stub(SectionsManager, "onceInitialized")
+ .callsFake(callback => callback());
+ sandbox.stub(SectionsManager, "enableSection");
+
+ let feed = getHighlightsFeedForTest(sandbox);
+ sandbox.stub(feed, "fetchHighlights");
+ sandbox.stub(feed.downloadsManager, "init");
+
+ feed.onAction({ type: at.INIT });
+
+ info("HighlightsFeed.onAction(INIT) should add a sync observer");
+ Assert.equal(
+ countObservers(SYNC_BOOKMARKS_FINISHED_EVENT),
+ INITIAL_SYNC_BOOKMARKS_FINISHED_EVENT_COUNT + 1
+ );
+ Assert.equal(
+ countObservers(BOOKMARKS_RESTORE_SUCCESS_EVENT),
+ INITIAL_BOOKMARKS_RESTORE_SUCCESS_EVENT_COUNT + 1
+ );
+ Assert.equal(
+ countObservers(BOOKMARKS_RESTORE_FAILED_EVENT),
+ INITIAL_BOOKMARKS_RESTORE_FAILED_EVENT_COUNT + 1
+ );
+
+ info(
+ "HighlightsFeed.onAction(INIT) should call SectionsManager.onceInitialized"
+ );
+ Assert.ok(
+ SectionsManager.onceInitialized.calledOnce,
+ "SectionsManager.onceInitialized was called"
+ );
+
+ info("HighlightsFeed.onAction(INIT) should enable its section");
+ Assert.ok(
+ SectionsManager.enableSection.calledOnce,
+ "SectionsManager.enableSection was called"
+ );
+ Assert.ok(SectionsManager.enableSection.calledWith(SECTION_ID));
+
+ info("HighlightsFeed.onAction(INIT) should fetch highlights");
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights was called"
+ );
+
+ info("HighlightsFeed.onAction(INIT) should initialize the DownloadsManager");
+ Assert.ok(
+ feed.downloadsManager.init.calledOnce,
+ "HighlightsFeed.downloadsManager.init was called"
+ );
+
+ feed.uninit();
+ // Let's make sure that uninit also removed these observers while we're here.
+ Assert.equal(
+ countObservers(SYNC_BOOKMARKS_FINISHED_EVENT),
+ INITIAL_SYNC_BOOKMARKS_FINISHED_EVENT_COUNT
+ );
+ Assert.equal(
+ countObservers(BOOKMARKS_RESTORE_SUCCESS_EVENT),
+ INITIAL_BOOKMARKS_RESTORE_SUCCESS_EVENT_COUNT
+ );
+ Assert.equal(
+ countObservers(BOOKMARKS_RESTORE_FAILED_EVENT),
+ INITIAL_BOOKMARKS_RESTORE_FAILED_EVENT_COUNT
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_observe_fetch_highlights() {
+ let topicDataPairs = [
+ {
+ description:
+ "should fetch highlights when we are done a sync for bookmarks",
+ shouldFetch: true,
+ topic: SYNC_BOOKMARKS_FINISHED_EVENT,
+ data: "bookmarks",
+ },
+ {
+ description: "should fetch highlights after a successful import",
+ shouldFetch: true,
+ topic: BOOKMARKS_RESTORE_SUCCESS_EVENT,
+ data: "html",
+ },
+ {
+ description: "should fetch highlights after a failed import",
+ shouldFetch: true,
+ topic: BOOKMARKS_RESTORE_FAILED_EVENT,
+ data: "json",
+ },
+ {
+ description:
+ "should not fetch highlights when we are doing a sync for something that is not bookmarks",
+ shouldFetch: false,
+ topic: SYNC_BOOKMARKS_FINISHED_EVENT,
+ data: "tabs",
+ },
+ {
+ description: "should not fetch highlights after a successful import",
+ shouldFetch: false,
+ topic: "someotherevent",
+ data: "bookmarks",
+ },
+ ];
+
+ for (let topicDataPair of topicDataPairs) {
+ info(`HighlightsFeed.observe ${topicDataPair.description}`);
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ sandbox.stub(feed, "fetchHighlights");
+ feed.observe(null, topicDataPair.topic, topicDataPair.data);
+
+ if (topicDataPair.shouldFetch) {
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights was called"
+ );
+ Assert.ok(feed.fetchHighlights.calledWith({ broadcast: true }));
+ } else {
+ Assert.ok(
+ feed.fetchHighlights.notCalled,
+ "HighlightsFeed.fetchHighlights was not called"
+ );
+ }
+
+ sandbox.restore();
+ }
+});
+
+add_task(async function test_filterForThumbnailExpiration_calls() {
+ info(
+ "HighlightsFeed.filterForThumbnailExpiration should pass rows.urls " +
+ "to the callback provided"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ let rows = [{ url: "foo.com" }, { url: "bar.com" }];
+
+ feed.store.state.Sections = [{ id: "highlights", rows, initialized: true }];
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ Assert.ok(stub.calledOnce, "Filter was called");
+ Assert.ok(stub.calledWithExactly(rows.map(r => r.url)));
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_filterForThumbnailExpiration_include_preview_image_url() {
+ info(
+ "HighlightsFeed.filterForThumbnailExpiration should include " +
+ "preview_image_url (if present) in the callback results"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ let 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.ok(stub.calledOnce, "Filter was called");
+ Assert.ok(stub.calledWithExactly(["foo.com", "bar.com", "bar.jpg"]));
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_filterForThumbnailExpiration_not_initialized() {
+ info(
+ "HighlightsFeed.filterForThumbnailExpiration should pass an empty " +
+ "array if not initialized"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ let rows = [{ url: "foo.com" }, { url: "bar.com" }];
+
+ feed.store.state.Sections = [{ rows, initialized: false }];
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ Assert.ok(stub.calledOnce, "Filter was called");
+ Assert.ok(stub.calledWithExactly([]));
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_TopSites_not_initialized() {
+ info(
+ "HighlightsFeed.fetchHighlights should return early if TopSites are not " +
+ "initialized"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ 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.ok(
+ NewTabUtils.activityStreamLinks.getHighlights.notCalled,
+ "NewTabUtils.activityStreamLinks.getHighlights was not called"
+ );
+ Assert.ok(
+ feed.linksCache.request.notCalled,
+ "HighlightsFeed.linksCache.request was not called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_sections_not_initialized() {
+ info(
+ "HighlightsFeed.fetchHighlights should return early if Sections are not " +
+ "initialized"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ 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.ok(
+ NewTabUtils.activityStreamLinks.getHighlights.notCalled,
+ "NewTabUtils.activityStreamLinks.getHighlights was not called"
+ );
+ Assert.ok(
+ feed.linksCache.request.notCalled,
+ "HighlightsFeed.linksCache.request was not called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_TopSites_initialized() {
+ info(
+ "HighlightsFeed.fetchHighlights should fetch Highlights if TopSites are " +
+ "initialised"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.spy(feed.linksCache, "request");
+
+ // fetchHighlights should continue
+ feed.store.state.TopSites.initialized = true;
+
+ await feed.fetchHighlights();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getHighlights.calledOnce,
+ "NewTabUtils.activityStreamLinks.getHighlights was called"
+ );
+ Assert.ok(
+ feed.linksCache.request.calledOnce,
+ "HighlightsFeed.linksCache.request was called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_chronological_order() {
+ info(
+ "HighlightsFeed.fetchHighlights should chronologically order highlight " +
+ "data types"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let 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
+ ];
+ let expectedChronological = [4, 6, 0, 5];
+ let expectedHistory = [1, 2, 3];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ [...expectedChronological, ...expectedHistory].forEach((link, index) => {
+ Assert.equal(
+ highlights[index].url,
+ links[link].url,
+ `highlight[${index}] should be link[${link}]`
+ );
+ });
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_TopSites_not_enabled() {
+ info(
+ "HighlightsFeed.fetchHighlights should fetch Highlights if TopSites " +
+ "are not enabled"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.spy(feed.linksCache, "request");
+
+ feed.store.state.Prefs.values["feeds.system.topsites"] = false;
+
+ await feed.fetchHighlights();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getHighlights.calledOnce,
+ "NewTabUtils.activityStreamLinks.getHighlights was called"
+ );
+ Assert.ok(
+ feed.linksCache.request.calledOnce,
+ "HighlightsFeed.linksCache.request was called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_TopSites_not_shown() {
+ info(
+ "HighlightsFeed.fetchHighlights should fetch Highlights if TopSites " +
+ "are not shown on NTP"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.spy(feed.linksCache, "request");
+
+ feed.store.state.Prefs.values["feeds.topsites"] = false;
+
+ await feed.fetchHighlights();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getHighlights.calledOnce,
+ "NewTabUtils.activityStreamLinks.getHighlights was called"
+ );
+ Assert.ok(
+ feed.linksCache.request.calledOnce,
+ "HighlightsFeed.linksCache.request was called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_add_hostname_hasImage() {
+ info(
+ "HighlightsFeed.fetchHighlights should add shortURL hostname and hasImage to each link"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [{ url: "https://mozilla.org" }];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights[0].hostname, shortURL(links[0]));
+ Assert.equal(highlights[0].hasImage, true);
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_add_existing_image() {
+ info(
+ "HighlightsFeed.fetchHighlights should add an existing image if it " +
+ "exists to the link without calling fetchImage"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [{ url: "https://mozilla.org", image: FAKE_IMAGE }];
+ sandbox.spy(feed, "fetchImage");
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights[0].image, FAKE_IMAGE);
+ Assert.ok(feed.fetchImage.notCalled, "HighlightsFeed.fetchImage not called");
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_correct_args() {
+ info(
+ "HighlightsFeed.fetchHighlights should call fetchImage with the correct " +
+ "arguments for new links"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ {
+ url: "https://mozilla.org",
+ preview_image_url: "https://mozilla.org/preview.jog",
+ },
+ ];
+ sandbox.spy(feed, "fetchImage");
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ await fetchHighlightsRows(feed);
+
+ Assert.ok(feed.fetchImage.calledOnce, "HighlightsFeed.fetchImage called");
+
+ let [arg] = feed.fetchImage.firstCall.args;
+ Assert.equal(arg.url, links[0].url);
+ Assert.equal(arg.preview_image_url, links[0].preview_image_url);
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_fetchHighlights_not_include_links_already_in_TopSites() {
+ info(
+ "HighlightsFeed.fetchHighlights should not include any links already in " +
+ "Top Sites"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ { url: "https://mozilla.org" },
+ { url: "http://www.topsite0.com" },
+ { url: "http://www.topsite1.com" },
+ { url: "http://www.topsite2.com" },
+ ];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 1);
+ Assert.equal(highlights[0].url, links[0].url);
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_fetchHighlights_not_include_history_already_in_TopSites() {
+ info(
+ "HighlightsFeed.fetchHighlights should include bookmark but not " +
+ "history already in Top Sites"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ { url: "http://www.topsite0.com", type: "bookmark" },
+ { url: "http://www.topsite1.com", type: "history" },
+ ];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 1);
+ Assert.equal(highlights[0].url, links[0].url);
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_fetchHighlights_not_include_history_same_hostname_as_bookmark() {
+ info(
+ "HighlightsFeed.fetchHighlights should not include history of same " +
+ "hostname as a bookmark"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/history", type: "history" },
+ ];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 1);
+ Assert.equal(highlights[0].url, links[0].url);
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_fetchHighlights_take_first_history_of_hostname() {
+ info(
+ "HighlightsFeed.fetchHighlights should take the first history of a hostname"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ { url: "https://site.com/first", type: "history" },
+ { url: "https://site.com/second", type: "history" },
+ { url: "https://other", type: "history" },
+ ];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 2);
+ Assert.equal(highlights[0].url, links[0].url);
+ Assert.equal(highlights[1].url, links[2].url);
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_fetchHighlights_take_bookmark_pocket_download_of_same_hostname() {
+ info(
+ "HighlightsFeed.fetchHighlights should take a bookmark, a pocket, and " +
+ "downloaded item of the same hostname"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ { url: "https://site.com/download", type: "download" },
+ ];
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ 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);
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_fetchHighlights_include_pocket_items() {
+ info(
+ "HighlightsFeed.fetchHighlights should includePocket pocket items when " +
+ "pref is true"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includePocket"] = true;
+ sandbox.spy(feed.linksCache, "request");
+
+ await fetchHighlightsRows(feed);
+
+ Assert.ok(
+ feed.linksCache.request.calledOnce,
+ "HighlightsFeed.linksCache.request called"
+ );
+ Assert.ok(
+ !feed.linksCache.request.firstCall.args[0].excludePocket,
+ "Should not be excluding Pocket items"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_do_not_include_pocket_items() {
+ info(
+ "HighlightsFeed.fetchHighlights should not includePocket pocket items " +
+ "when pref is false"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includePocket"] = false;
+ sandbox.spy(feed.linksCache, "request");
+
+ await fetchHighlightsRows(feed);
+
+ Assert.ok(
+ feed.linksCache.request.calledOnce,
+ "HighlightsFeed.linksCache.request called"
+ );
+ Assert.ok(
+ feed.linksCache.request.firstCall.args[0].excludePocket,
+ "Should be excluding Pocket items"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_do_not_include_downloads() {
+ info(
+ "HighlightsFeed.fetchHighlights should not include downloads when " +
+ "includeDownloads pref is false"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includeDownloads"] = false;
+ feed.downloadsManager.getDownloads = () => [
+ { url: "https://site1.com/download" },
+ { url: "https://site2.com/download" },
+ ];
+
+ let links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ ];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 2);
+ Assert.equal(highlights[0].url, links[0].url);
+ Assert.equal(highlights[1].url, links[1].url);
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_include_downloads() {
+ info(
+ "HighlightsFeed.fetchHighlights should include downloads when " +
+ "includeDownloads pref is true"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includeDownloads"] = true;
+ feed.downloadsManager.getDownloads = () => [
+ { url: "https://site.com/download" },
+ ];
+
+ let links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ ];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ 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.equal(highlights[2].type, "download");
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_take_one_download() {
+ info("HighlightsFeed.fetchHighlights should only take 1 download");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includeDownloads"] = true;
+ feed.downloadsManager.getDownloads = () => [
+ { url: "https://site1.com/download" },
+ { url: "https://site2.com/download" },
+ ];
+
+ let links = [{ url: "https://site.com/bookmark", type: "bookmark" }];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights.length, 2);
+ Assert.equal(highlights[0].url, links[0].url);
+ Assert.equal(highlights[1].url, "https://site1.com/download");
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_chronological_sort() {
+ info(
+ "HighlightsFeed.fetchHighlights should sort bookmarks, pocket, " +
+ "and downloads chronologically"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includeDownloads"] = true;
+ feed.downloadsManager.getDownloads = () => [
+ {
+ url: "https://site1.com/download",
+ type: "download",
+ date_added: Date.now(),
+ },
+ ];
+
+ let 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(),
+ },
+ ];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ 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
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_fetchHighlights_set_type_to_bookmark_on_bookmarkGuid() {
+ info(
+ "HighlightsFeed.fetchHighlights should set type to bookmark if there " +
+ "is a bookmarkGuid"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values["section.highlights.includeBookmarks"] = true;
+ feed.downloadsManager.getDownloads = () => [
+ {
+ url: "https://site1.com/download",
+ type: "download",
+ date_added: Date.now(),
+ },
+ ];
+
+ let links = [
+ {
+ url: "https://mozilla.org",
+ type: "history",
+ bookmarkGuid: "1234567890",
+ },
+ ];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights[0].type, "bookmark");
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_fetchHighlights_keep_history_type_on_bookmarkGuid() {
+ info(
+ "HighlightsFeed.fetchHighlights should keep history type if there is a " +
+ "bookmarkGuid but don't include bookmarks"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.store.state.Prefs.values[
+ "section.highlights.includeBookmarks"
+ ] = false;
+
+ let links = [
+ {
+ url: "https://mozilla.org",
+ type: "history",
+ bookmarkGuid: "1234567890",
+ },
+ ];
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves(links);
+
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.equal(highlights[0].type, "history");
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_fetchHighlights_filter_adult() {
+ info("HighlightsFeed.fetchHighlights should filter out adult pages");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.stub(FilterAdult, "filter").returns([]);
+ let highlights = await fetchHighlightsRows(feed);
+
+ Assert.ok(FilterAdult.filter.calledOnce, "FilterAdult.filter called");
+ Assert.equal(highlights.length, 0);
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchHighlights_no_expose_internal_link_props() {
+ info(
+ "HighlightsFeed.fetchHighlights should not expose internal link properties"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ let highlights = await fetchHighlightsRows(feed);
+ let internal = Object.keys(highlights[0]).filter(key => key.startsWith("__"));
+
+ Assert.equal(internal.join(""), "");
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_fetchHighlights_broadcast_when_feed_not_initialized() {
+ info(
+ "HighlightsFeed.fetchHighlights should broadcast if feed is not initialized"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves([]);
+ sandbox.stub(SectionsManager, "updateSection");
+ await feed.fetchHighlights();
+
+ Assert.ok(
+ SectionsManager.updateSection.calledOnce,
+ "SectionsManager.updateSection called once"
+ );
+ Assert.ok(
+ SectionsManager.updateSection.calledWithExactly(
+ SECTION_ID,
+ { rows: [] },
+ true,
+ undefined
+ )
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_fetchHighlights_broadcast_on_broadcast_in_options() {
+ info(
+ "HighlightsFeed.fetchHighlights should broadcast if options.broadcast is true"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves([]);
+ feed.store.state.Sections[0].initialized = true;
+
+ sandbox.stub(SectionsManager, "updateSection");
+ await feed.fetchHighlights({ broadcast: true });
+
+ Assert.ok(
+ SectionsManager.updateSection.calledOnce,
+ "SectionsManager.updateSection called once"
+ );
+ Assert.ok(
+ SectionsManager.updateSection.calledWithExactly(
+ SECTION_ID,
+ { rows: [] },
+ true,
+ undefined
+ )
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_fetchHighlights_no_broadcast() {
+ info(
+ "HighlightsFeed.fetchHighlights should not broadcast if " +
+ "options.broadcast is false and initialized is true"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ NewTabUtils.activityStreamLinks.getHighlights.resolves([]);
+ feed.store.state.Sections[0].initialized = true;
+
+ sandbox.stub(SectionsManager, "updateSection");
+ await feed.fetchHighlights({ broadcast: false });
+
+ Assert.ok(
+ SectionsManager.updateSection.calledOnce,
+ "SectionsManager.updateSection called once"
+ );
+ Assert.ok(
+ SectionsManager.updateSection.calledWithExactly(
+ SECTION_ID,
+ { rows: [] },
+ false,
+ undefined
+ )
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_fetchImage_capture_if_available() {
+ info("HighlightsFeed.fetchImage should capture the image, if available");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.stub(Screenshots, "getScreenshotForURL");
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+
+ await fetchImage(feed, {
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ });
+
+ Assert.ok(
+ Screenshots.getScreenshotForURL.calledOnce,
+ "Screenshots.getScreenshotForURL called once"
+ );
+ Assert.ok(Screenshots.getScreenshotForURL.calledWith(FAKE_IMAGE_URL));
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchImage_fallback_to_screenshot() {
+ info("HighlightsFeed.fetchImage should fall back to capturing a screenshot");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.stub(Screenshots, "getScreenshotForURL");
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+
+ await fetchImage(feed, { url: FAKE_URL });
+
+ Assert.ok(
+ Screenshots.getScreenshotForURL.calledOnce,
+ "Screenshots.getScreenshotForURL called once"
+ );
+ Assert.ok(Screenshots.getScreenshotForURL.calledWith(FAKE_URL));
+
+ sandbox.restore();
+});
+
+add_task(async function test_fetchImage_updateSectionCard_args() {
+ info(
+ "HighlightsFeed.fetchImage should call " +
+ "SectionsManager.updateSectionCard with the right arguments"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.stub(SectionsManager, "updateSectionCard");
+ sandbox.stub(Screenshots, "getScreenshotForURL").resolves(FAKE_IMAGE);
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+
+ await fetchImage(feed, {
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ });
+ Assert.ok(
+ SectionsManager.updateSectionCard.calledOnce,
+ "SectionsManager.updateSectionCard called"
+ );
+ Assert.ok(
+ SectionsManager.updateSectionCard.calledWith(
+ "highlights",
+ FAKE_URL,
+ { image: FAKE_IMAGE },
+ true
+ )
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_fetchImage_no_update_card_with_image() {
+ info("HighlightsFeed.fetchImage should not update the card with the image");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.stub(SectionsManager, "updateSectionCard");
+ sandbox.stub(Screenshots, "getScreenshotForURL").resolves(FAKE_IMAGE);
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+
+ let card = {
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ };
+ await fetchImage(feed, card);
+ Assert.ok(!card.image, "Image not set on card");
+ sandbox.restore();
+});
+
+add_task(async function test_uninit_disable_section() {
+ info("HighlightsFeed.onAction(UNINIT) should disable its section");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.init();
+
+ sandbox.stub(SectionsManager, "disableSection");
+ feed.onAction({ type: at.UNINIT });
+ Assert.ok(
+ SectionsManager.disableSection.calledOnce,
+ "SectionsManager.disableSection called"
+ );
+ Assert.ok(SectionsManager.disableSection.calledWith(SECTION_ID));
+ sandbox.restore();
+});
+
+add_task(async function test_uninit_remove_expiration_filter() {
+ info("HighlightsFeed.onAction(UNINIT) should remove the expiration filter");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ feed.init();
+
+ sandbox.stub(PageThumbs, "removeExpirationFilter");
+ feed.onAction({ type: at.UNINIT });
+ Assert.ok(
+ PageThumbs.removeExpirationFilter.calledOnce,
+ "PageThumbs.removeExpirationFilter called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_relay_to_DownloadsManager_onAction() {
+ info(
+ "HighlightsFeed.onAction should relay all actions to " +
+ "DownloadsManager.onAction"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+ sandbox.stub(feed.downloadsManager, "onAction");
+
+ let action = {
+ type: at.COPY_DOWNLOAD_LINK,
+ data: { url: "foo.png" },
+ _target: {},
+ };
+ feed.onAction(action);
+
+ Assert.ok(
+ feed.downloadsManager.onAction.calledOnce,
+ "HighlightsFeed.downloadManager.onAction called"
+ );
+ Assert.ok(feed.downloadsManager.onAction.calledWith(action));
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_fetch_highlights_on_SYSTEM_TICK() {
+ info("HighlightsFeed.onAction should fetch highlights on SYSTEM_TICK");
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ await feed.fetchHighlights();
+
+ sandbox.spy(feed, "fetchHighlights");
+ feed.onAction({ type: at.SYSTEM_TICK });
+
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights called"
+ );
+ Assert.ok(
+ feed.fetchHighlights.calledWithExactly({
+ broadcast: false,
+ isStartup: false,
+ })
+ );
+ sandbox.restore();
+});
+
+add_task(
+ async function test_onAction_fetch_highlights_on_PREF_CHANGED_for_include() {
+ info(
+ "HighlightsFeed.onAction should fetch highlights on PREF_CHANGED " +
+ "for include prefs"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.spy(feed, "fetchHighlights");
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "section.highlights.includeBookmarks" },
+ });
+
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights called"
+ );
+ Assert.ok(feed.fetchHighlights.calledWithExactly({ broadcast: true }));
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_onAction_no_fetch_highlights_on_PREF_CHANGED_for_other() {
+ info(
+ "HighlightsFeed.onAction should not fetch highlights on PREF_CHANGED " +
+ "for other prefs"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ sandbox.spy(feed, "fetchHighlights");
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "section.topstories.pocketCta" },
+ });
+
+ Assert.ok(
+ feed.fetchHighlights.notCalled,
+ "HighlightsFeed.fetchHighlights not called"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_onAction_fetch_highlights_on_actions() {
+ info("HighlightsFeed.onAction should fetch highlights for various actions");
+
+ let actions = [
+ {
+ actionType: "PLACES_HISTORY_CLEARED",
+ expectsExpire: false,
+ expectsBroadcast: true,
+ },
+ {
+ actionType: "DOWNLOAD_CHANGED",
+ expectsExpire: false,
+ expectsBroadcast: true,
+ },
+ {
+ actionType: "PLACES_LINKS_CHANGED",
+ expectsExpire: true,
+ expectsBroadcast: false,
+ },
+ {
+ actionType: "PLACES_LINK_BLOCKED",
+ expectsExpire: false,
+ expectsBroadcast: true,
+ },
+ {
+ actionType: "PLACES_SAVED_TO_POCKET",
+ expectsExpire: true,
+ expectsBroadcast: false,
+ },
+ ];
+ for (let action of actions) {
+ info(
+ `HighlightsFeed.onAction should fetch highlights on ${action.actionType}`
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ await feed.fetchHighlights();
+ sandbox.spy(feed, "fetchHighlights");
+ sandbox.stub(feed.linksCache, "expire");
+
+ feed.onAction({ type: at[action.actionType] });
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights called"
+ );
+ Assert.ok(
+ feed.fetchHighlights.calledWith({ broadcast: action.expectsBroadcast })
+ );
+
+ if (action.expectsExpire) {
+ Assert.ok(
+ feed.linksCache.expire.calledOnce,
+ "HighlightsFeed.linksCache.expire called"
+ );
+ }
+
+ sandbox.restore();
+ }
+});
+
+add_task(
+ async function test_onAction_fetch_highlights_no_broadcast_on_TOP_SITES_UPDATED() {
+ info(
+ "HighlightsFeed.onAction should fetch highlights with broadcast " +
+ "false on TOP_SITES_UPDATED"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ await feed.fetchHighlights();
+ sandbox.spy(feed, "fetchHighlights");
+
+ feed.onAction({ type: at.TOP_SITES_UPDATED });
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights called"
+ );
+ Assert.ok(
+ feed.fetchHighlights.calledWithExactly({
+ broadcast: false,
+ isStartup: false,
+ })
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_onAction_fetch_highlights_on_deleting_archiving_pocket() {
+ info(
+ "HighlightsFeed.onAction should call fetchHighlights when deleting " +
+ "or archiving from Pocket"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let feed = getHighlightsFeedForTest(sandbox);
+
+ await feed.fetchHighlights();
+ sandbox.spy(feed, "fetchHighlights");
+
+ feed.onAction({
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ data: { pocket_id: 12345 },
+ });
+ Assert.ok(
+ feed.fetchHighlights.calledOnce,
+ "HighlightsFeed.fetchHighlights called"
+ );
+ Assert.ok(feed.fetchHighlights.calledWithExactly({ broadcast: true }));
+
+ sandbox.restore();
+ }
+);
diff --git a/browser/components/newtab/test/xpcshell/test_PlacesFeed.js b/browser/components/newtab/test/xpcshell/test_PlacesFeed.js
new file mode 100644
index 0000000000..8e7c42d639
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_PlacesFeed.js
@@ -0,0 +1,1812 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+ChromeUtils.defineESModuleGetters(this, {
+ AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
+ 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",
+ PlacesFeed: "resource://activity-stream/lib/PlacesFeed.sys.mjs",
+ PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
+ SearchService: "resource://gre/modules/SearchService.sys.mjs",
+ sinon: "resource://testing-common/Sinon.sys.mjs",
+ TestUtils: "resource://testing-common/TestUtils.sys.mjs",
+});
+
+const { PlacesObserver } = PlacesFeed;
+
+const FAKE_BOOKMARK = {
+ bookmarkGuid: "D3r1sKRobtbW",
+ bookmarkTitle: "Foo",
+ dateAdded: 123214232,
+ url: "foo.com",
+};
+const TYPE_BOOKMARK = 1; // This is fake, for testing
+const SOURCES = {
+ DEFAULT: 0,
+ SYNC: 1,
+ IMPORT: 2,
+ RESTORE: 5,
+ RESTORE_ON_STARTUP: 6,
+};
+
+// The event dispatched in NewTabUtils when a link is blocked;
+const BLOCKED_EVENT = "newtab-linkBlocked";
+
+const TOP_SITES_BLOCKED_SPONSORS_PREF = "browser.topsites.blockedSponsors";
+const POCKET_SITE_PREF = "extensions.pocket.site";
+
+function getPlacesFeedForTest(sandbox) {
+ let feed = new PlacesFeed();
+ feed.store = {
+ dispatch: sandbox.spy(),
+ feeds: {
+ get: sandbox.stub(),
+ },
+ };
+
+ sandbox.stub(AboutNewTab, "activityStream").value({
+ store: feed.store,
+ });
+
+ return feed;
+}
+
+add_task(async function test_construction() {
+ info("PlacesFeed construction should work");
+ let feed = new PlacesFeed();
+ Assert.ok(feed, "PlacesFeed could be constructed.");
+});
+
+add_task(async function test_PlacesObserver() {
+ info("PlacesFeed should have a PlacesObserver that dispatches to the store");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let action = { type: "FOO" };
+ feed.placesObserver.dispatch(action);
+
+ await TestUtils.waitForTick();
+ Assert.ok(feed.store.dispatch.calledOnce, "PlacesFeed.store dispatch called");
+ Assert.equal(feed.store.dispatch.firstCall.args[0].type, action.type);
+
+ sandbox.restore();
+});
+
+add_task(async function test_addToBlockedTopSitesSponsors_add_to_blocklist() {
+ info(
+ "PlacesFeed.addToBlockedTopSitesSponsors should add the blocked sponsors " +
+ "to the blocklist"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ feed.addToBlockedTopSitesSponsors([
+ { url: "test.com" },
+ { url: "test1.com" },
+ ]);
+
+ let blockedSponsors = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF)
+ );
+ Assert.deepEqual(
+ new Set(["foo", "bar", "test", "test1"]),
+ new Set(blockedSponsors)
+ );
+
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
+
+add_task(async function test_addToBlockedTopSitesSponsors_no_dupes() {
+ info(
+ "PlacesFeed.addToBlockedTopSitesSponsors should not add duplicate " +
+ "sponsors to the blocklist"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ feed.addToBlockedTopSitesSponsors([
+ { url: "foo.com" },
+ { url: "bar.com" },
+ { url: "test.com" },
+ ]);
+
+ let blockedSponsors = JSON.parse(
+ Services.prefs.getStringPref(TOP_SITES_BLOCKED_SPONSORS_PREF)
+ );
+ Assert.deepEqual(new Set(["foo", "bar", "test"]), new Set(blockedSponsors));
+
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_PlacesEvents() {
+ info(
+ "PlacesFeed.onAction should add bookmark, history, places, blocked " +
+ "observers on INIT"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed.placesObserver, "handlePlacesEvent");
+
+ feed.onAction({ type: at.INIT });
+ // The PlacesObserver registration happens at the next tick of the
+ // event loop.
+ await TestUtils.waitForTick();
+
+ // These are some dummy PlacesEvents that we'll pass through the
+ // PlacesObserver service, checking that the handlePlacesEvent receives them
+ // properly.
+ let notifications = [
+ new PlacesBookmarkAddition({
+ dateAdded: 0,
+ guid: "dQFSYrbM5SJN",
+ id: -1,
+ index: 0,
+ isTagging: false,
+ itemType: 1,
+ parentGuid: "n_HOEFys1qsL",
+ parentId: -2,
+ source: 0,
+ title: "test-123",
+ tags: "tags",
+ url: "http://example.com/test-123",
+ frecency: 0,
+ hidden: false,
+ visitCount: 0,
+ lastVisitDate: 0,
+ targetFolderGuid: null,
+ targetFolderItemId: -1,
+ targetFolderTitle: null,
+ }),
+ new PlacesBookmarkRemoved({
+ id: -1,
+ url: "http://example.com/test-123",
+ title: "test-123",
+ itemType: 1,
+ parentId: -2,
+ index: 0,
+ guid: "M3WYgJlm2Jlx",
+ parentGuid: "DO1f97R4KC3Y",
+ source: 0,
+ isTagging: false,
+ isDescendantRemoval: false,
+ }),
+ new PlacesHistoryCleared(),
+ new PlacesVisitRemoved({
+ url: "http://example.com/test-123",
+ pageGuid: "sPVcW2V4H7Rg",
+ reason: PlacesVisitRemoved.REASON_DELETED,
+ transitionType: 0,
+ isRemovedFromStore: true,
+ isPartialVisistsRemoval: false,
+ }),
+ ];
+
+ for (let notification of notifications) {
+ PlacesUtils.observers.notifyListeners([notification]);
+ Assert.ok(
+ feed.placesObserver.handlePlacesEvent.calledOnce,
+ "PlacesFeed.handlePlacesEvent called"
+ );
+ Assert.ok(feed.placesObserver.handlePlacesEvent.calledWith([notification]));
+ feed.placesObserver.handlePlacesEvent.resetHistory();
+ }
+
+ info(
+ "PlacesFeed.onAction remove bookmark, history, places, blocked " +
+ "observers, and timers on UNINIT"
+ );
+
+ let placesChangedTimerCancel = sandbox.spy();
+ feed.placesChangedTimer = {
+ cancel: placesChangedTimerCancel,
+ };
+
+ // Unlike INIT, UNINIT removes the observers synchronously, so no need to
+ // wait for the event loop to tick around again.
+ feed.onAction({ type: at.UNINIT });
+
+ for (let notification of notifications) {
+ PlacesUtils.observers.notifyListeners([notification]);
+ Assert.ok(
+ feed.placesObserver.handlePlacesEvent.notCalled,
+ "PlacesFeed.handlePlacesEvent not called"
+ );
+ feed.placesObserver.handlePlacesEvent.resetHistory();
+ }
+
+ Assert.equal(feed.placesChangedTimer, null);
+ Assert.ok(placesChangedTimerCancel.calledOnce);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_BLOCK_URL() {
+ info("PlacesFeed.onAction should block a url on BLOCK_URL");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "blockURL");
+
+ feed.onAction({
+ type: at.BLOCK_URL,
+ data: [{ url: "apple.com", pocket_id: 1234 }],
+ });
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.blockURL.calledWith({
+ url: "apple.com",
+ pocket_id: 1234,
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_BLOCK_URL_topsites_sponsors() {
+ info(
+ "PlacesFeed.onAction BLOCK_URL should update the blocked top " +
+ "sites sponsors"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "addToBlockedTopSitesSponsors");
+
+ feed.onAction({
+ type: at.BLOCK_URL,
+ data: [{ url: "foo.com", pocket_id: 1234, isSponsoredTopSite: 1 }],
+ });
+ Assert.ok(feed.addToBlockedTopSitesSponsors.calledWith([{ url: "foo.com" }]));
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_BOOKMARK_URL() {
+ info("PlacesFeed.onAction should bookmark a url on BOOKMARK_URL");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "addBookmark");
+
+ let data = { url: "pear.com", title: "A pear" };
+ let _target = { browser: { ownerGlobal() {} } };
+ feed.onAction({ type: at.BOOKMARK_URL, data, _target });
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.addBookmark.calledWith(
+ data,
+ _target.browser.ownerGlobal
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_DELETE_BOOKMARK_BY_ID() {
+ info("PlacesFeed.onAction should delete a bookmark on DELETE_BOOKMARK_BY_ID");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "deleteBookmark");
+
+ feed.onAction({ type: at.DELETE_BOOKMARK_BY_ID, data: "g123kd" });
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.deleteBookmark.calledWith("g123kd")
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_DELETE_HISTORY_URL() {
+ info(
+ "PlacesFeed.onAction should delete a history entry on DELETE_HISTORY_URL"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "deleteHistoryEntry");
+ sandbox.stub(NewTabUtils.activityStreamLinks, "blockURL");
+
+ feed.onAction({
+ type: at.DELETE_HISTORY_URL,
+ data: { url: "guava.com", forceBlock: null },
+ });
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.deleteHistoryEntry.calledWith("guava.com")
+ );
+ Assert.ok(NewTabUtils.activityStreamLinks.blockURL.notCalled);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_DELETE_HISTORY_URL_and_block() {
+ info(
+ "PlacesFeed.onAction should delete a history entry on " +
+ "DELETE_HISTORY_URL and force a site to be blocked if specified"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "deleteHistoryEntry");
+ sandbox.stub(NewTabUtils.activityStreamLinks, "blockURL");
+
+ feed.onAction({
+ type: at.DELETE_HISTORY_URL,
+ data: { url: "guava.com", forceBlock: "g123kd" },
+ });
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.deleteHistoryEntry.calledWith("guava.com")
+ );
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.blockURL.calledWith({
+ url: "guava.com",
+ pocket_id: undefined,
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_NEW_WINDOW() {
+ info(
+ "PlacesFeed.onAction should call openTrustedLinkIn with the " +
+ "correct url, where and params on OPEN_NEW_WINDOW"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openWindowAction = {
+ type: at.OPEN_NEW_WINDOW,
+ data: { url: "https://foo.com" },
+ _target: { browser: { ownerGlobal: { openTrustedLinkIn } } },
+ };
+
+ feed.onAction(openWindowAction);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [url, where, params] = openTrustedLinkIn.firstCall.args;
+ Assert.equal(url, "https://foo.com");
+ Assert.equal(where, "window");
+ Assert.ok(!params.private);
+ Assert.ok(!params.forceForeground);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_PRIVATE_WINDOW() {
+ info(
+ "PlacesFeed.onAction should call openTrustedLinkIn with the " +
+ "correct url, where, params and privacy args on OPEN_PRIVATE_WINDOW"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openWindowAction = {
+ type: at.OPEN_PRIVATE_WINDOW,
+ data: { url: "https://foo.com" },
+ _target: { browser: { ownerGlobal: { openTrustedLinkIn } } },
+ };
+
+ feed.onAction(openWindowAction);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [url, where, params] = openTrustedLinkIn.firstCall.args;
+ Assert.equal(url, "https://foo.com");
+ Assert.equal(where, "window");
+ Assert.ok(params.private);
+ Assert.ok(!params.forceForeground);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_LINK() {
+ info(
+ "PlacesFeed.onAction should call openTrustedLinkIn with the " +
+ "correct url, where and params on OPEN_LINK"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openLinkAction = {
+ type: at.OPEN_LINK,
+ data: { url: "https://foo.com" },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+ feed.onAction(openLinkAction);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [url, where, params] = openTrustedLinkIn.firstCall.args;
+ Assert.equal(url, "https://foo.com");
+ Assert.equal(where, "current");
+ Assert.ok(!params.private);
+ Assert.ok(!params.forceForeground);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_LINK_referrer() {
+ info("PlacesFeed.onAction should open link with referrer on OPEN_LINK");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let 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);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [, , params] = openTrustedLinkIn.firstCall.args;
+ Assert.equal(params.referrerInfo.referrerPolicy, 5);
+ Assert.equal(
+ params.referrerInfo.originalReferrer.spec,
+ "https://foo.com/ref"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_LINK_typed_bonus() {
+ info(
+ "PlacesFeed.onAction should mark link with typed bonus as " +
+ "typed before opening OPEN_LINK"
+ );
+ let sandbox = sinon.createSandbox();
+ let callOrder = [];
+ // We can't stub out PlacesUtils.history.markPageAsTyped, since that's an
+ // XPCOM component. We'll stub out history instead.
+ sandbox.stub(PlacesUtils, "history").get(() => {
+ return {
+ markPageAsTyped: sandbox.stub().callsFake(() => {
+ callOrder.push("markPageAsTyped");
+ }),
+ };
+ });
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub().callsFake(() => {
+ callOrder.push("openTrustedLinkIn");
+ });
+ let openLinkAction = {
+ type: at.OPEN_LINK,
+ data: {
+ typedBonus: true,
+ url: "https://foo.com",
+ },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "tab" },
+ },
+ },
+ };
+ feed.onAction(openLinkAction);
+
+ Assert.deepEqual(callOrder, ["markPageAsTyped", "openTrustedLinkIn"]);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_LINK_pocket() {
+ info(
+ "PlacesFeed.onAction should open the pocket link if it's a " +
+ "pocket story on OPEN_LINK"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openLinkAction = {
+ type: at.OPEN_LINK,
+ data: {
+ url: "https://foo.com",
+ open_url: "https://getpocket.com/foo",
+ type: "pocket",
+ },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [url, where, params] = openTrustedLinkIn.firstCall.args;
+ Assert.equal(url, "https://getpocket.com/foo");
+ Assert.equal(where, "current");
+ Assert.ok(!params.private);
+ Assert.ok(!params.forceForeground);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_OPEN_LINK_not_http() {
+ info("PlacesFeed.onAction should not open link if not http");
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openLinkAction = {
+ type: at.OPEN_LINK,
+ data: { url: "file:///foo.com" },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ Assert.ok(openTrustedLinkIn.notCalled, "openTrustedLinkIn not called");
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_FILL_SEARCH_TERM() {
+ info(
+ "PlacesFeed.onAction should call fillSearchTopSiteTerm " +
+ "on FILL_SEARCH_TERM"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "fillSearchTopSiteTerm");
+
+ feed.onAction({ type: at.FILL_SEARCH_TERM });
+
+ Assert.ok(
+ feed.fillSearchTopSiteTerm.calledOnce,
+ "PlacesFeed.fillSearchTopSiteTerm called"
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_ABOUT_SPONSORED_TOP_SITES() {
+ info(
+ "PlacesFeed.onAction should call openTrustedLinkIn with the " +
+ "correct SUMO url on ABOUT_SPONSORED_TOP_SITES"
+ );
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+ let openTrustedLinkIn = sandbox.stub();
+ let openLinkAction = {
+ type: at.ABOUT_SPONSORED_TOP_SITES,
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [url, where] = openTrustedLinkIn.firstCall.args;
+ Assert.ok(url.endsWith("sponsor-privacy"));
+ Assert.equal(where, "tab");
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_FILL_SEARCH_TERM() {
+ info(
+ "PlacesFeed.onAction should set the URL bar value to the label value " +
+ "on FILL_SEARCH_TERM"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(SearchService.prototype, "getEngineByAlias").resolves(null);
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let locationBar = { search: sandbox.stub() };
+ let action = {
+ type: at.FILL_SEARCH_TERM,
+ data: { label: "@Foo" },
+ _target: { browser: { ownerGlobal: { gURLBar: locationBar } } },
+ };
+
+ await feed.onAction(action);
+
+ Assert.ok(locationBar.search.calledOnce, "gURLBar.search called");
+ Assert.ok(
+ locationBar.search.calledWithExactly("@Foo", {
+ searchEngine: null,
+ searchModeEntry: "topsites_newtab",
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_SAVE_TO_POCKET() {
+ info("PlacesFeed.onAction should call saveToPocket on SAVE_TO_POCKET");
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "saveToPocket");
+
+ let action = {
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+
+ await feed.onAction(action);
+
+ Assert.ok(feed.saveToPocket.calledOnce, "PlacesFeed.saveToPocket called");
+ Assert.ok(
+ feed.saveToPocket.calledWithExactly(
+ action.data.site,
+ action._target.browser
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_SAVE_TO_POCKET_not_logged_in() {
+ info(
+ "PlacesFeed.onAction should openTrustedLinkIn with sendToPocket " +
+ "if not logged in on SAVE_TO_POCKET"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(pktApi, "isUserLoggedIn").returns(false);
+ sandbox.stub(NimbusFeatures.pocketNewtab, "getVariable").returns(true);
+ sandbox.stub(ExperimentAPI, "getExperiment").returns({
+ slug: "slug",
+ branch: { slug: "branch-slug" },
+ });
+ Services.prefs.setStringPref(POCKET_SITE_PREF, "getpocket.com");
+
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let openTrustedLinkIn = sandbox.stub();
+ let action = {
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+
+ await feed.onAction(action);
+
+ Assert.ok(openTrustedLinkIn.calledOnce, "openTrustedLinkIn called");
+ let [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");
+
+ Services.prefs.clearUserPref(POCKET_SITE_PREF);
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_SAVE_TO_POCKET_logged_in() {
+ info(
+ "PlacesFeed.onAction should call " +
+ "NewTabUtils.activityStreamLinks.addPocketEntry if we are saving a " +
+ "pocket story on SAVE_TO_POCKET"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(pktApi, "isUserLoggedIn").returns(true);
+ sandbox.stub(NewTabUtils.activityStreamLinks, "addPocketEntry");
+
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let openTrustedLinkIn = sandbox.stub();
+ let action = {
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+
+ await feed.onAction(action);
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.addPocketEntry.calledOnce,
+ "NewTabUtils.activityStreamLinks.addPocketEntry called"
+ );
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.addPocketEntry.calledWithExactly(
+ action.data.site.url,
+ action.data.site.title,
+ action._target.browser
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_saveToPocket_addPocketEntry_rejects() {
+ info(
+ "PlacesFeed.saveToPocket should still resolve if " +
+ "NewTabUtils.activityStreamLinks.addPocketEntry rejects"
+ );
+ let sandbox = sinon.createSandbox();
+ let e = new Error("Error");
+
+ sandbox.stub(NewTabUtils.activityStreamLinks, "addPocketEntry").rejects(e);
+
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let openTrustedLinkIn = sandbox.stub();
+ let action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+
+ try {
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ Assert.ok(true, "PlacesFeed.saveToPocket Promise resolved");
+ } catch {
+ Assert.ok(false, "PlacesFeed.saveToPocket Promise rejected");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_saveToPocket_broadcast_to_content() {
+ info(
+ "PlacesFeed.saveToPocket should broadcast to content if we " +
+ "successfully added a link to Pocket"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(pktApi, "isUserLoggedIn").returns(true);
+
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "addPocketEntry")
+ .resolves({ item: { open_url: "pocket.com/itemID", item_id: 1234 } });
+
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let openTrustedLinkIn = sandbox.stub();
+ let action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ Assert.ok(
+ feed.store.dispatch.calledOnce,
+ "PlacesFeed.store.dispatch was called"
+ );
+ 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",
+ });
+
+ sandbox.restore();
+});
+
+add_task(async function test_saveToPocket_broadcast_only_on_data() {
+ info(
+ "PlacesFeed.saveToPocket should broadcast to content if we " +
+ "successfully added a link to Pocket"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(pktApi, "isUserLoggedIn").returns(true);
+
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "addPocketEntry")
+ .resolves(null);
+
+ let feed = getPlacesFeedForTest(sandbox);
+
+ let openTrustedLinkIn = sandbox.stub();
+ let action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: {
+ browser: {
+ ownerGlobal: {
+ openTrustedLinkIn,
+ },
+ },
+ },
+ };
+
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ Assert.ok(
+ feed.store.dispatch.notCalled,
+ "PlacesFeed.store.dispatch was not called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_DELETE_FROM_POCKET() {
+ info(
+ "PlacesFeed.onAction should call deleteFromPocket on DELETE_FROM_POCKET"
+ );
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "deleteFromPocket");
+
+ feed.onAction({
+ type: at.DELETE_FROM_POCKET,
+ data: { pocket_id: 12345 },
+ });
+
+ Assert.ok(
+ feed.deleteFromPocket.calledOnce,
+ "PlacesFeed.deleteFromPocket called"
+ );
+ Assert.ok(feed.deleteFromPocket.calledWithExactly(12345));
+
+ sandbox.restore();
+});
+
+add_task(async function test_deleteFromPocket_resolves() {
+ info(
+ "PlacesFeed.deleteFromPocket should still resolve if deletePocketEntry " +
+ "rejects"
+ );
+ let sandbox = sinon.createSandbox();
+ let e = new Error("Error");
+ sandbox.stub(NewTabUtils.activityStreamLinks, "deletePocketEntry").rejects(e);
+
+ let feed = getPlacesFeedForTest(sandbox);
+ await feed.deleteFromPocket(12345);
+
+ try {
+ await feed.deleteFromPocket(12345);
+ Assert.ok(true, "PlacesFeed.deleteFromPocket Promise resolved");
+ } catch {
+ Assert.ok(false, "PlacesFeed.deleteFromPocket Promise rejected");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_deleteFromPocket_calls_deletePocketEntry() {
+ info(
+ "PlacesFeed.deleteFromPocket should call " +
+ "NewTabUtils.deletePocketEntry and dispatch " +
+ "POCKET_LINK_DELETED_OR_ARCHIVED when deleting from Pocket"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.activityStreamLinks, "deletePocketEntry");
+
+ let feed = getPlacesFeedForTest(sandbox);
+ await feed.deleteFromPocket(12345);
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.deletePocketEntry.calledOnce,
+ "NewTabUtils.activityStreamLinks.deletePocketEntry called"
+ );
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.deletePocketEntry.calledWithExactly(12345)
+ );
+ Assert.ok(
+ feed.store.dispatch.calledOnce,
+ "PlacesFeed.store.dispatch was called"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly({
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_ARCHIVE_FROM_POCKET() {
+ info(
+ "PlacesFeed.onAction should call archiveFromPocket on ARCHIVE_FROM_POCKET"
+ );
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "archiveFromPocket");
+
+ await feed.onAction({
+ type: at.ARCHIVE_FROM_POCKET,
+ data: { pocket_id: 12345 },
+ });
+
+ Assert.ok(
+ feed.archiveFromPocket.calledOnce,
+ "PlacesFeed.archiveFromPocket called"
+ );
+ Assert.ok(feed.archiveFromPocket.calledWithExactly(12345));
+
+ sandbox.restore();
+});
+
+add_task(async function test_archiveFromPocket_resolves() {
+ info(
+ "PlacesFeed.archiveFromPocket should resolve if archivePocketEntry rejects"
+ );
+ let sandbox = sinon.createSandbox();
+ let e = new Error("Error");
+ sandbox
+ .stub(NewTabUtils.activityStreamLinks, "archivePocketEntry")
+ .rejects(e);
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "archiveFromPocket");
+
+ try {
+ await feed.archiveFromPocket(12345);
+ Assert.ok(true, "PlacesFeed.archiveFromPocket Promise resolved");
+ } catch {
+ Assert.ok(false, "PlacesFeed.archiveFromPocket Promise rejected");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_archiveFromPocket_calls_archivePocketEntry() {
+ info(
+ "PlacesFeed.archiveFromPocket should call " +
+ "NewTabUtils.archivePocketEntry and dispatch " +
+ "POCKET_LINK_DELETED_OR_ARCHIVED when deleting from Pocket"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.activityStreamLinks, "archivePocketEntry");
+
+ let feed = getPlacesFeedForTest(sandbox);
+ await feed.archiveFromPocket(12345);
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.archivePocketEntry.calledOnce,
+ "NewTabUtils.activityStreamLinks.archivePocketEntry called"
+ );
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.archivePocketEntry.calledWithExactly(12345)
+ );
+ Assert.ok(
+ feed.store.dispatch.calledOnce,
+ "PlacesFeed.store.dispatch was called"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly({
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_HANDOFF_SEARCH_TO_AWESOMEBAR() {
+ info(
+ "PlacesFeed.onAction should call handoffSearchToAwesomebar " +
+ "on HANDOFF_SEARCH_TO_AWESOMEBAR"
+ );
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "handoffSearchToAwesomebar");
+
+ let action = {
+ type: at.HANDOFF_SEARCH_TO_AWESOMEBAR,
+ data: { text: "f" },
+ meta: { fromTarget: {} },
+ _target: { browser: { ownerGlobal: { gURLBar: { focus: () => {} } } } },
+ };
+
+ await feed.onAction(action);
+
+ Assert.ok(
+ feed.handoffSearchToAwesomebar.calledOnce,
+ "PlacesFeed.handoffSearchToAwesomebar called"
+ );
+ Assert.ok(feed.handoffSearchToAwesomebar.calledWithExactly(action));
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_PARTNER_LINK_ATTRIBUTION() {
+ info(
+ "PlacesFeed.onAction should call makeAttributionRequest on " +
+ "PARTNER_LINK_ATTRIBUTION"
+ );
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(feed, "makeAttributionRequest");
+
+ let data = { targetURL: "https://partnersite.com", source: "topsites" };
+ feed.onAction({
+ type: at.PARTNER_LINK_ATTRIBUTION,
+ data,
+ });
+
+ Assert.ok(
+ feed.makeAttributionRequest.calledOnce,
+ "PlacesFeed.makeAttributionRequest called"
+ );
+ Assert.ok(feed.makeAttributionRequest.calledWithExactly(data));
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_makeAttributionRequest_PartnerLinkAttribution_makeReq() {
+ info(
+ "PlacesFeed.makeAttributionRequest should call " +
+ "PartnerLinkAttribution.makeRequest"
+ );
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ sandbox.stub(PartnerLinkAttribution, "makeRequest");
+
+ let data = { targetURL: "https://partnersite.com", source: "topsites" };
+ feed.makeAttributionRequest(data);
+
+ Assert.ok(
+ PartnerLinkAttribution.makeRequest.calledOnce,
+ "PartnerLinkAttribution.makeRequest called"
+ );
+
+ sandbox.restore();
+ }
+);
+
+function createFakeURLBar(sandbox) {
+ let fakeURLBar = {
+ focus: sandbox.spy(),
+ handoff: sandbox.spy(),
+ setHiddenFocus: sandbox.spy(),
+ removeHiddenFocus: sandbox.spy(),
+ addEventListener: (ev, cb) => {
+ fakeURLBar.listeners[ev] = cb;
+ },
+ removeEventListener: sandbox.spy(),
+
+ listeners: [],
+ };
+
+ return fakeURLBar;
+}
+
+add_task(async function test_handoffSearchToAwesomebar_no_text() {
+ info(
+ "PlacesFeed.handoffSearchToAwesomebar should properly handle handoff " +
+ "with no text passed in"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let fakeURLBar = createFakeURLBar(sandbox);
+
+ sandbox.stub(PrivateBrowsingUtils, "isBrowserPrivate").returns(false);
+ sandbox.stub(feed, "_getDefaultSearchEngine").returns(null);
+
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeURLBar } } },
+ data: {},
+ meta: { fromTarget: {} },
+ });
+
+ Assert.ok(
+ fakeURLBar.setHiddenFocus.calledOnce,
+ "gURLBar.setHiddenFocus called"
+ );
+ Assert.ok(fakeURLBar.handoff.notCalled, "gURLBar.handoff not called");
+ Assert.ok(
+ feed.store.dispatch.notCalled,
+ "PlacesFeed.store.dispatch not called"
+ );
+
+ // Now type a character.
+ fakeURLBar.listeners.keydown({ key: "f" });
+ Assert.ok(fakeURLBar.handoff.calledOnce, "gURLBar.handoff called");
+ Assert.ok(
+ fakeURLBar.removeHiddenFocus.calledOnce,
+ "gURLBar.removeHiddenFocus called"
+ );
+ Assert.ok(feed.store.dispatch.calledOnce, "PlacesFeed.store.dispatch called");
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "DISABLE_SEARCH",
+ }),
+ "PlacesFeed.store.dispatch called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_handoffSearchToAwesomebar_with_text() {
+ info(
+ "PlacesFeed.handoffSearchToAwesomebar should properly handle handoff " +
+ "with text data passed in"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let fakeURLBar = createFakeURLBar(sandbox);
+
+ sandbox.stub(PrivateBrowsingUtils, "isBrowserPrivate").returns(false);
+ let engine = {};
+ sandbox.stub(feed, "_getDefaultSearchEngine").returns(engine);
+
+ const SESSION_ID = "decafc0ffee";
+ AboutNewTab.activityStream.store.feeds.get.returns({
+ sessions: {
+ get: () => {
+ return { session_id: SESSION_ID };
+ },
+ },
+ });
+
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeURLBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+
+ Assert.ok(fakeURLBar.handoff.calledOnce, "gURLBar.handoff was called");
+ Assert.ok(fakeURLBar.handoff.calledWithExactly("foo", engine, SESSION_ID));
+ Assert.ok(fakeURLBar.focus.notCalled, "gURLBar.focus not called");
+ Assert.ok(
+ fakeURLBar.setHiddenFocus.notCalled,
+ "gURLBar.setHiddenFocus not called"
+ );
+
+ // Now call blur listener.
+ fakeURLBar.listeners.blur();
+ Assert.ok(feed.store.dispatch.calledOnce, "PlacesFeed.store.dispatch called");
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_handoffSearchToAwesomebar_with_text_pb_mode() {
+ info(
+ "PlacesFeed.handoffSearchToAwesomebar should properly handle handoff " +
+ "with text data passed in, in private browsing mode"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let fakeURLBar = createFakeURLBar(sandbox);
+
+ sandbox.stub(PrivateBrowsingUtils, "isBrowserPrivate").returns(true);
+ let engine = {};
+ sandbox.stub(feed, "_getDefaultSearchEngine").returns(engine);
+
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeURLBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ Assert.ok(fakeURLBar.handoff.calledOnce, "gURLBar.handoff was called");
+ Assert.ok(fakeURLBar.handoff.calledWithExactly("foo", engine, undefined));
+ Assert.ok(fakeURLBar.focus.notCalled, "gURLBar.focus not called");
+ Assert.ok(
+ fakeURLBar.setHiddenFocus.notCalled,
+ "gURLBar.setHiddenFocus not called"
+ );
+
+ // Now call blur listener.
+ fakeURLBar.listeners.blur();
+ Assert.ok(feed.store.dispatch.calledOnce, "PlacesFeed.store.dispatch called");
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_handoffSearchToAwesomebar_SHOW_SEARCH_on_esc() {
+ info(
+ "PlacesFeed.handoffSearchToAwesomebar should SHOW_SEARCH on ESC keydown"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let fakeURLBar = createFakeURLBar(sandbox);
+
+ sandbox.stub(PrivateBrowsingUtils, "isBrowserPrivate").returns(false);
+ let engine = {};
+ sandbox.stub(feed, "_getDefaultSearchEngine").returns(engine);
+
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeURLBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ Assert.ok(fakeURLBar.handoff.calledOnce, "gURLBar.handoff was called");
+ Assert.ok(fakeURLBar.handoff.calledWithExactly("foo", engine, undefined));
+ Assert.ok(fakeURLBar.focus.notCalled, "gURLBar.focus not called");
+
+ // Now call ESC keydown.
+ fakeURLBar.listeners.keydown({ key: "Escape" });
+ Assert.ok(feed.store.dispatch.calledOnce, "PlacesFeed.store.dispatch called");
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ })
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_handoffSearchToAwesomebar_with_session_id_no_text() {
+ info(
+ "PlacesFeed.handoffSearchToAwesomebar should properly handoff a " +
+ "newtab session id with no text passed in"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ let fakeURLBar = createFakeURLBar(sandbox);
+
+ sandbox.stub(PrivateBrowsingUtils, "isBrowserPrivate").returns(false);
+ let engine = {};
+ sandbox.stub(feed, "_getDefaultSearchEngine").returns(engine);
+
+ const SESSION_ID = "decafc0ffee";
+ AboutNewTab.activityStream.store.feeds.get.returns({
+ sessions: {
+ get: () => {
+ return { session_id: SESSION_ID };
+ },
+ },
+ });
+
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeURLBar } } },
+ data: {},
+ meta: { fromTarget: {} },
+ });
+
+ Assert.ok(
+ fakeURLBar.setHiddenFocus.calledOnce,
+ "gURLBar.setHiddenFocus was called"
+ );
+ Assert.ok(fakeURLBar.handoff.notCalled, "gURLBar.handoff not called");
+ Assert.ok(fakeURLBar.focus.notCalled, "gURLBar.focus not called");
+ Assert.ok(
+ feed.store.dispatch.notCalled,
+ "PlacesFeed.store.dispatch not called"
+ );
+
+ // Now type a character.
+ fakeURLBar.listeners.keydown({ key: "f" });
+ Assert.ok(fakeURLBar.handoff.calledOnce, "gURLBar.handoff was called");
+ Assert.ok(fakeURLBar.handoff.calledWithExactly("", engine, SESSION_ID));
+
+ Assert.ok(
+ fakeURLBar.removeHiddenFocus.calledOnce,
+ "gURLBar.removeHiddenFocus was called"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledOnce,
+ "PlacesFeed.store.dispatch called"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "DISABLE_SEARCH",
+ })
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_observe_dispatch_PLACES_LINK_BLOCKED() {
+ info(
+ "PlacesFeed.observe should dispatch a PLACES_LINK_BLOCKED action " +
+ "with the url of the blocked link"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ 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",
+ });
+
+ sandbox.restore();
+});
+
+add_task(async function test_observe_no_dispatch() {
+ info(
+ "PlacesFeed.observe should not call dispatch if the topic is something " +
+ "other than BLOCKED_EVENT"
+ );
+
+ let sandbox = sinon.createSandbox();
+
+ let feed = getPlacesFeedForTest(sandbox);
+ feed.observe(null, "someotherevent");
+ Assert.ok(
+ feed.store.dispatch.notCalled,
+ "PlacesFeed.store.dispatch not called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_handlePlacesEvent_dispatch_one_PLACES_LINKS_CHANGED() {
+ let events = [
+ {
+ message:
+ "PlacesFeed.handlePlacesEvent should only dispatch 1 PLACES_LINKS_CHANGED action " +
+ "if many bookmark-added notifications happened at once",
+ dispatchCallCount: 5,
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesFeed.handlePlacesEvent should only dispatch 1 " +
+ "PLACES_LINKS_CHANGED action if many onItemRemoved notifications " +
+ "happened at once",
+ dispatchCallCount: 5,
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "rTU_oiklsU7D",
+ parentGuid: "2BzBQXOPFmuU",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ },
+ {
+ message:
+ "PlacesFeed.handlePlacesEvent should only dispatch 1 " +
+ "PLACES_LINKS_CHANGED action if any page-removed notifications " +
+ "happened at once",
+ dispatchCallCount: 5,
+ event: {
+ type: "page-removed",
+ url: "foo.com",
+ isRemovedFromStore: true,
+ },
+ },
+ ];
+
+ for (let { message, dispatchCallCount, event } of events) {
+ info(message);
+
+ let sandbox = sinon.createSandbox();
+ let feed = getPlacesFeedForTest(sandbox);
+
+ await feed.placesObserver.handlePlacesEvent([event]);
+ await feed.placesObserver.handlePlacesEvent([event]);
+ await feed.placesObserver.handlePlacesEvent([event]);
+ await feed.placesObserver.handlePlacesEvent([event]);
+
+ Assert.ok(feed.placesChangedTimer, "PlacesFeed dispatch timer created");
+
+ // Let's speed things up a bit.
+ feed.placesChangedTimer.delay = 0;
+
+ // Wait for the timer to go off and get cleared
+ await TestUtils.waitForCondition(
+ () => !feed.placesChangedTimer,
+ "PlacesFeed dispatch timer cleared"
+ );
+
+ Assert.equal(
+ feed.store.dispatch.callCount,
+ dispatchCallCount,
+ `PlacesFeed.store.dispatch was called ${dispatchCallCount} times`
+ );
+
+ Assert.ok(
+ feed.store.dispatch.withArgs(
+ ac.OnlyToMain({ type: at.PLACES_LINKS_CHANGED })
+ ).calledOnce,
+ "PlacesFeed.store.dispatch called with PLACES_LINKS_CHANGED once"
+ );
+
+ sandbox.restore();
+ }
+ }
+);
+
+add_task(async function test_PlacesObserver_dispatches() {
+ let events = [
+ {
+ message:
+ "PlacesObserver should dispatch a PLACES_HISTORY_CLEARED action " +
+ "on history-cleared",
+ args: { type: "history-cleared" },
+ expectedAction: { type: at.PLACES_HISTORY_CLEARED },
+ },
+ {
+ message:
+ "PlacesObserver should dispatch a PLACES_LINKS_DELETED action " +
+ "with the right url",
+ args: {
+ type: "page-removed",
+ url: "foo.com",
+ isRemovedFromStore: true,
+ },
+ expectedAction: {
+ type: at.PLACES_LINKS_DELETED,
+ data: { urls: ["foo.com"] },
+ },
+ },
+ {
+ message:
+ "PlacesObserver should dispatch a PLACES_BOOKMARK_ADDED action with " +
+ "the bookmark data - http",
+ 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",
+ },
+ expectedAction: {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ bookmarkGuid: FAKE_BOOKMARK.bookmarkGuid,
+ bookmarkTitle: FAKE_BOOKMARK.bookmarkTitle,
+ dateAdded: FAKE_BOOKMARK.dateAdded * 1000,
+ url: "http://www.foo.com",
+ },
+ },
+ },
+ {
+ message:
+ "PlacesObserver should dispatch a PLACES_BOOKMARK_ADDED action with " +
+ "the bookmark data - https",
+ 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",
+ },
+ expectedAction: {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ bookmarkGuid: FAKE_BOOKMARK.bookmarkGuid,
+ bookmarkTitle: FAKE_BOOKMARK.bookmarkTitle,
+ dateAdded: FAKE_BOOKMARK.dateAdded * 1000,
+ url: "https://www.foo.com",
+ },
+ },
+ },
+ ];
+
+ for (let { message, args, expectedAction } of events) {
+ info(message);
+ let sandbox = sinon.createSandbox();
+ let dispatch = sandbox.spy();
+ let observer = new PlacesObserver(dispatch);
+ await observer.handlePlacesEvent([args]);
+ Assert.ok(dispatch.calledWith(expectedAction));
+ sandbox.restore();
+ }
+});
+
+add_task(async function test_PlacesObserver_ignores() {
+ let events = [
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARK_ADDED action - " +
+ "not http/https for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARK_ADDED action - " +
+ "has IMPORT source for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARK_ADDED " +
+ "action - has RESTORE source for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARK_ADDED " +
+ "action - has RESTORE_ON_STARTUP source for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARK_ADDED " +
+ "action - has SYNC source for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should ignore events that are not of " +
+ "TYPE_BOOKMARK for bookmark-added",
+ event: {
+ 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",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should ignore events that are not of " +
+ "TYPE_BOOKMARK for bookmark-removed",
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: "nottypebookmark",
+ url: null,
+ guid: "461Z_7daEqIh",
+ parentGuid: "hkHScG3aI3hh",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARKS_REMOVED " +
+ "action - has SYNC source for bookmark-removed",
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "uvRE3stjoZOI",
+ parentGuid: "BnsXZl8VMJjB",
+ source: SOURCES.SYNC,
+ type: "bookmark-removed",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARKS_REMOVED " +
+ "action - has IMPORT source for bookmark-removed",
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "VF6YwhGpHrOW",
+ parentGuid: "7Vz8v9nKcSoq",
+ source: SOURCES.IMPORT,
+ type: "bookmark-removed",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARKS_REMOVED " +
+ "action - has RESTORE source for bookmark-removed",
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "eKozFyXJP97R",
+ parentGuid: "ya8Z2FbjKnD0",
+ source: SOURCES.RESTORE,
+ type: "bookmark-removed",
+ },
+ },
+ {
+ message:
+ "PlacesObserver should not dispatch a PLACES_BOOKMARKS_REMOVED " +
+ "action - has RESTORE_ON_STARTUP source for bookmark-removed",
+ event: {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "StSGMhrYYfyD",
+ parentGuid: "vL8wsCe2j_eT",
+ source: SOURCES.RESTORE_ON_STARTUP,
+ type: "bookmark-removed",
+ },
+ },
+ ];
+
+ for (let { message, event } of events) {
+ info(message);
+ let sandbox = sinon.createSandbox();
+ let dispatch = sandbox.spy();
+ let observer = new PlacesObserver(dispatch);
+
+ await observer.handlePlacesEvent([event]);
+ Assert.ok(dispatch.notCalled, "PlacesObserver.dispatch not called");
+ sandbox.restore();
+ }
+});
+
+add_task(async function test_PlacesObserver_bookmark_removed() {
+ info(
+ "PlacesObserver should dispatch a PLACES_BOOKMARKS_REMOVED " +
+ "action with the right URL and bookmarkGuid for bookmark-removed"
+ );
+ let sandbox = sinon.createSandbox();
+ let dispatch = sandbox.spy();
+ let observer = new PlacesObserver(dispatch);
+
+ await observer.handlePlacesEvent([
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "Xgnxs27I9JnX",
+ parentGuid: "a4k739PL55sP",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ ]);
+
+ Assert.ok(
+ dispatch.calledWith({
+ type: at.PLACES_BOOKMARKS_REMOVED,
+ data: { urls: ["foo.com"] },
+ })
+ );
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_Store.js b/browser/components/newtab/test/xpcshell/test_Store.js
new file mode 100644
index 0000000000..b05ad36cd6
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_Store.js
@@ -0,0 +1,453 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { Store } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/Store.sys.mjs"
+);
+const { ActivityStreamMessageChannel } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/ActivityStreamMessageChannel.sys.mjs"
+);
+const { ActivityStreamStorage } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/ActivityStreamStorage.sys.mjs"
+);
+const { sinon } = ChromeUtils.importESModule(
+ "resource://testing-common/Sinon.sys.mjs"
+);
+
+// This creates the Redux top-level object.
+/* globals Redux */
+Services.scriptloader.loadSubScript(
+ "resource://activity-stream/vendor/redux.js",
+ this
+);
+
+add_task(async function test_expected_properties() {
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ Assert.equal(store.feeds.constructor.name, "Map", "Should create a Map");
+ Assert.equal(store.feeds.size, 0, "Store should start without any feeds.");
+
+ Assert.ok(store._store, "Has a ._store");
+ Assert.ok(store.dispatch, "Has a .dispatch");
+ Assert.ok(store.getState, "Has a .getState");
+
+ sandbox.restore();
+});
+
+add_task(async function test_messagechannel() {
+ let sandbox = sinon.createSandbox();
+ sandbox
+ .stub(ActivityStreamMessageChannel.prototype, "middleware")
+ .returns(s => next => action => next(action));
+ let store = new Store();
+
+ info(
+ "Store should create a ActivityStreamMessageChannel with the right dispatcher"
+ );
+ Assert.ok(store.getMessageChannel(), "Has a message channel");
+ Assert.equal(
+ store.getMessageChannel().dispatch,
+ store.dispatch,
+ "MessageChannel.dispatch forwards to store.dispatch"
+ );
+ Assert.equal(
+ store.getMessageChannel(),
+ store._messageChannel,
+ "_messageChannel is the member for getMessageChannel()"
+ );
+
+ store.dispatch({ type: "FOO" });
+ Assert.ok(
+ ActivityStreamMessageChannel.prototype.middleware.calledOnce,
+ "Middleware called."
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_initFeed_add_feeds() {
+ info("Store.initFeed should add an instance of the feed to .feeds");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ class Foo {}
+ store._prefs.set("foo", true);
+ await store.init(new Map([["foo", () => new Foo()]]));
+ store.initFeed("foo");
+
+ Assert.ok(store.feeds.has("foo"), "foo is set");
+ Assert.ok(store.feeds.get("foo") instanceof Foo, "Got registered class");
+ sandbox.restore();
+});
+
+add_task(async function test_initFeed_calls_onAction() {
+ info("Store should call the feed's onAction with uninit action if it exists");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ let testFeed;
+ let createTestFeed = () => {
+ testFeed = { onAction: sandbox.spy() };
+ return testFeed;
+ };
+ const action = { type: "FOO" };
+ store._feedFactories = new Map([["test", createTestFeed]]);
+
+ store.initFeed("test", action);
+
+ Assert.ok(testFeed.onAction.calledOnce, "onAction called");
+ Assert.ok(
+ testFeed.onAction.calledWith(action),
+ "onAction called with test action"
+ );
+
+ info("Store should add a .store property to the feed");
+ Assert.ok(testFeed.store, "Store exists");
+ Assert.equal(testFeed.store, store, "Feed store is the Store");
+ sandbox.restore();
+});
+
+add_task(async function test_initFeed_on_init() {
+ info("Store should call .initFeed with each key");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.stub(store, "initFeed");
+ store._prefs.set("foo", true);
+ store._prefs.set("bar", true);
+ await store.init(
+ new Map([
+ ["foo", () => {}],
+ ["bar", () => {}],
+ ])
+ );
+ Assert.ok(store.initFeed.calledWith("foo"), "First test feed initted");
+ Assert.ok(store.initFeed.calledWith("bar"), "Second test feed initted");
+ sandbox.restore();
+});
+
+add_task(async function test_initFeed_calls__initIndexedDB() {
+ info("Store should call _initIndexedDB");
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.spy(store, "_initIndexedDB");
+
+ let dbStub = sandbox.stub(ActivityStreamStorage.prototype, "db");
+ let dbAccessed = false;
+ dbStub.get(() => {
+ dbAccessed = true;
+ return {};
+ });
+
+ store._prefs.set("testfeed", true);
+ await store.init(
+ new Map([
+ [
+ "testfeed",
+ () => {
+ return {};
+ },
+ ],
+ ])
+ );
+
+ Assert.ok(store._initIndexedDB.calledOnce, "_initIndexedDB called once");
+ Assert.ok(
+ store._initIndexedDB.calledWithExactly("feeds.telemetry"),
+ "feeds.telemetry was passed"
+ );
+ // Due to what appears to be a bug in sinon when using calledOnce
+ // with a stubbed getter, we can't just use dbStub.calledOnce here.
+ Assert.ok(dbAccessed, "ActivityStreamStorage was accessed");
+
+ info(
+ "Store should reset ActivityStreamStorage telemetry if opening the db fails"
+ );
+ dbStub.rejects();
+ await store.init(new Map());
+
+ Assert.equal(
+ store.dbStorage.telemetry,
+ null,
+ "Telemetry on storage was cleared"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_disabled_feed() {
+ info("Store should not initialize the feed if the Pref is set to false");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.stub(store, "initFeed");
+ store._prefs.set("foo", false);
+ await store.init(new Map([["foo", () => {}]]));
+ Assert.ok(store.initFeed.notCalled, ".initFeed not called");
+
+ store._prefs.set("foo", true);
+
+ sandbox.restore();
+});
+
+add_task(async function test_observe_pref_branch() {
+ info("Store should observe the pref branch");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.stub(store._prefs, "observeBranch");
+ await store.init(new Map());
+ Assert.ok(store._prefs.observeBranch.calledOnce, "observeBranch called once");
+ Assert.ok(
+ store._prefs.observeBranch.calledWith(store),
+ "observeBranch passed the store"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_emit_initial_event() {
+ info("Store should emit an initial event if provided");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ const action = { type: "FOO" };
+ sandbox.stub(store, "dispatch");
+ await store.init(new Map(), action);
+ Assert.ok(store.dispatch.calledOnce, "Dispatch called once");
+ Assert.ok(store.dispatch.calledWith(action), "Dispatch called with action");
+
+ sandbox.restore();
+});
+
+add_task(async function test_initialize_telemetry_feed_first() {
+ info("Store should initialize the telemetry feed first");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ 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],
+ ]);
+ await store.init(feedFactories);
+ Assert.ok(telemetrySpy.calledBefore(fooSpy), "Telemetry feed initted first");
+
+ sandbox.restore();
+});
+
+add_task(async function test_dispatch_init_load_events() {
+ info("Store should dispatch init/load events");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.stub(store.getMessageChannel(), "simulateMessagesForExistingTabs");
+ await store.init(new Map(), { type: "FOO" });
+ Assert.ok(
+ store.getMessageChannel().simulateMessagesForExistingTabs.calledOnce,
+ "simulateMessagesForExistingTabs called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_init_before_load() {
+ info("Store should dispatch INIT before LOAD");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ sandbox.stub(store.getMessageChannel(), "simulateMessagesForExistingTabs");
+ sandbox.stub(store, "dispatch");
+ const init = { type: "INIT" };
+ const load = { type: "TAB_LOAD" };
+ store
+ .getMessageChannel()
+ .simulateMessagesForExistingTabs.callsFake(() => store.dispatch(load));
+ await store.init(new Map(), init);
+
+ Assert.ok(store.dispatch.calledTwice, "Dispatch called twice");
+ Assert.equal(
+ store.dispatch.firstCall.args[0],
+ init,
+ "First dispatch was for init event"
+ );
+ Assert.equal(
+ store.dispatch.secondCall.args[0],
+ load,
+ "Second dispatch was for load event"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_uninit_feeds() {
+ info("uninitFeed should not throw if no feed with that name exists");
+
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+
+ try {
+ store.uninitFeed("does-not-exist");
+ Assert.ok(true, "Didn't throw");
+ } catch (e) {
+ Assert.ok(false, "Should not have thrown");
+ }
+
+ info(
+ "uninitFeed should call the feed's onAction with uninit action if it exists"
+ );
+ let feed;
+ function createFeed() {
+ feed = { onAction: sandbox.spy() };
+ return feed;
+ }
+ const action = { type: "BAR" };
+ store._feedFactories = new Map([["foo", createFeed]]);
+ store.initFeed("foo");
+
+ store.uninitFeed("foo", action);
+
+ Assert.ok(feed.onAction.calledOnce);
+ Assert.ok(feed.onAction.calledWith(action));
+
+ info("uninitFeed should remove the feed from .feeds");
+ Assert.ok(!store.feeds.has("foo"), "foo is not in .feeds");
+
+ sandbox.restore();
+});
+
+add_task(async function test_onPrefChanged() {
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ let initFeedStub = sandbox.stub(store, "initFeed");
+ let uninitFeedStub = sandbox.stub(store, "uninitFeed");
+ store._prefs.set("foo", false);
+ store.init(new Map([["foo", () => ({})]]));
+
+ info("onPrefChanged should initialize the feed if called with true");
+ store.onPrefChanged("foo", true);
+ Assert.ok(initFeedStub.calledWith("foo"));
+ Assert.ok(!uninitFeedStub.calledOnce);
+ initFeedStub.resetHistory();
+ uninitFeedStub.resetHistory();
+
+ info("onPrefChanged should uninitialize the feed if called with false");
+ store.onPrefChanged("foo", false);
+ Assert.ok(uninitFeedStub.calledWith("foo"));
+ Assert.ok(!initFeedStub.calledOnce);
+ initFeedStub.resetHistory();
+ uninitFeedStub.resetHistory();
+
+ info("onPrefChanged should do nothing if not an expected feed");
+ store.onPrefChanged("bar", false);
+
+ Assert.ok(!initFeedStub.calledOnce);
+ Assert.ok(!uninitFeedStub.calledOnce);
+ sandbox.restore();
+});
+
+add_task(async function test_uninit() {
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ let dispatchStub = sandbox.stub(store, "dispatch");
+ const action = { type: "BAR" };
+ await store.init(new Map(), null, action);
+ store.uninit();
+
+ Assert.ok(store.dispatch.calledOnce);
+ Assert.ok(store.dispatch.calledWith(action));
+
+ info("Store.uninit should clear .feeds and ._feedFactories");
+ store._prefs.set("a", true);
+ await store.init(
+ new Map([
+ ["a", () => ({})],
+ ["b", () => ({})],
+ ["c", () => ({})],
+ ])
+ );
+
+ store.uninit();
+
+ Assert.equal(store.feeds.size, 0);
+ Assert.equal(store._feedFactories, null);
+
+ info("Store.uninit should emit an uninit event if provided on init");
+ dispatchStub.resetHistory();
+ const uninitAction = { type: "BAR" };
+ await store.init(new Map(), null, uninitAction);
+ store.uninit();
+
+ Assert.ok(store.dispatch.calledOnce);
+ Assert.ok(store.dispatch.calledWith(uninitAction));
+ sandbox.restore();
+});
+
+add_task(async function test_getState() {
+ info("Store.getState should return the redux state");
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ store._store = Redux.createStore((prevState = 123) => prevState);
+ const { getState } = store;
+ Assert.equal(getState(), 123);
+ sandbox.restore();
+});
+
+/**
+ * addNumberReducer - a simple dummy reducer for testing that adds a number
+ */
+function addNumberReducer(prevState = 0, action) {
+ return action.type === "ADD" ? prevState + action.data : prevState;
+}
+
+add_task(async function test_dispatch() {
+ info("Store.dispatch should call .onAction of each feed");
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ 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.ok(sub.onAction.calledWith(action));
+
+ info("Sandbox.dispatch should call the reducers");
+
+ store._store = Redux.createStore(addNumberReducer);
+ dispatch({ type: "ADD", data: 14 });
+ Assert.equal(store.getState(), 14);
+
+ sandbox.restore();
+});
+
+add_task(async function test_subscribe() {
+ info("Store.subscribe should subscribe to changes to the store");
+ let sandbox = sinon.createSandbox();
+ let store = new Store();
+ const sub = sandbox.spy();
+ const action = { type: "FOO" };
+
+ store.subscribe(sub);
+ store.dispatch(action);
+
+ Assert.ok(sub.calledOnce);
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_TelemetryFeed.js b/browser/components/newtab/test/xpcshell/test_TelemetryFeed.js
new file mode 100644
index 0000000000..b54d6094ad
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_TelemetryFeed.js
@@ -0,0 +1,3285 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.importESModule(
+ "resource:///modules/asrouter/ActorConstants.sys.mjs"
+);
+
+const { updateAppInfo } = ChromeUtils.importESModule(
+ "resource://testing-common/AppInfo.sys.mjs"
+);
+
+const { TelemetryFeed, USER_PREFS_ENCODING } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/TelemetryFeed.sys.mjs"
+);
+
+ChromeUtils.defineESModuleGetters(this, {
+ AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
+ AboutWelcomeTelemetry:
+ "resource:///modules/aboutwelcome/AboutWelcomeTelemetry.sys.mjs",
+ ExperimentAPI: "resource://nimbus/ExperimentAPI.sys.mjs",
+ ExtensionSettingsStore:
+ "resource://gre/modules/ExtensionSettingsStore.sys.mjs",
+ HomePage: "resource:///modules/HomePage.sys.mjs",
+ JsonSchemaValidator:
+ "resource://gre/modules/components-utils/JsonSchemaValidator.sys.mjs",
+ sinon: "resource://testing-common/Sinon.sys.mjs",
+ TelemetryController: "resource://gre/modules/TelemetryController.sys.mjs",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
+ TelemetryTestUtils: "resource://testing-common/TelemetryTestUtils.sys.mjs",
+ UpdateUtils: "resource://gre/modules/UpdateUtils.sys.mjs",
+ UTEventReporting: "resource://activity-stream/lib/UTEventReporting.sys.mjs",
+});
+
+const FAKE_UUID = "{foo-123-foo}";
+const PREF_IMPRESSION_ID = "browser.newtabpage.activity-stream.impressionId";
+const PREF_TELEMETRY = "browser.newtabpage.activity-stream.telemetry";
+const PREF_EVENT_TELEMETRY =
+ "browser.newtabpage.activity-stream.telemetry.ut.events";
+
+let ASRouterEventPingSchemaPromise;
+let BasePingSchemaPromise;
+let SessionPingSchemaPromise;
+let UserEventPingSchemaPromise;
+
+function assertPingMatchesSchema(pingKind, ping, schema) {
+ // Unlike the validator from JsonSchema.sys.mjs, JsonSchemaValidator
+ // lets us opt-in to having "undefined" properties, which are then
+ // ignored. This is fine because the ping is sent as a JSON string
+ // over an XHR, and undefined properties are culled as part of the
+ // JSON encoding process.
+ let result = JsonSchemaValidator.validate(ping, schema, {
+ allowExplicitUndefinedProperties: true,
+ });
+
+ if (!result.valid) {
+ info(`${pingKind} failed to validate against the schema: ${result.error}`);
+ }
+
+ Assert.ok(result.valid, `${pingKind} is valid against the schema.`);
+}
+
+async function assertSessionPingValid(ping) {
+ let schema = await SessionPingSchemaPromise;
+ assertPingMatchesSchema("SessionPing", ping, schema);
+}
+
+async function assertBasePingValid(ping) {
+ let schema = await BasePingSchemaPromise;
+ assertPingMatchesSchema("BasePing", ping, schema);
+}
+
+async function assertUserEventPingValid(ping) {
+ let schema = await UserEventPingSchemaPromise;
+ assertPingMatchesSchema("UserEventPing", ping, schema);
+}
+
+async function assertASRouterEventPingValid(ping) {
+ let schema = await ASRouterEventPingSchemaPromise;
+ assertPingMatchesSchema("ASRouterEventPing", ping, schema);
+}
+
+add_setup(async function setup() {
+ ASRouterEventPingSchemaPromise = IOUtils.readJSON(
+ do_get_file("../schemas/asrouter_event_ping.schema.json").path
+ );
+
+ BasePingSchemaPromise = IOUtils.readJSON(
+ do_get_file("../schemas/base_ping.schema.json").path
+ );
+
+ SessionPingSchemaPromise = IOUtils.readJSON(
+ do_get_file("../schemas/session_ping.schema.json").path
+ );
+
+ UserEventPingSchemaPromise = IOUtils.readJSON(
+ do_get_file("../schemas/user_event_ping.schema.json").path
+ );
+
+ do_get_profile();
+ // FOG needs to be initialized in order for data to flow.
+ Services.fog.initializeFOG();
+
+ await TelemetryController.testReset();
+
+ updateAppInfo({
+ name: "XPCShell",
+ ID: "xpcshell@tests.mozilla.org",
+ version: "122",
+ platformVersion: "122",
+ });
+
+ Services.prefs.setCharPref(
+ "browser.contextual-services.contextId",
+ FAKE_UUID
+ );
+});
+
+add_task(async function test_construction() {
+ let testInstance = new TelemetryFeed();
+ Assert.ok(
+ testInstance,
+ "Should have been able to create an instance of TelemetryFeed."
+ );
+ Assert.ok(
+ testInstance.utEvents instanceof UTEventReporting,
+ "Should add .utEvents, a UTEventReporting instance."
+ );
+ Assert.ok(
+ testInstance._impressionId,
+ "Should create impression id if none exists"
+ );
+});
+
+add_task(async function test_load_impressionId() {
+ info(
+ "Constructing a TelemetryFeed should use a saved impression ID if one exists."
+ );
+ const FAKE_IMPRESSION_ID = "{some-fake-impression-ID}";
+ const IMPRESSION_PREF = "browser.newtabpage.activity-stream.impressionId";
+ Services.prefs.setCharPref(IMPRESSION_PREF, FAKE_IMPRESSION_ID);
+ Assert.equal(new TelemetryFeed()._impressionId, FAKE_IMPRESSION_ID);
+ Services.prefs.clearUserPref(IMPRESSION_PREF);
+});
+
+add_task(async function test_init() {
+ info(
+ "init should make this.browserOpenNewtabStart() observe browser-open-newtab-start"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox
+ .stub(TelemetryFeed.prototype, "getOrCreateImpressionId")
+ .returns(FAKE_UUID);
+
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance, "browserOpenNewtabStart");
+ instance.init();
+
+ Services.obs.notifyObservers(null, "browser-open-newtab-start");
+ Assert.ok(
+ instance.browserOpenNewtabStart.calledOnce,
+ "browserOpenNewtabStart called once."
+ );
+
+ info("init should create impression id if none exists");
+ Assert.equal(instance._impressionId, FAKE_UUID);
+
+ instance.uninit();
+ sandbox.restore();
+});
+
+add_task(async function test_saved_impression_id() {
+ const FAKE_IMPRESSION_ID = "fakeImpressionId";
+ Services.prefs.setCharPref(PREF_IMPRESSION_ID, FAKE_IMPRESSION_ID);
+ Assert.equal(new TelemetryFeed()._impressionId, FAKE_IMPRESSION_ID);
+ Services.prefs.clearUserPref(PREF_IMPRESSION_ID);
+});
+
+add_task(async function test_telemetry_prefs() {
+ info("Telemetry pref changes from false to true");
+ Services.prefs.setBoolPref(PREF_TELEMETRY, false);
+ let instance = new TelemetryFeed();
+ Assert.ok(!instance.telemetryEnabled, "Telemetry disabled");
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ Assert.ok(instance.telemetryEnabled, "Telemetry enabled");
+
+ info("Event telemetry pref changes from false to true");
+
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, false);
+ Assert.ok(!instance.eventTelemetryEnabled, "Event telemetry disabled");
+
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ Assert.ok(instance.eventTelemetryEnabled, "Event telemetry enabled");
+
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+});
+
+add_task(async function test_deletionRequest_scalars() {
+ info("TelemetryFeed.init should set two scalars for deletion-request");
+
+ Services.telemetry.clearScalars();
+ let instance = new TelemetryFeed();
+ instance.init();
+
+ let snapshot = Services.telemetry.getSnapshotForScalars(
+ "deletion-request",
+ false
+ ).parent;
+ TelemetryTestUtils.assertScalar(
+ snapshot,
+ "deletion.request.impression_id",
+ instance._impressionId
+ );
+ TelemetryTestUtils.assertScalar(
+ snapshot,
+ "deletion.request.context_id",
+ FAKE_UUID
+ );
+ instance.uninit();
+});
+
+add_task(async function test_metrics_on_initialization() {
+ info("TelemetryFeed.init should record initial metrics from newtab prefs");
+ Services.fog.testResetFOG();
+ const ENABLED_SETTING = true;
+ const TOP_SITES_ROWS = 3;
+ const BLOCKED_SPONSORS = ["mozilla"];
+
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.topsites",
+ ENABLED_SETTING
+ );
+ Services.prefs.setIntPref(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ TOP_SITES_ROWS
+ );
+ Services.prefs.setCharPref(
+ "browser.topsites.blockedSponsors",
+ JSON.stringify(BLOCKED_SPONSORS)
+ );
+
+ let instance = new TelemetryFeed();
+ instance.init();
+
+ Assert.equal(Glean.topsites.enabled.testGetValue(), ENABLED_SETTING);
+ Assert.equal(Glean.topsites.rows.testGetValue(), TOP_SITES_ROWS);
+ Assert.deepEqual(
+ Glean.newtab.blockedSponsors.testGetValue(),
+ BLOCKED_SPONSORS
+ );
+
+ instance.uninit();
+
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.topsites"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.topSitesRows"
+ );
+ Services.prefs.clearUserPref("browser.topsites.blockedSponsors");
+});
+
+add_task(async function test_metrics_with_bad_json() {
+ info(
+ "TelemetryFeed.init should not record blocked sponsor metrics when " +
+ "bad json string is passed"
+ );
+ Services.fog.testResetFOG();
+ Services.prefs.setCharPref("browser.topsites.blockedSponsors", "BAD[JSON]");
+
+ let instance = new TelemetryFeed();
+ instance.init();
+
+ Assert.equal(Glean.newtab.blockedSponsors.testGetValue(), null);
+
+ instance.uninit();
+
+ Services.prefs.clearUserPref("browser.topsites.blockedSponsors");
+});
+
+add_task(async function test_metrics_on_pref_changes() {
+ info("TelemetryFeed.init should record new metrics for newtab pref changes");
+ const INITIAL_TOP_SITES_ROWS = 3;
+ const INITIAL_BLOCKED_SPONSORS = [];
+ Services.fog.testResetFOG();
+ Services.prefs.setIntPref(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ INITIAL_TOP_SITES_ROWS
+ );
+ Services.prefs.setCharPref(
+ "browser.topsites.blockedSponsors",
+ JSON.stringify(INITIAL_BLOCKED_SPONSORS)
+ );
+
+ let instance = new TelemetryFeed();
+ instance.init();
+
+ Assert.equal(Glean.topsites.rows.testGetValue(), INITIAL_TOP_SITES_ROWS);
+ Assert.deepEqual(
+ Glean.newtab.blockedSponsors.testGetValue(),
+ INITIAL_BLOCKED_SPONSORS
+ );
+
+ const NEXT_TOP_SITES_ROWS = 2;
+ const NEXT_BLOCKED_SPONSORS = ["mozilla"];
+
+ Services.prefs.setIntPref(
+ "browser.newtabpage.activity-stream.topSitesRows",
+ NEXT_TOP_SITES_ROWS
+ );
+
+ Services.prefs.setStringPref(
+ "browser.topsites.blockedSponsors",
+ JSON.stringify(NEXT_BLOCKED_SPONSORS)
+ );
+
+ Assert.equal(Glean.topsites.rows.testGetValue(), NEXT_TOP_SITES_ROWS);
+ Assert.deepEqual(
+ Glean.newtab.blockedSponsors.testGetValue(),
+ NEXT_BLOCKED_SPONSORS
+ );
+
+ instance.uninit();
+
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.topSitesRows"
+ );
+ Services.prefs.clearUserPref("browser.topsites.blockedSponsors");
+});
+
+add_task(async function test_events_on_pref_changes() {
+ info("TelemetryFeed.init should record events for some newtab pref changes");
+ // We only record events for browser.newtabpage.activity-stream.feeds.topsites and
+ // browser.newtabpage.activity-stream.showSponsoredTopSites being changed.
+ const INITIAL_TOPSITES_ENABLED = false;
+ const INITIAL_SHOW_SPONSORED_TOP_SITES = true;
+ Services.fog.testResetFOG();
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.topsites",
+ INITIAL_TOPSITES_ENABLED
+ );
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.showSponsoredTopSites",
+ INITIAL_SHOW_SPONSORED_TOP_SITES
+ );
+
+ let instance = new TelemetryFeed();
+ instance.init();
+
+ const NEXT_TOPSITES_ENABLED = true;
+ const NEXT_SHOW_SPONSORED_TOP_SITES = false;
+
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.topsites",
+ NEXT_TOPSITES_ENABLED
+ );
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.showSponsoredTopSites",
+ NEXT_SHOW_SPONSORED_TOP_SITES
+ );
+
+ let prefChangeEvents = Glean.topsites.prefChanged.testGetValue();
+ Assert.deepEqual(prefChangeEvents[0].extra, {
+ pref_name: "browser.newtabpage.activity-stream.feeds.topsites",
+ new_value: String(NEXT_TOPSITES_ENABLED),
+ });
+ Assert.deepEqual(prefChangeEvents[1].extra, {
+ pref_name: "browser.newtabpage.activity-stream.showSponsoredTopSites",
+ new_value: String(NEXT_SHOW_SPONSORED_TOP_SITES),
+ });
+
+ instance.uninit();
+
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.topsites"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.showSponsoredTopSites"
+ );
+});
+
+add_task(async function test_browserOpenNewtabStart() {
+ info(
+ "TelemetryFeed.browserOpenNewtabStart should call " +
+ "ChromeUtils.addProfilerMarker with browser-open-newtab-start"
+ );
+
+ let instance = new TelemetryFeed();
+
+ let entries = 10000;
+ let interval = 1;
+ let threads = ["GeckoMain"];
+ let features = [];
+ await Services.profiler.StartProfiler(entries, interval, features, threads);
+ instance.browserOpenNewtabStart();
+
+ let profileArrayBuffer =
+ await Services.profiler.getProfileDataAsArrayBuffer();
+ await Services.profiler.StopProfiler();
+
+ let profileUint8Array = new Uint8Array(profileArrayBuffer);
+ let textDecoder = new TextDecoder("utf-8", { fatal: true });
+ let profileString = textDecoder.decode(profileUint8Array);
+ let profile = JSON.parse(profileString);
+ Assert.ok(profile.threads);
+ Assert.equal(profile.threads.length, 1);
+
+ let foundMarker = profile.threads[0].markers.data.find(marker => {
+ return marker[5]?.name === "browser-open-newtab-start";
+ });
+
+ Assert.ok(foundMarker, "Found the browser-open-newtab-start marker");
+});
+
+add_task(async function test_addSession_and_get_session() {
+ info("TelemetryFeed.addSession should add a session and return it");
+ let instance = new TelemetryFeed();
+ let session = instance.addSession("foo");
+
+ Assert.equal(instance.sessions.get("foo"), session);
+
+ info("TelemetryFeed.addSession should set a session_id");
+ Assert.ok(session.session_id, "Should have a session_id set");
+});
+
+add_task(async function test_addSession_url_param() {
+ info("TelemetryFeed.addSession should set the page if a url param is given");
+ let instance = new TelemetryFeed();
+ let session = instance.addSession("foo", "about:monkeys");
+ Assert.equal(session.page, "about:monkeys");
+
+ info(
+ "TelemetryFeed.assSession should set the page prop to 'unknown' " +
+ "if no URL param given"
+ );
+ session = instance.addSession("test2");
+ Assert.equal(session.page, "unknown");
+});
+
+add_task(async function test_addSession_perf_properties() {
+ info(
+ "TelemetryFeed.addSession should set the perf type when lacking " +
+ "timestamp"
+ );
+ let instance = new TelemetryFeed();
+ let session = instance.addSession("foo");
+ Assert.equal(session.perf.load_trigger_type, "unexpected");
+
+ info(
+ "TelemetryFeed.addSession should set load_trigger_type to " +
+ "first_window_opened on the first about:home seen"
+ );
+ session = instance.addSession("test2", "about:home");
+ Assert.equal(session.perf.load_trigger_type, "first_window_opened");
+
+ info(
+ "TelemetryFeed.addSession should set load_trigger_ts to the " +
+ "value of the process start timestamp"
+ );
+ Assert.equal(
+ session.perf.load_trigger_ts,
+ Services.startup.getStartupInfo().process.getTime(),
+ "Should have set a timestamp to be the process start time"
+ );
+
+ info(
+ "TelemetryFeed.addSession should NOT set load_trigger_type to " +
+ "first_window_opened on the second about:home seen"
+ );
+ let session2 = instance.addSession("test2", "about:home");
+ Assert.notEqual(session2.perf.load_trigger_type, "first_window_opened");
+});
+
+add_task(async function test_addSession_valid_ping_on_first_abouthome() {
+ info(
+ "TelemetryFeed.addSession should create a valid session ping " +
+ "on the first about:home seen"
+ );
+ let instance = new TelemetryFeed();
+ // Add a session
+ const PORT_ID = "foo";
+ let session = instance.addSession(PORT_ID, "about:home");
+
+ // Create a ping referencing the session
+ let ping = instance.createSessionEndEvent(session);
+ await assertSessionPingValid(ping);
+});
+
+add_task(async function test_addSession_valid_ping_data_late_by_ms() {
+ info(
+ "TelemetryFeed.addSession should create a valid session ping " +
+ "with the data_late_by_ms perf"
+ );
+ let instance = new TelemetryFeed();
+ // Add a session
+ const PORT_ID = "foo";
+ let session = instance.addSession(PORT_ID, "about:home");
+
+ const TOPSITES_LATE_BY_MS = 10;
+ const HIGHLIGHTS_LATE_BY_MS = 20;
+ instance.saveSessionPerfData("foo", {
+ topsites_data_late_by_ms: TOPSITES_LATE_BY_MS,
+ });
+ instance.saveSessionPerfData("foo", {
+ highlights_data_late_by_ms: HIGHLIGHTS_LATE_BY_MS,
+ });
+
+ // Create a ping referencing the session
+ let ping = instance.createSessionEndEvent(session);
+ await assertSessionPingValid(ping);
+ Assert.equal(session.perf.topsites_data_late_by_ms, TOPSITES_LATE_BY_MS);
+ Assert.equal(session.perf.highlights_data_late_by_ms, HIGHLIGHTS_LATE_BY_MS);
+});
+
+add_task(async function test_addSession_valid_ping_topsites_stats_perf() {
+ info(
+ "TelemetryFeed.addSession should create a valid session ping " +
+ "with the topsites stats perf"
+ );
+ let instance = new TelemetryFeed();
+ // Add a session
+ const PORT_ID = "foo";
+ let session = instance.addSession(PORT_ID, "about:home");
+
+ const SCREENSHOT_WITH_ICON = 2;
+ const TOPSITES_PINNED = 3;
+ const TOPSITES_SEARCH_SHORTCUTS = 2;
+
+ instance.saveSessionPerfData("foo", {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: SCREENSHOT_WITH_ICON,
+ screenshot: 1,
+ tippytop: 2,
+ rich_icon: 1,
+ no_image: 0,
+ },
+ topsites_pinned: TOPSITES_PINNED,
+ topsites_search_shortcuts: TOPSITES_SEARCH_SHORTCUTS,
+ });
+
+ // Create a ping referencing the session
+ let ping = instance.createSessionEndEvent(session);
+ await assertSessionPingValid(ping);
+ Assert.equal(
+ instance.sessions.get("foo").perf.topsites_icon_stats.screenshot_with_icon,
+ SCREENSHOT_WITH_ICON
+ );
+ Assert.equal(
+ instance.sessions.get("foo").perf.topsites_pinned,
+ TOPSITES_PINNED
+ );
+ Assert.equal(
+ instance.sessions.get("foo").perf.topsites_search_shortcuts,
+ TOPSITES_SEARCH_SHORTCUTS
+ );
+});
+
+add_task(async function test_endSession_no_throw_on_bad_session() {
+ info(
+ "TelemetryFeed.endSession should not throw if there is no " +
+ "session for a given port ID"
+ );
+ let instance = new TelemetryFeed();
+ try {
+ instance.endSession("doesn't exist");
+ Assert.ok(true, "Did not throw.");
+ } catch (e) {
+ Assert.ok(false, "Should not have thrown.");
+ }
+});
+
+add_task(async function test_endSession_session_duration() {
+ info(
+ "TelemetryFeed.endSession should add a session_duration integer " +
+ "if there is a visibility_event_rcvd_ts"
+ );
+ let instance = new TelemetryFeed();
+ let session = instance.addSession("foo");
+ session.perf.visibility_event_rcvd_ts = 444.4732;
+ instance.endSession("foo");
+
+ Assert.ok(
+ Number.isInteger(session.session_duration),
+ "session_duration should be an integer"
+ );
+});
+
+add_task(async function test_endSession_no_ping_on_no_visibility_event() {
+ info(
+ "TelemetryFeed.endSession shouldn't send session ping if there's " +
+ "no visibility_event_rcvd_ts"
+ );
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ let instance = new TelemetryFeed();
+ instance.addSession("foo");
+
+ Services.telemetry.clearEvents();
+ instance.endSession("foo");
+ TelemetryTestUtils.assertNumberOfEvents(0);
+
+ info("TelemetryFeed.endSession should remove the session from .sessions");
+ Assert.ok(!instance.sessions.has("foo"));
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+});
+
+add_task(async function test_endSession_send_ping() {
+ info(
+ "TelemetryFeed.endSession should call createSessionSendEvent with the " +
+ "session if visibilty_event_rcvd_ts was set"
+ );
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ let instance = new TelemetryFeed();
+
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(instance, "createSessionEndEvent");
+ sandbox.stub(instance.utEvents, "sendSessionEndEvent");
+
+ let session = instance.addSession("foo");
+
+ session.perf.visibility_event_rcvd_ts = 444.4732;
+ instance.endSession("foo");
+
+ Assert.ok(instance.createSessionEndEvent.calledWith(session));
+ let sessionEndEvent = instance.createSessionEndEvent.firstCall.returnValue;
+ Assert.ok(instance.utEvents.sendSessionEndEvent.calledWith(sessionEndEvent));
+
+ info("TelemetryFeed.endSession should remove the session from .sessions");
+ Assert.ok(!instance.sessions.has("foo"));
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+
+ sandbox.restore();
+});
+
+add_task(async function test_createPing_valid_base_if_no_portID() {
+ info(
+ "TelemetryFeed.createPing should create a valid base ping " +
+ "without a session if no portID is supplied"
+ );
+ let instance = new TelemetryFeed();
+ let ping = await instance.createPing();
+ await assertBasePingValid(ping);
+ Assert.ok(!ping.session_id);
+ Assert.ok(!ping.page);
+});
+
+add_task(async function test_createPing_valid_base_if_portID() {
+ info(
+ "TelemetryFeed.createPing should create a valid base ping " +
+ "with session info if a portID is supplied"
+ );
+ // Add a session
+ const PORT_ID = "foo";
+ let instance = new TelemetryFeed();
+ instance.addSession(PORT_ID, "about:home");
+ let sessionID = instance.sessions.get(PORT_ID).session_id;
+
+ // Create a ping referencing the session
+ let ping = await instance.createPing(PORT_ID);
+ await assertBasePingValid(ping);
+
+ // Make sure we added the right session-related stuff to the ping
+ Assert.equal(ping.session_id, sessionID);
+ Assert.equal(ping.page, "about:home");
+});
+
+add_task(async function test_createPing_no_session_yet_portID() {
+ info(
+ "TelemetryFeed.createPing should create an 'unexpected' base ping " +
+ "if no session yet portID is supplied"
+ );
+ let instance = new TelemetryFeed();
+ let ping = await instance.createPing("foo");
+ await assertBasePingValid(ping);
+
+ Assert.equal(ping.page, "unknown");
+ Assert.equal(
+ instance.sessions.get("foo").perf.load_trigger_type,
+ "unexpected"
+ );
+});
+
+add_task(async function test_createPing_includes_userPrefs() {
+ info("TelemetryFeed.createPing should create a base ping with user_prefs");
+ let expectedUserPrefs = 0;
+
+ for (let pref of Object.keys(USER_PREFS_ENCODING)) {
+ Services.prefs.setBoolPref(
+ `browser.newtabpage.activity-stream.${pref}`,
+ true
+ );
+ expectedUserPrefs |= USER_PREFS_ENCODING[pref];
+ }
+
+ let instance = new TelemetryFeed();
+ let ping = await instance.createPing("foo");
+ await assertBasePingValid(ping);
+ Assert.equal(ping.user_prefs, expectedUserPrefs);
+
+ for (const pref of Object.keys(USER_PREFS_ENCODING)) {
+ Services.prefs.clearUserPref(`browser.newtabpage.activity-stream.${pref}`);
+ }
+});
+
+add_task(async function test_createUserEvent_is_valid() {
+ info(
+ "TelemetryFeed.createUserEvent should create a valid user event ping " +
+ "with the right session_id"
+ );
+ const PORT_ID = "foo";
+
+ let instance = new TelemetryFeed();
+ let data = { source: "TOP_SITES", event: "CLICK" };
+ let action = ac.AlsoToMain(ac.UserEvent(data), PORT_ID);
+ let session = instance.addSession(PORT_ID);
+
+ let ping = await instance.createUserEvent(action);
+
+ // Is it valid?
+ await assertUserEventPingValid(ping);
+ // Does it have the right session_id?
+ Assert.equal(ping.session_id, session.session_id);
+});
+
+add_task(async function test_createSessionEndEvent_is_valid() {
+ info(
+ "TelemetryFeed.createSessionEndEvent should create a valid session ping"
+ );
+ const FAKE_DURATION = 12345;
+ let instance = new TelemetryFeed();
+ let ping = await instance.createSessionEndEvent({
+ session_id: FAKE_UUID,
+ page: "about:newtab",
+ session_duration: FAKE_DURATION,
+ perf: {
+ load_trigger_ts: 10,
+ load_trigger_type: "menu_plus_or_keyboard",
+ visibility_event_rcvd_ts: 20,
+ is_preloaded: true,
+ },
+ });
+
+ // Is it valid?
+ await assertSessionPingValid(ping);
+ Assert.equal(ping.session_id, FAKE_UUID);
+ Assert.equal(ping.page, "about:newtab");
+ Assert.equal(ping.session_duration, FAKE_DURATION);
+});
+
+add_task(async function test_createSessionEndEvent_with_unexpected_is_valid() {
+ info(
+ "TelemetryFeed.createSessionEndEvent should create a valid 'unexpected' " +
+ "session ping"
+ );
+ const FAKE_DURATION = 12345;
+ const FAKE_TRIGGER_TYPE = "unexpected";
+
+ let instance = new TelemetryFeed();
+ let ping = await instance.createSessionEndEvent({
+ session_id: FAKE_UUID,
+ page: "about:newtab",
+ session_duration: FAKE_DURATION,
+ perf: {
+ load_trigger_type: FAKE_TRIGGER_TYPE,
+ is_preloaded: true,
+ },
+ });
+
+ // Is it valid?
+ await assertSessionPingValid(ping);
+ Assert.equal(ping.session_id, FAKE_UUID);
+ Assert.equal(ping.page, "about:newtab");
+ Assert.equal(ping.session_duration, FAKE_DURATION);
+ Assert.equal(ping.perf.load_trigger_type, FAKE_TRIGGER_TYPE);
+});
+
+add_task(async function test_applyCFRPolicy_prerelease() {
+ info(
+ "TelemetryFeed.applyCFRPolicy should use client_id and message_id " +
+ "in prerelease"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("nightly");
+
+ let instance = new TelemetryFeed();
+
+ let data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ Assert.equal(pingType, "cfr");
+ Assert.equal(ping.impression_id, undefined);
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.bucket_id, "cfr_bucket_01");
+ Assert.equal(ping.message_id, "cfr_message_01");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyCFRPolicy_release() {
+ info(
+ "TelemetryFeed.applyCFRPolicy should use impression_id and bucket_id " +
+ "in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox
+ .stub(TelemetryFeed.prototype, "getOrCreateImpressionId")
+ .returns(FAKE_UUID);
+
+ let instance = new TelemetryFeed();
+
+ let data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ Assert.equal(pingType, "cfr");
+ Assert.equal(ping.impression_id, FAKE_UUID);
+ Assert.equal(ping.client_id, undefined);
+ Assert.equal(ping.bucket_id, "cfr_bucket_01");
+ Assert.equal(ping.message_id, "n/a");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyCFRPolicy_experiment_release() {
+ info(
+ "TelemetryFeed.applyCFRPolicy should use impression_id and bucket_id " +
+ "in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+
+ let instance = new TelemetryFeed();
+
+ let data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ Assert.equal(pingType, "cfr");
+ Assert.equal(ping.impression_id, undefined);
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.bucket_id, "cfr_bucket_01");
+ Assert.equal(ping.message_id, "cfr_message_01");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyCFRPolicy_release_private_browsing() {
+ info(
+ "TelemetryFeed.applyCFRPolicy should use impression_id and bucket_id " +
+ "in Private Browsing in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox
+ .stub(TelemetryFeed.prototype, "getOrCreateImpressionId")
+ .returns(FAKE_UUID);
+
+ let instance = new TelemetryFeed();
+
+ let data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ is_private: true,
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ Assert.equal(pingType, "cfr");
+ Assert.equal(ping.impression_id, FAKE_UUID);
+ Assert.equal(ping.client_id, undefined);
+ Assert.equal(ping.bucket_id, "cfr_bucket_01");
+ Assert.equal(ping.message_id, "n/a");
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_applyCFRPolicy_release_experiment_private_browsing() {
+ info(
+ "TelemetryFeed.applyCFRPolicy should use client_id and message_id in the " +
+ "experiment cohort in Private Browsing in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+
+ let instance = new TelemetryFeed();
+
+ let data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ is_private: true,
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ Assert.equal(pingType, "cfr");
+ Assert.equal(ping.impression_id, undefined);
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.bucket_id, "cfr_bucket_01");
+ Assert.equal(ping.message_id, "cfr_message_01");
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_applyWhatsNewPolicy() {
+ info(
+ "TelemetryFeed.applyWhatsNewPolicy should set client_id and set pingType"
+ );
+ let instance = new TelemetryFeed();
+ let { ping, pingType } = await instance.applyWhatsNewPolicy({});
+
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(pingType, "whats-new-panel");
+});
+
+add_task(async function test_applyInfoBarPolicy() {
+ info(
+ "TelemetryFeed.applyInfoBarPolicy should set client_id and set pingType"
+ );
+ let instance = new TelemetryFeed();
+ let { ping, pingType } = await instance.applyInfoBarPolicy({});
+
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(pingType, "infobar");
+});
+
+add_task(async function test_applyToastNotificationPolicy() {
+ info(
+ "TelemetryFeed.applyToastNotificationPolicy should set client_id " +
+ "and set pingType"
+ );
+ let instance = new TelemetryFeed();
+ let { ping, pingType } = await instance.applyToastNotificationPolicy({});
+
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(pingType, "toast_notification");
+});
+
+add_task(async function test_applySpotlightPolicy() {
+ info(
+ "TelemetryFeed.applySpotlightPolicy should set client_id " +
+ "and set pingType"
+ );
+ let instance = new TelemetryFeed();
+ let { ping, pingType } = await instance.applySpotlightPolicy({
+ action: "foo",
+ });
+
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(pingType, "spotlight");
+ Assert.equal(ping.action, undefined);
+});
+
+add_task(async function test_applyMomentsPolicy_prerelease() {
+ info(
+ "TelemetryFeed.applyMomentsPolicy should use client_id and " +
+ "message_id in prerelease"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("nightly");
+
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ Assert.equal(pingType, "moments");
+ Assert.equal(ping.impression_id, undefined);
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.bucket_id, "moments_bucket_01");
+ Assert.equal(ping.message_id, "moments_message_01");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyMomentsPolicy_release() {
+ info(
+ "TelemetryFeed.applyMomentsPolicy should use impression_id and " +
+ "bucket_id in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox
+ .stub(TelemetryFeed.prototype, "getOrCreateImpressionId")
+ .returns(FAKE_UUID);
+
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ Assert.equal(pingType, "moments");
+ Assert.equal(ping.impression_id, FAKE_UUID);
+ Assert.equal(ping.client_id, undefined);
+ Assert.equal(ping.bucket_id, "moments_bucket_01");
+ Assert.equal(ping.message_id, "n/a");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyMomentsPolicy_experiment_release() {
+ info(
+ "TelemetryFeed.applyMomentsPolicy client_id and message_id in " +
+ "the experiment cohort in release"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(UpdateUtils, "getUpdateChannel").returns("release");
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ let { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ Assert.equal(pingType, "moments");
+ Assert.equal(ping.impression_id, undefined);
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.bucket_id, "moments_bucket_01");
+ Assert.equal(ping.message_id, "moments_message_01");
+
+ sandbox.restore();
+});
+
+add_task(async function test_applyOnboardingPolicy_includes_client_id() {
+ info("TelemetryFeed.applyOnboardingPolicy should include client_id");
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ let { ping, pingType } = await instance.applyOnboardingPolicy(data);
+
+ Assert.equal(pingType, "onboarding");
+ Assert.equal(
+ ping.client_id,
+ Services.prefs.getCharPref("toolkit.telemetry.cachedClientID")
+ );
+ Assert.equal(ping.message_id, "onboarding_message_01");
+ Assert.equal(
+ ping.browser_session_id,
+ TelemetrySession.getMetadata("").sessionId
+ );
+});
+
+add_task(async function test_applyOnboardingPolicy_with_session() {
+ info(
+ "TelemetryFeed.applyOnboardingPolicy should include page to " +
+ "event_context if there is a session"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ let session = { page: "about:welcome" };
+ let { ping, pingType } = await instance.applyOnboardingPolicy(data, session);
+
+ Assert.equal(pingType, "onboarding");
+ Assert.equal(ping.event_context, JSON.stringify({ page: "about:welcome" }));
+ Assert.equal(ping.message_id, "onboarding_message_01");
+});
+
+add_task(async function test_applyOnboardingPolicy_only_allowed_pages() {
+ info(
+ "TelemetryFeed.applyOnboardingPolicy should not set page if it is " +
+ "not in ONBOARDING_ALLOWED_PAGE_VALUES"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ let session = { page: "foo" };
+ let { ping, pingType } = await instance.applyOnboardingPolicy(data, session);
+
+ Assert.equal(pingType, "onboarding");
+ Assert.equal(ping.event_context, JSON.stringify({}));
+ Assert.equal(ping.message_id, "onboarding_message_01");
+});
+
+add_task(
+ async function test_applyOnboardingPolicy_append_page_to_event_context() {
+ info(
+ "TelemetryFeed.applyOnboardingPolicy should append page to event_context " +
+ "if it is not empty"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ event_context: JSON.stringify({ foo: "bar" }),
+ };
+ let session = { page: "about:welcome" };
+ let { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ Assert.equal(pingType, "onboarding");
+ Assert.equal(
+ ping.event_context,
+ JSON.stringify({ foo: "bar", page: "about:welcome" })
+ );
+ Assert.equal(ping.message_id, "onboarding_message_01");
+ }
+);
+
+add_task(
+ async function test_applyOnboardingPolicy_append_page_to_event_context() {
+ info(
+ "TelemetryFeed.applyOnboardingPolicy should append page to event_context " +
+ "if it is not a JSON serialized string"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ event_context: "foo",
+ };
+ let session = { page: "about:welcome" };
+ let { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ Assert.equal(pingType, "onboarding");
+ Assert.equal(
+ ping.event_context,
+ JSON.stringify({ value: "foo", page: "about:welcome" })
+ );
+ Assert.equal(ping.message_id, "onboarding_message_01");
+ }
+);
+
+add_task(async function test_applyUndesiredEventPolicy() {
+ info(
+ "TelemetryFeed.applyUndesiredEventPolicy should exclude client_id " +
+ "and use impression_id"
+ );
+ let sandbox = sinon.createSandbox();
+ sandbox
+ .stub(TelemetryFeed.prototype, "getOrCreateImpressionId")
+ .returns(FAKE_UUID);
+
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "asrouter_undesired_event",
+ event: "RS_MISSING_DATA",
+ };
+ let { ping, pingType } = await instance.applyUndesiredEventPolicy(data);
+
+ Assert.equal(pingType, "undesired-events");
+ Assert.equal(ping.client_id, undefined);
+ Assert.equal(ping.impression_id, FAKE_UUID);
+
+ sandbox.restore();
+});
+
+add_task(async function test_createASRouterEvent_valid_ping() {
+ info(
+ "TelemetryFeed.createASRouterEvent should create a valid " +
+ "ASRouterEventPing ping"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "cfr_user_event",
+ event: "CLICK",
+ message_id: "cfr_message_01",
+ };
+ let action = ac.ASRouterUserEvent(data);
+ let { ping } = await instance.createASRouterEvent(action);
+
+ await assertASRouterEventPingValid(ping);
+ Assert.equal(ping.event, "CLICK");
+});
+
+add_task(async function test_createASRouterEvent_call_correctPolicy() {
+ let testCallCorrectPolicy = async (expectedPolicyFnName, data) => {
+ info(
+ `TelemetryFeed.createASRouterEvent should call ${expectedPolicyFnName} ` +
+ `on action ${data.action} and event ${data.event}`
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance, expectedPolicyFnName);
+
+ let action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+ Assert.ok(
+ instance[expectedPolicyFnName].calledOnce,
+ `TelemetryFeed.${expectedPolicyFnName} called`
+ );
+
+ sandbox.restore();
+ };
+
+ testCallCorrectPolicy("applyCFRPolicy", {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ });
+
+ testCallCorrectPolicy("applyOnboardingPolicy", {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "onboarding_message_01",
+ });
+
+ testCallCorrectPolicy("applyWhatsNewPolicy", {
+ action: "whats-new-panel_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "whats-new-panel_message_01",
+ });
+
+ testCallCorrectPolicy("applyMomentsPolicy", {
+ action: "moments_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "moments_message_01",
+ });
+
+ testCallCorrectPolicy("applySpotlightPolicy", {
+ action: "spotlight_user_event",
+ event: "CLICK",
+ message_id: "SPOTLIGHT_MESSAGE_93",
+ });
+
+ testCallCorrectPolicy("applyToastNotificationPolicy", {
+ action: "toast_notification_user_event",
+ event: "IMPRESSION",
+ message_id: "TEST_TOAST_NOTIFICATION1",
+ });
+
+ testCallCorrectPolicy("applyUndesiredEventPolicy", {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ });
+});
+
+add_task(async function test_createASRouterEvent_stringify_event_context() {
+ info(
+ "TelemetryFeed.createASRouterEvent should stringify event_context if " +
+ "it is an Object"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ event_context: { foo: "bar" },
+ };
+ let action = ac.ASRouterUserEvent(data);
+ let { ping } = await instance.createASRouterEvent(action);
+
+ Assert.equal(ping.event_context, JSON.stringify({ foo: "bar" }));
+});
+
+add_task(async function test_createASRouterEvent_not_stringify_event_context() {
+ info(
+ "TelemetryFeed.createASRouterEvent should not stringify event_context " +
+ "if it is a String"
+ );
+ let instance = new TelemetryFeed();
+ let data = {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ event_context: "foo",
+ };
+ let action = ac.ASRouterUserEvent(data);
+ let { ping } = await instance.createASRouterEvent(action);
+
+ Assert.equal(ping.event_context, "foo");
+});
+
+add_task(async function test_sendUTEvent_call_right_function() {
+ info("TelemetryFeed.sendUTEvent should call the UT event function passed in");
+ let sandbox = sinon.createSandbox();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+
+ let event = {};
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance.utEvents, "sendUserEvent");
+ instance.addSession("foo");
+
+ await instance.sendUTEvent(event, instance.utEvents.sendUserEvent);
+ Assert.ok(instance.utEvents.sendUserEvent.calledWith(event));
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_setLoadTriggerInfo() {
+ info(
+ "TelemetryFeed.setLoadTriggerInfo should call saveSessionPerfData " +
+ "w/load_trigger_{ts,type} data"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance, "saveSessionPerfData");
+
+ instance.browserOpenNewtabStart();
+ instance.addSession("port123");
+ instance.setLoadTriggerInfo("port123");
+
+ Assert.ok(
+ instance.saveSessionPerfData.calledWith(
+ "port123",
+ sinon.match({
+ load_trigger_type: "menu_plus_or_keyboard",
+ load_trigger_ts: sinon.match.number,
+ })
+ ),
+ "TelemetryFeed.saveSessionPerfData was called with the right arguments"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_setLoadTriggerInfo_no_saveSessionPerfData() {
+ info(
+ "TelemetryFeed.setLoadTriggerInfo should not call saveSessionPerfData " +
+ "when getting mark throws"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance, "saveSessionPerfData");
+
+ instance.addSession("port123");
+ instance.setLoadTriggerInfo("port123");
+
+ Assert.ok(
+ instance.saveSessionPerfData.notCalled,
+ "TelemetryFeed.saveSessionPerfData was not called"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_saveSessionPerfData_updates_session_with_data() {
+ info(
+ "TelemetryFeed.saveSessionPerfData should update the given session " +
+ "with the given data"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ instance.addSession("port123");
+ Assert.equal(instance.sessions.get("port123").fake_ts, undefined);
+ let data = { fake_ts: 456, other_fake_ts: 789 };
+ instance.saveSessionPerfData("port123", data);
+
+ let sessionPerfData = instance.sessions.get("port123").perf;
+ Assert.equal(sessionPerfData.fake_ts, 456);
+ Assert.equal(sessionPerfData.other_fake_ts, 789);
+
+ sandbox.restore();
+});
+
+add_task(async function test_saveSessionPerfData_calls_setLoadTriggerInfo() {
+ info(
+ "TelemetryFeed.saveSessionPerfData should call setLoadTriggerInfo if " +
+ "data has visibility_event_rcvd_ts"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123");
+ let data = { visibility_event_rcvd_ts: 444455 };
+
+ instance.saveSessionPerfData("port123", data);
+
+ Assert.ok(
+ instance.setLoadTriggerInfo.calledOnce,
+ "TelemetryFeed.setLoadTriggerInfo was called once"
+ );
+ Assert.ok(instance.setLoadTriggerInfo.calledWithExactly("port123"));
+
+ Assert.equal(
+ instance.sessions.get("port123").perf.visibility_event_rcvd_ts,
+ 444455
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_saveSessionPerfData_does_not_call_setLoadTriggerInfo() {
+ info(
+ "TelemetryFeed.saveSessionPerfData shouldn't call setLoadTriggerInfo if " +
+ "data has no visibility_event_rcvd_ts"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123");
+ instance.saveSessionPerfData("port123", { monkeys_ts: 444455 });
+
+ Assert.ok(
+ instance.setLoadTriggerInfo.notCalled,
+ "TelemetryFeed.setLoadTriggerInfo was not called"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_saveSessionPerfData_does_not_call_setLoadTriggerInfo_about_home() {
+ info(
+ "TelemetryFeed.saveSessionPerfData should not call setLoadTriggerInfo when " +
+ "url is about:home"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123", "about:home");
+ let data = { visibility_event_rcvd_ts: 444455 };
+ instance.saveSessionPerfData("port123", data);
+
+ Assert.ok(
+ instance.setLoadTriggerInfo.notCalled,
+ "TelemetryFeed.setLoadTriggerInfo was not called"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_saveSessionPerfData_calls_maybeRecordTopsitesPainted() {
+ info(
+ "TelemetryFeed.saveSessionPerfData should call maybeRecordTopsitesPainted " +
+ "when url is about:home and topsites_first_painted_ts is given"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ const TOPSITES_FIRST_PAINTED_TS = 44455;
+ let data = { topsites_first_painted_ts: TOPSITES_FIRST_PAINTED_TS };
+
+ sandbox.stub(AboutNewTab, "maybeRecordTopsitesPainted");
+ instance.addSession("port123", "about:home");
+ instance.saveSessionPerfData("port123", data);
+
+ Assert.ok(
+ AboutNewTab.maybeRecordTopsitesPainted.calledOnce,
+ "AboutNewTab.maybeRecordTopsitesPainted called once"
+ );
+ Assert.ok(
+ AboutNewTab.maybeRecordTopsitesPainted.calledWith(
+ TOPSITES_FIRST_PAINTED_TS
+ )
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_saveSessionPerfData_records_Glean_newtab_opened_event() {
+ info(
+ "TelemetryFeed.saveSessionPerfData should record a Glean newtab.opened event " +
+ "with the correct visit_id when visibility event received"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "decafc0ffee";
+ const PAGE = "about:newtab";
+ let session = { page: PAGE, perf: {}, session_id: SESSION_ID };
+ let data = { visibility_event_rcvd_ts: 444455 };
+
+ sandbox.stub(instance.sessions, "get").returns(session);
+ instance.saveSessionPerfData("port123", data);
+
+ let newtabOpenedEvents = Glean.newtab.opened.testGetValue();
+ Assert.deepEqual(newtabOpenedEvents[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ source: PAGE,
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_uninit_calls_utEvents_uninit() {
+ info("TelemetryFeed.uninit should call .utEvents.uninit");
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ sandbox.stub(instance.utEvents, "uninit");
+
+ instance.uninit();
+ Assert.ok(
+ instance.utEvents.uninit.calledOnce,
+ "TelemetryFeed.utEvents.uninit should be called"
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_uninit_deregisters_observer() {
+ info(
+ "TelemetryFeed.uninit should make this.browserOpenNewtabStart() stop " +
+ "observing browser-open-newtab-start"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ let countObservers = () => {
+ return [...Services.obs.enumerateObservers("browser-open-newtab-start")]
+ .length;
+ };
+
+ const ORIGINAL_COUNT = countObservers();
+ instance.init();
+ Assert.equal(countObservers(), ORIGINAL_COUNT + 1, "Observer was added");
+
+ instance.uninit();
+ Assert.equal(countObservers(), ORIGINAL_COUNT, "Observer was removed");
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_basic_actions() {
+ let browser = Services.appShell
+ .createWindowlessBrowser(false)
+ .document.createElement("browser");
+
+ let testOnAction = (setupFn, action, checkFn) => {
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ setupFn(sandbox, instance);
+
+ instance.onAction(action);
+ checkFn(instance);
+ sandbox.restore();
+ };
+
+ info("TelemetryFeed.onAction should call .init() on an INIT action");
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "init");
+ sandbox.stub(instance, "sendPageTakeoverData");
+ },
+ { type: at.INIT },
+ instance => {
+ Assert.ok(instance.init.calledOnce, "TelemetryFeed.init called once");
+ Assert.ok(
+ instance.sendPageTakeoverData.calledOnce,
+ "TelemetryFeed.sendPageTakeoverData called once"
+ );
+ }
+ );
+
+ info("TelemetryFeed.onAction should call .uninit() on an UNINIT action");
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "uninit");
+ },
+ { type: at.UNINIT },
+ instance => {
+ Assert.ok(instance.uninit.calledOnce, "TelemetryFeed.uninit called once");
+ }
+ );
+
+ info(
+ "TelemetryFeed.onAction should call .handleNewTabInit on a " +
+ "NEW_TAB_INIT action"
+ );
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "handleNewTabInit");
+ },
+ ac.AlsoToMain({
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:newtab", browser },
+ }),
+ instance => {
+ Assert.ok(
+ instance.handleNewTabInit.calledOnce,
+ "TelemetryFeed.handleNewTabInit called once"
+ );
+ }
+ );
+
+ info(
+ "TelemetryFeed.onAction should call .addSession() on a " +
+ "NEW_TAB_INIT action"
+ );
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "addSession").returns({ perf: {} });
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ },
+ ac.AlsoToMain(
+ {
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:monkeys", browser },
+ },
+ "port123"
+ ),
+ instance => {
+ Assert.ok(
+ instance.addSession.calledOnce,
+ "TelemetryFeed.addSession called once"
+ );
+ Assert.ok(instance.addSession.calledWith("port123", "about:monkeys"));
+ }
+ );
+
+ info(
+ "TelemetryFeed.onAction should call .endSession() on a " +
+ "NEW_TAB_UNLOAD action"
+ );
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "endSession");
+ },
+ ac.AlsoToMain({ type: at.NEW_TAB_UNLOAD }, "port123"),
+ instance => {
+ Assert.ok(
+ instance.endSession.calledOnce,
+ "TelemetryFeed.endSession called once"
+ );
+ Assert.ok(instance.endSession.calledWith("port123"));
+ }
+ );
+
+ info(
+ "TelemetryFeed.onAction should call .saveSessionPerfData " +
+ "on SAVE_SESSION_PERF_DATA"
+ );
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "saveSessionPerfData");
+ },
+ ac.AlsoToMain(
+ { type: at.SAVE_SESSION_PERF_DATA, data: { some_ts: 10 } },
+ "port123"
+ ),
+ instance => {
+ Assert.ok(
+ instance.saveSessionPerfData.calledOnce,
+ "TelemetryFeed.saveSessionPerfData called once"
+ );
+ Assert.ok(
+ instance.saveSessionPerfData.calledWith("port123", { some_ts: 10 })
+ );
+ }
+ );
+
+ info(
+ "TelemetryFeed.onAction should send an event on a TELEMETRY_USER_EVENT " +
+ "action"
+ );
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "createUserEvent");
+ sandbox.stub(instance.utEvents, "sendUserEvent");
+ },
+ { type: at.TELEMETRY_USER_EVENT },
+ instance => {
+ Assert.ok(
+ instance.createUserEvent.calledOnce,
+ "TelemetryFeed.createUserEvent called once"
+ );
+ Assert.ok(
+ instance.createUserEvent.calledWith({ type: at.TELEMETRY_USER_EVENT })
+ );
+ Assert.ok(
+ instance.utEvents.sendUserEvent.calledOnce,
+ "TelemetryFeed.utEvents.sendUserEvent called once"
+ );
+ Assert.ok(
+ instance.utEvents.sendUserEvent.calledWith(
+ instance.createUserEvent.returnValue
+ )
+ );
+ }
+ );
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+
+ info(
+ "TelemetryFeed.onAction should send an event on a " +
+ "DISCOVERY_STREAM_USER_EVENT action"
+ );
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ testOnAction(
+ (sandbox, instance) => {
+ sandbox.stub(instance, "createUserEvent");
+ sandbox.stub(instance.utEvents, "sendUserEvent");
+ },
+ { type: at.DISCOVERY_STREAM_USER_EVENT },
+ instance => {
+ Assert.ok(
+ instance.createUserEvent.calledOnce,
+ "TelemetryFeed.createUserEvent called once"
+ );
+ Assert.ok(
+ instance.createUserEvent.calledWith({
+ type: at.DISCOVERY_STREAM_USER_EVENT,
+ data: {
+ value: {
+ pocket_logged_in_status: Glean.pocket.isSignedIn.testGetValue(),
+ },
+ },
+ })
+ );
+ Assert.ok(
+ instance.utEvents.sendUserEvent.calledOnce,
+ "TelemetryFeed.utEvents.sendUserEvent called once"
+ );
+ Assert.ok(
+ instance.utEvents.sendUserEvent.calledWith(
+ instance.createUserEvent.returnValue
+ )
+ );
+ }
+ );
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+});
+
+add_task(async function test_onAction_calls_handleASRouterUserEvent() {
+ let actions = [
+ at.AS_ROUTER_TELEMETRY_USER_EVENT,
+ msg.TOOLBAR_BADGE_TELEMETRY,
+ msg.TOOLBAR_PANEL_TELEMETRY,
+ msg.MOMENTS_PAGE_TELEMETRY,
+ msg.DOORHANGER_TELEMETRY,
+ ];
+ Services.prefs.setBoolPref(PREF_EVENT_TELEMETRY, true);
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ actions.forEach(type => {
+ info(`Testing ${type} action`);
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ const eventHandler = sandbox.spy(instance, "handleASRouterUserEvent");
+ const action = {
+ type,
+ data: { event: "CLICK" },
+ };
+
+ instance.onAction(action);
+
+ Assert.ok(eventHandler.calledWith(action));
+ sandbox.restore();
+ });
+ Services.prefs.clearUserPref(PREF_EVENT_TELEMETRY);
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+});
+
+add_task(
+ async function test_onAction_calls_handleDiscoveryStreamImpressionStats_ds() {
+ info(
+ "TelemetryFeed.onAction should call " +
+ ".handleDiscoveryStreamImpressionStats on a " +
+ "DISCOVERY_STREAM_IMPRESSION_STATS action"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ let data = { source: "foo", tiles: [{ id: 1 }] };
+ let action = { type: at.DISCOVERY_STREAM_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleDiscoveryStreamImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action, "port123"));
+
+ Assert.ok(
+ instance.handleDiscoveryStreamImpressionStats.calledWith("port123", data)
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_onAction_calls_handleTopSitesSponsoredImpressionStats() {
+ info(
+ "TelemetryFeed.onAction should call " +
+ ".handleTopSitesSponsoredImpressionStats on a " +
+ "TOP_SITES_SPONSORED_IMPRESSION_STATS action"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ let data = { type: "impression", tile_id: 42, position: 1 };
+ let action = { type: at.TOP_SITES_SPONSORED_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleTopSitesSponsoredImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ Assert.ok(
+ instance.handleTopSitesSponsoredImpressionStats.calledOnce,
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats called once"
+ );
+ Assert.deepEqual(
+ instance.handleTopSitesSponsoredImpressionStats.firstCall.args[0].data,
+ data
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_onAction_calls_handleAboutSponsoredTopSites() {
+ info(
+ "TelemetryFeed.onAction should call " +
+ ".handleAboutSponsoredTopSites on a " +
+ "ABOUT_SPONSORED_TOP_SITES action"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let data = { position: 0, advertiser_name: "moo", tile_id: 42 };
+ let action = { type: at.ABOUT_SPONSORED_TOP_SITES, data };
+ sandbox.spy(instance, "handleAboutSponsoredTopSites");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ Assert.ok(
+ instance.handleAboutSponsoredTopSites.calledOnce,
+ "TelemetryFeed.handleAboutSponsoredTopSites called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_calls_handleBlockUrl() {
+ info(
+ "TelemetryFeed.onAction should call #handleBlockUrl on a BLOCK_URL action"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let data = { position: 0, advertiser_name: "moo", tile_id: 42 };
+ let action = { type: at.BLOCK_URL, data };
+ sandbox.spy(instance, "handleBlockUrl");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ Assert.ok(
+ instance.handleBlockUrl.calledOnce,
+ "TelemetryFeed.handleBlockUrl called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_onAction_calls_handleTopSitesOrganicImpressionStats() {
+ info(
+ "TelemetryFeed.onAction should call .handleTopSitesOrganicImpressionStats " +
+ "on a TOP_SITES_ORGANIC_IMPRESSION_STATS action"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+
+ let data = { type: "impression", position: 1 };
+ let action = { type: at.TOP_SITES_ORGANIC_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleTopSitesOrganicImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action));
+
+ Assert.ok(
+ instance.handleTopSitesOrganicImpressionStats.calledOnce,
+ "TelemetryFeed.handleTopSitesOrganicImpressionStats called once"
+ );
+ Assert.deepEqual(
+ instance.handleTopSitesOrganicImpressionStats.firstCall.args[0].data,
+ data
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_handleNewTabInit_sets_preloaded_session() {
+ info(
+ "TelemetryFeed.handleNewTabInit should set the session as preloaded " +
+ "if the browser is preloaded"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let 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, "is_preloaded property was set");
+
+ sandbox.restore();
+});
+
+add_task(async function test_handleNewTabInit_sets_nonpreloaded_session() {
+ info(
+ "TelemetryFeed.handleNewTabInit should set the session as non-preloaded " +
+ "if the browser is non-preloaded"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ let session = { perf: {} };
+ let preloadedBrowser = {
+ getAttribute() {
+ return "";
+ },
+ };
+ 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, "is_preloaded property is not true");
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_SendASRouterUndesiredEvent_calls_handleASRouterUserEvent() {
+ info(
+ "TelemetryFeed.SendASRouterUndesiredEvent should call " +
+ "handleASRouterUserEvent"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ sandbox.stub(instance, "handleASRouterUserEvent");
+
+ instance.SendASRouterUndesiredEvent({ foo: "bar" });
+
+ Assert.ok(
+ instance.handleASRouterUserEvent.calledOnce,
+ "TelemetryFeed.handleASRouterUserEvent was called once"
+ );
+ let [payload] = instance.handleASRouterUserEvent.firstCall.args;
+ Assert.equal(payload.data.action, "asrouter_undesired_event");
+ Assert.equal(payload.data.foo, "bar");
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_sendPageTakeoverData_homepage_category() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData should call " +
+ "handleASRouterUserEvent"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ sandbox.stub(HomePage, "get").returns("https://searchprovider.com");
+ instance._classifySite = () => Promise.resolve("other");
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.homepageCategory.testGetValue(), "other");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_newtab_category_custom() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData should send correct newtab " +
+ "category for about:newtab set to custom URL"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ sandbox.stub(AboutNewTab, "newTabURLOverridden").get(() => true);
+ sandbox
+ .stub(AboutNewTab, "newTabURL")
+ .get(() => "https://searchprovider.com");
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ instance._classifySite = () => Promise.resolve("other");
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.newtabCategory.testGetValue(), "other");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_newtab_category_custom() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData should not set home|newtab " +
+ "category if neither about:{home,newtab} are set to custom URL"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ instance._classifySite = () => Promise.resolve("other");
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.newtabCategory.testGetValue(), "enabled");
+ Assert.equal(Glean.newtab.homepageCategory.testGetValue(), "enabled");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_newtab_category_extension() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData should set correct home|newtab " +
+ "category when changed by extension"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const ID = "{abc-foo-bar}";
+ sandbox.stub(ExtensionSettingsStore, "getSetting").returns({ id: ID });
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ instance._classifySite = () => Promise.resolve("other");
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.newtabCategory.testGetValue(), "extension");
+ Assert.equal(Glean.newtab.homepageCategory.testGetValue(), "extension");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_newtab_disabled() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData instruments when newtab is disabled"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ Services.prefs.setBoolPref("browser.newtabpage.enabled", false);
+ instance._classifySite = () => Promise.resolve("other");
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.newtabCategory.testGetValue(), "disabled");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ Services.prefs.clearUserPref("browser.newtabpage.enabled");
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_homepage_disabled() {
+ info(
+ "TelemetryFeed.sendPageTakeoverData instruments when homepage is disabled"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+ sandbox.stub(HomePage, "overridden").get(() => true);
+
+ await instance.sendPageTakeoverData();
+ Assert.equal(Glean.newtab.homepageCategory.testGetValue(), "disabled");
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(async function test_sendPageTakeoverData_newtab_ping() {
+ info("TelemetryFeed.sendPageTakeoverData should send a 'newtab' ping");
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+
+ let pingSubmitted = new Promise(resolve => {
+ GleanPings.newtab.testBeforeNextSubmit(reason => {
+ Assert.equal(reason, "component_init");
+ resolve();
+ });
+ });
+
+ await instance.sendPageTakeoverData();
+ await pingSubmitted;
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+});
+
+add_task(
+ async function test_handleDiscoveryStreamImpressionStats_should_throw() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamImpressionStats should throw " +
+ "for a missing session"
+ );
+
+ let instance = new TelemetryFeed();
+ try {
+ instance.handleDiscoveryStreamImpressionStats("a_missing_port", {});
+ Assert.ok(false, "Should not have reached here.");
+ } catch (e) {
+ Assert.ok(true, "Should have thrown for a missing session.");
+ }
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamImpressionStats_instrument_pocket_impressions() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamImpressionStats should throw " +
+ "for a missing session"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "1337cafe";
+ const POS_1 = 1;
+ const POS_2 = 4;
+ const SHIM = "Y29uc2lkZXIgeW91ciBjdXJpb3NpdHkgcmV3YXJkZWQ=";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ let pingSubmitted = new Promise(resolve => {
+ GleanPings.spoc.testBeforeNextSubmit(reason => {
+ Assert.equal(reason, "impression");
+
+ let pocketImpressions = Glean.pocket.impression.testGetValue();
+ Assert.equal(pocketImpressions.length, 2);
+ Assert.deepEqual(pocketImpressions[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: String(POS_1),
+ recommendation_id: "decaf-c0ff33",
+ tile_id: String(1),
+ });
+ Assert.deepEqual(pocketImpressions[1].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(true),
+ position: String(POS_2),
+ tile_id: String(2),
+ });
+ Assert.equal(Glean.pocket.shim.testGetValue(), SHIM);
+
+ resolve();
+ });
+ });
+
+ instance.handleDiscoveryStreamImpressionStats("_", {
+ source: "foo",
+ tiles: [
+ {
+ id: 1,
+ pos: POS_1,
+ type: "organic",
+ recommendation_id: "decaf-c0ff33",
+ },
+ {
+ id: 2,
+ pos: POS_2,
+ type: "spoc",
+ recommendation_id: undefined,
+ shim: SHIM,
+ },
+ ],
+ window_inner_width: 1000,
+ window_inner_height: 900,
+ });
+
+ await pingSubmitted;
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleASRouterUserEvent_calls_submitGleanPingForPing() {
+ info(
+ "TelemetryFeed.handleASRouterUserEvent should call " +
+ "submitGleanPingForPing on known pingTypes when telemetry is enabled"
+ );
+
+ let data = {
+ action: "onboarding_user_event",
+ event: "IMPRESSION",
+ message_id: "12345",
+ };
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+
+ sandbox.spy(AboutWelcomeTelemetry.prototype, "submitGleanPingForPing");
+
+ await instance.handleASRouterUserEvent({ data });
+
+ Assert.ok(
+ AboutWelcomeTelemetry.prototype.submitGleanPingForPing.calledOnce,
+ "AboutWelcomeTelemetry.submitGleanPingForPing called once"
+ );
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleASRouterUserEvent_no_submit_unknown_pingTypes() {
+ info(
+ "TelemetryFeed.handleASRouterUserEvent not submit pings on unknown pingTypes"
+ );
+
+ let data = {
+ action: "unknown_event",
+ event: "IMPRESSION",
+ message_id: "12345",
+ };
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ Services.prefs.setBoolPref(PREF_TELEMETRY, true);
+
+ sandbox.spy(AboutWelcomeTelemetry.prototype, "submitGleanPingForPing");
+
+ await instance.handleASRouterUserEvent({ data });
+
+ Assert.ok(
+ AboutWelcomeTelemetry.prototype.submitGleanPingForPing.notCalled,
+ "AboutWelcomeTelemetry.submitGleanPingForPing not called"
+ );
+
+ Services.prefs.clearUserPref(PREF_TELEMETRY);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_isInCFRCohort_return_false_for_no_CFR_experiment() {
+ info(
+ "TelemetryFeed.isInCFRCohort should return false if there " +
+ "is no CFR experiment registered"
+ );
+ let instance = new TelemetryFeed();
+ Assert.ok(
+ !instance.isInCFRCohort,
+ "Should not be in CFR cohort by default"
+ );
+ }
+);
+
+add_task(
+ async function test_isInCFRCohort_return_true_for_registered_CFR_experiment() {
+ info(
+ "TelemetryFeed.isInCFRCohort should return true if there " +
+ "is a CFR experiment registered"
+ );
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+
+ Assert.ok(instance.isInCFRCohort, "Should be in a CFR cohort");
+ Assert.equal(
+ ExperimentAPI.getExperimentMetaData.firstCall.args[0].featureId,
+ "cfr"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesSponsoredImpressionStats_add_keyed_scalar() {
+ info(
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats should add to " +
+ "keyed scalar on an impression event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.telemetry.clearScalars();
+
+ let data = {
+ type: "impression",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+ TelemetryTestUtils.assertKeyedScalar(
+ TelemetryTestUtils.getProcessScalars("parent", true, true),
+ "contextual.services.topsites.impression",
+ "newtab_1",
+ 1
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesSponsoredImpressionStats_add_keyed_scalar_click() {
+ info(
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats should add to " +
+ "keyed scalar on a click event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.telemetry.clearScalars();
+
+ let data = {
+ type: "click",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+ TelemetryTestUtils.assertKeyedScalar(
+ TelemetryTestUtils.getProcessScalars("parent", true, true),
+ "contextual.services.topsites.click",
+ "newtab_1",
+ 1
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesSponsoredImpressionStats_record_glean_impression() {
+ info(
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats should record a " +
+ "Glean topsites.impression event on an impression event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ type: "impression",
+ tile_id: 42,
+ source: "newtab",
+ position: 1,
+ reporting_url: "https://test.reporting.net/",
+ advertiser: "adnoid ads",
+ };
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+ let impressions = Glean.topsites.impression.testGetValue();
+ Assert.equal(impressions.length, 1, "Should have recorded 1 impression");
+
+ Assert.deepEqual(impressions[0].extra, {
+ advertiser_name: "adnoid ads",
+ tile_id: data.tile_id,
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(true),
+ position: String(1),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesSponsoredImpressionStats_record_glean_click() {
+ info(
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats should record " +
+ "a Glean topsites.click event on a click event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ type: "click",
+ advertiser: "test advertiser",
+ tile_id: 42,
+ source: "newtab",
+ position: 0,
+ reporting_url: "https://test.reporting.net/",
+ };
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+ let clicks = Glean.topsites.click.testGetValue();
+ Assert.equal(clicks.length, 1, "Should have recorded 1 click");
+
+ Assert.deepEqual(clicks[0].extra, {
+ advertiser_name: "test advertiser",
+ tile_id: data.tile_id,
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(true),
+ position: String(0),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesSponsoredImpressionStats_no_submit_unknown_pingType() {
+ info(
+ "TelemetryFeed.handleTopSitesSponsoredImpressionStats should not " +
+ "submit on unknown pingTypes"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = { type: "unknown_type" };
+
+ await instance.handleTopSitesSponsoredImpressionStats({ data });
+ let impressions = Glean.topsites.impression.testGetValue();
+ Assert.ok(!impressions, "Should not have recorded any impressions");
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesOrganicImpressionStats_record_glean_topsites_impression() {
+ info(
+ "TelemetryFeed.handleTopSitesOrganicImpressionStats should record a " +
+ "Glean topsites.impression event on an impression event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ type: "impression",
+ source: "newtab",
+ position: 0,
+ };
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ await instance.handleTopSitesOrganicImpressionStats({ data });
+ let impressions = Glean.topsites.impression.testGetValue();
+ Assert.equal(impressions.length, 1, "Recorded 1 impression");
+
+ Assert.deepEqual(impressions[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: String(0),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesOrganicImpressionStats_record_glean_topsites_click() {
+ info(
+ "TelemetryFeed.handleTopSitesOrganicImpressionStats should record a " +
+ "Glean topsites.click event on a click event"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ type: "click",
+ source: "newtab",
+ position: 0,
+ };
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ await instance.handleTopSitesOrganicImpressionStats({ data });
+ let clicks = Glean.topsites.click.testGetValue();
+ Assert.equal(clicks.length, 1, "Recorded 1 click");
+
+ Assert.deepEqual(clicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: String(0),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesOrganicImpressionStats_no_recording() {
+ info(
+ "TelemetryFeed.handleTopSitesOrganicImpressionStats should not " +
+ "record events on an unknown session"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ sandbox.stub(instance.sessions, "get").returns(false);
+
+ await instance.handleTopSitesOrganicImpressionStats({});
+ Assert.ok(!Glean.topsites.click.testGetValue(), "Click was not recorded");
+ Assert.ok(
+ !Glean.topsites.impression.testGetValue(),
+ "Impression was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleTopSitesOrganicImpressionStats_no_recording_with_session() {
+ info(
+ "TelemetryFeed.handleTopSitesOrganicImpressionStats should not record " +
+ "events on an unknown impressionStats action"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ await instance.handleTopSitesOrganicImpressionStats({ type: "unknown" });
+ Assert.ok(!Glean.topsites.click.testGetValue(), "Click was not recorded");
+ Assert.ok(
+ !Glean.topsites.impression.testGetValue(),
+ "Impression was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_no_recording_with_session() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent correctly handles " +
+ "action with no `data`"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let action = ac.DiscoveryStreamUserEvent();
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+ Assert.ok(
+ !Glean.pocket.topicClick.testGetValue(),
+ "Pocket topicClick was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.click.testGetValue(),
+ "Pocket click was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.save.testGetValue(),
+ "Pocket save was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_click_with_no_value() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent correctly handles " +
+ "CLICK data with no value"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ });
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+ let topicClicks = Glean.pocket.topicClick.testGetValue();
+ Assert.equal(topicClicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(topicClicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_non_popular_click_with_no_value() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent correctly handles " +
+ "non-POPULAR_TOPICS CLICK data with no value"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ });
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+ Assert.ok(
+ !Glean.pocket.topicClick.testGetValue(),
+ "Pocket topicClick was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.click.testGetValue(),
+ "Pocket click was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.save.testGetValue(),
+ "Pocket save was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_non_popular_click() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent correctly handles " +
+ "CLICK data with non-POPULAR_TOPICS source"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const TOPIC = "atopic";
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ value: {
+ card_type: "topics_widget",
+ topic: TOPIC,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+ let topicClicks = Glean.pocket.topicClick.testGetValue();
+ Assert.equal(topicClicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(topicClicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ topic: TOPIC,
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_without_card_type() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent doesn't instrument " +
+ "a CLICK without a card_type"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "not-POPULAR_TOPICS",
+ value: {
+ card_type: "not spoc, organic, or topics_widget",
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ Assert.ok(
+ !Glean.pocket.topicClick.testGetValue(),
+ "Pocket topicClick was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.click.testGetValue(),
+ "Pocket click was not recorded"
+ );
+ Assert.ok(
+ !Glean.pocket.save.testGetValue(),
+ "Pocket save was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_handleDiscoveryStreamUserEvent_popular_click() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments a popular " +
+ "topic click"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const TOPIC = "entertainment";
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ value: {
+ card_type: "topics_widget",
+ topic: TOPIC,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+ let topicClicks = Glean.pocket.topicClick.testGetValue();
+ Assert.equal(topicClicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(topicClicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ topic: TOPIC,
+ });
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_organic_top_stories_click() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments an organic " +
+ "top stories click"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const ACTION_POSITION = 42;
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ action_position: ACTION_POSITION,
+ value: {
+ card_type: "organic",
+ recommendation_id: "decaf-c0ff33",
+ tile_id: 314623757745896,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ let clicks = Glean.pocket.click.testGetValue();
+ Assert.equal(clicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(clicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: ACTION_POSITION,
+ recommendation_id: "decaf-c0ff33",
+ tile_id: String(314623757745896),
+ });
+
+ Assert.ok(
+ !Glean.pocket.shim.testGetValue(),
+ "Pocket shim was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_sponsored_top_stories_click() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments a sponsored " +
+ "top stories click"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const ACTION_POSITION = 42;
+ const SHIM = "Y29uc2lkZXIgeW91ciBjdXJpb3NpdHkgcmV3YXJkZWQ=";
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "CLICK",
+ action_position: ACTION_POSITION,
+ value: {
+ card_type: "spoc",
+ recommendation_id: undefined,
+ tile_id: 448685088,
+ shim: SHIM,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ let pingSubmitted = new Promise(resolve => {
+ GleanPings.spoc.testBeforeNextSubmit(reason => {
+ Assert.equal(reason, "click");
+ resolve();
+ });
+ });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ let clicks = Glean.pocket.click.testGetValue();
+ Assert.equal(clicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(clicks[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(true),
+ position: ACTION_POSITION,
+ tile_id: String(448685088),
+ });
+
+ await pingSubmitted;
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_organic_top_stories_save() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments a save of an " +
+ "organic top story"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const ACTION_POSITION = 42;
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position: ACTION_POSITION,
+ value: {
+ card_type: "organic",
+ recommendation_id: "decaf-c0ff33",
+ tile_id: 314623757745896,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ let saves = Glean.pocket.save.testGetValue();
+ Assert.equal(saves.length, 1, "Recorded 1 save");
+ Assert.deepEqual(saves[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: ACTION_POSITION,
+ recommendation_id: "decaf-c0ff33",
+ tile_id: String(314623757745896),
+ });
+ Assert.ok(
+ !Glean.pocket.shim.testGetValue(),
+ "Pocket shim was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_sponsored_top_stories_save() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments a save of a " +
+ "sponsored top story"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const ACTION_POSITION = 42;
+ const SHIM = "Y29uc2lkZXIgeW91ciBjdXJpb3NpdHkgcmV3YXJkZWQ=";
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position: ACTION_POSITION,
+ value: {
+ card_type: "spoc",
+ recommendation_id: undefined,
+ tile_id: 448685088,
+ shim: SHIM,
+ },
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+ let pingSubmitted = new Promise(resolve => {
+ GleanPings.spoc.testBeforeNextSubmit(reason => {
+ Assert.equal(reason, "save");
+ Assert.equal(
+ Glean.pocket.shim.testGetValue(),
+ SHIM,
+ "Pocket shim was recorded"
+ );
+
+ resolve();
+ });
+ });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ let saves = Glean.pocket.save.testGetValue();
+ Assert.equal(saves.length, 1, "Recorded 1 save");
+ Assert.deepEqual(saves[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(true),
+ position: ACTION_POSITION,
+ tile_id: String(448685088),
+ });
+
+ await pingSubmitted;
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleDiscoveryStreamUserEvent_sponsored_top_stories_save_no_value() {
+ info(
+ "TelemetryFeed.handleDiscoveryStreamUserEvent instruments a save of a " +
+ "sponsored top story, without `value`"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+ const ACTION_POSITION = 42;
+ let action = ac.DiscoveryStreamUserEvent({
+ event: "SAVE_TO_POCKET",
+ action_position: ACTION_POSITION,
+ });
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleDiscoveryStreamUserEvent(action);
+
+ let saves = Glean.pocket.save.testGetValue();
+ Assert.equal(saves.length, 1, "Recorded 1 save");
+ Assert.deepEqual(saves[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: ACTION_POSITION,
+ });
+ Assert.ok(
+ !Glean.pocket.shim.testGetValue(),
+ "Pocket shim was not recorded"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleAboutSponsoredTopSites_record_showPrivacyClick() {
+ info(
+ "TelemetryFeed.handleAboutSponsoredTopSites should record a Glean " +
+ "topsites.showPrivacyClick event on action"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ position: 42,
+ advertiser_name: "mozilla",
+ tile_id: 4567,
+ };
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ instance.handleAboutSponsoredTopSites({ data });
+
+ let clicks = Glean.topsites.showPrivacyClick.testGetValue();
+ Assert.equal(clicks.length, 1, "Recorded 1 click");
+ Assert.deepEqual(clicks[0].extra, {
+ advertiser_name: data.advertiser_name,
+ tile_id: String(data.tile_id),
+ newtab_visit_id: SESSION_ID,
+ position: String(data.position),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_handleAboutSponsoredTopSites_no_record_showPrivacyClick() {
+ info(
+ "TelemetryFeed.handleAboutSponsoredTopSites should not record a Glean " +
+ "topsites.showPrivacyClick event if there's no session"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ let data = {
+ position: 42,
+ advertiser_name: "mozilla",
+ tile_id: 4567,
+ };
+
+ sandbox.stub(instance.sessions, "get").returns(null);
+
+ instance.handleAboutSponsoredTopSites({ data });
+
+ let clicks = Glean.topsites.showPrivacyClick.testGetValue();
+ Assert.ok(!clicks, "Did not record any clicks");
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_handleBlockUrl_no_record_dismisses() {
+ info(
+ "TelemetryFeed.handleBlockUrl shouldn't record events for pocket " +
+ "cards' dismisses"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ let data = [
+ {
+ // Shouldn't record anything for this one
+ is_pocket_card: true,
+ position: 43,
+ tile_id: undefined,
+ },
+ ];
+
+ await instance.handleBlockUrl({ data });
+
+ Assert.ok(
+ !Glean.topsites.dismiss.testGetValue(),
+ "Should not record a dismiss for Pocket cards"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_handleBlockUrl_record_dismiss_on_action() {
+ info(
+ "TelemetryFeed.handleBlockUrl should record a topsites.dismiss event " +
+ "on action"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ let data = [
+ {
+ is_pocket_card: false,
+ position: 42,
+ advertiser_name: "mozilla",
+ tile_id: 4567,
+ isSponsoredTopSite: 1, // for some reason this is an int.
+ },
+ ];
+
+ await instance.handleBlockUrl({ data });
+
+ let dismisses = Glean.topsites.dismiss.testGetValue();
+ Assert.equal(dismisses.length, 1, "Should have recorded 1 dismiss");
+ Assert.deepEqual(dismisses[0].extra, {
+ advertiser_name: data[0].advertiser_name,
+ tile_id: String(data[0].tile_id),
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(!!data[0].isSponsoredTopSite),
+ position: String(data[0].position),
+ });
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_handleBlockUrl_record_dismiss_on_nonsponsored_action() {
+ info(
+ "TelemetryFeed.handleBlockUrl should record a Glean topsites.dismiss " +
+ "event on action on non-sponsored topsite"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ const SESSION_ID = "decafc0ffee";
+ sandbox.stub(instance.sessions, "get").returns({ session_id: SESSION_ID });
+
+ let data = [
+ {
+ is_pocket_card: false,
+ position: 42,
+ tile_id: undefined,
+ },
+ ];
+
+ await instance.handleBlockUrl({ data });
+
+ let dismisses = Glean.topsites.dismiss.testGetValue();
+ Assert.equal(dismisses.length, 1, "Should have recorded 1 dismiss");
+ Assert.deepEqual(dismisses[0].extra, {
+ newtab_visit_id: SESSION_ID,
+ is_sponsored: String(false),
+ position: String(data[0].position),
+ });
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_handleBlockUrl_no_record_dismiss_on_no_session() {
+ info(
+ "TelemetryFeed.handleBlockUrl should not record a Glean " +
+ "topsites.dismiss event if there's no session"
+ );
+
+ let sandbox = sinon.createSandbox();
+ let instance = new TelemetryFeed();
+ Services.fog.testResetFOG();
+
+ sandbox.stub(instance.sessions, "get").returns(null);
+
+ let data = {};
+
+ await instance.handleBlockUrl({ data });
+
+ Assert.ok(
+ !Glean.topsites.dismiss.testGetValue(),
+ "Should not have recorded a dismiss"
+ );
+
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_TopSitesFeed.js b/browser/components/newtab/test/xpcshell/test_TopSitesFeed.js
new file mode 100644
index 0000000000..860e8758a5
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_TopSitesFeed.js
@@ -0,0 +1,3397 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { TopSitesFeed, DEFAULT_TOP_SITES } = ChromeUtils.importESModule(
+ "resource://activity-stream/lib/TopSitesFeed.sys.mjs"
+);
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.importESModule(
+ "resource://activity-stream/common/Actions.sys.mjs"
+);
+
+ChromeUtils.defineESModuleGetters(this, {
+ FilterAdult: "resource://activity-stream/lib/FilterAdult.sys.mjs",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
+ shortURL: "resource://activity-stream/lib/ShortURL.sys.mjs",
+ sinon: "resource://testing-common/Sinon.sys.mjs",
+ Screenshots: "resource://activity-stream/lib/Screenshots.sys.mjs",
+ Sampling: "resource://gre/modules/components-utils/Sampling.sys.mjs",
+ SearchService: "resource://gre/modules/SearchService.sys.mjs",
+ TOP_SITES_DEFAULT_ROWS: "resource://activity-stream/common/Reducers.sys.mjs",
+ TOP_SITES_MAX_SITES_PER_ROW:
+ "resource://activity-stream/common/Reducers.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 CONTILE_CACHE_PREF = "browser.topsites.contile.cachedTiles";
+
+// This pref controls how long the contile cache is valid for in seconds.
+const CONTILE_CACHE_VALID_FOR_SECONDS_PREF =
+ "browser.topsites.contile.cacheValidFor";
+// This pref records when the last contile fetch occurred, as a UNIX timestamp
+// in seconds.
+const CONTILE_CACHE_LAST_FETCH_PREF = "browser.topsites.contile.lastFetch";
+
+function FakeTippyTopProvider() {}
+FakeTippyTopProvider.prototype = {
+ async init() {
+ this.initialized = true;
+ },
+ processSite(site) {
+ return site;
+ },
+};
+
+let gSearchServiceInitStub;
+let gGetTopSitesStub;
+
+function getTopSitesFeedForTest(sandbox) {
+ let 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) },
+ };
+
+ return feed;
+}
+
+add_setup(async () => {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(SearchService.prototype, "defaultEngine").get(() => {
+ return { identifier: "ddg", searchForm: "https://duckduckgo.com" };
+ });
+
+ gGetTopSitesStub = sandbox
+ .stub(NewTabUtils.activityStreamLinks, "getTopSites")
+ .resolves(FAKE_LINKS);
+
+ gSearchServiceInitStub = sandbox
+ .stub(SearchService.prototype, "init")
+ .resolves();
+
+ sandbox.stub(NewTabUtils.activityStreamProvider, "_faviconBytesToDataURI");
+
+ sandbox
+ .stub(NewTabUtils.activityStreamProvider, "_addFavicons")
+ .callsFake(l => {
+ return Promise.resolve(
+ l.map(link => {
+ link.favicon = FAKE_FAVICON;
+ link.faviconSize = FAKE_FAVICON_SIZE;
+ return link;
+ })
+ );
+ });
+
+ sandbox.stub(Screenshots, "getScreenshotForURL").resolves(FAKE_SCREENSHOT);
+ sandbox.spy(Screenshots, "maybeCacheScreenshot");
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+add_task(async function test_construction() {
+ let feed = new TopSitesFeed();
+ Assert.ok(feed, "Could construct a TopSitesFeed");
+ Assert.ok(feed._currentSearchHostname, "_currentSearchHostname defined");
+});
+
+add_task(async function test_refreshDefaults() {
+ let sandbox = sinon.createSandbox();
+ let feed = new TopSitesFeed();
+ Assert.ok(
+ !DEFAULT_TOP_SITES.length,
+ "Should have 0 DEFAULT_TOP_SITES initially."
+ );
+
+ info("refreshDefaults should add defaults on PREFS_INITIAL_VALUES");
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "https://foo.com" },
+ });
+
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 1,
+ "Should have 1 DEFAULT_TOP_SITES now."
+ );
+
+ // Reset the DEFAULT_TOP_SITES;
+ DEFAULT_TOP_SITES.length = 0;
+
+ info("refreshDefaults should add defaults on default.sites PREF_CHANGED");
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "default.sites", value: "https://foo.com" },
+ });
+
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 1,
+ "Should have 1 DEFAULT_TOP_SITES now."
+ );
+
+ // Reset the DEFAULT_TOP_SITES;
+ DEFAULT_TOP_SITES.length = 0;
+
+ info("refreshDefaults should refresh on topSiteRows PREF_CHANGED");
+ let refreshStub = sandbox.stub(feed, "refresh");
+ feed.onAction({ type: at.PREF_CHANGED, data: { name: "topSitesRows" } });
+ Assert.ok(feed.refresh.calledOnce, "refresh called");
+ refreshStub.restore();
+
+ // Reset the DEFAULT_TOP_SITES;
+ DEFAULT_TOP_SITES.length = 0;
+
+ info("refreshDefaults should have default sites with .isDefault = true");
+ feed.refreshDefaults("https://foo.com");
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 1,
+ "Should have a DEFAULT_TOP_SITES now."
+ );
+ Assert.ok(
+ DEFAULT_TOP_SITES[0].isDefault,
+ "Lone top site should be the default."
+ );
+
+ // Reset the DEFAULT_TOP_SITES;
+ DEFAULT_TOP_SITES.length = 0;
+
+ info("refreshDefaults should have default sites with appropriate hostname");
+ feed.refreshDefaults("https://foo.com");
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 1,
+ "Should have a DEFAULT_TOP_SITES now."
+ );
+ let [site] = DEFAULT_TOP_SITES;
+ Assert.equal(
+ site.hostname,
+ shortURL(site),
+ "Lone top site should have the right hostname."
+ );
+
+ // Reset the DEFAULT_TOP_SITES;
+ DEFAULT_TOP_SITES.length = 0;
+
+ info("refreshDefaults should add no defaults on empty pref");
+ feed.refreshDefaults("");
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 0,
+ "Should have 0 DEFAULT_TOP_SITES now."
+ );
+
+ info("refreshDefaults should be able to clear defaults");
+ feed.refreshDefaults("https://foo.com");
+ feed.refreshDefaults("");
+
+ Assert.equal(
+ DEFAULT_TOP_SITES.length,
+ 0,
+ "Should have 0 DEFAULT_TOP_SITES now."
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_filterForThumbnailExpiration() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ info(
+ "filterForThumbnailExpiration 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 = sandbox.stub();
+ feed.filterForThumbnailExpiration(stub);
+ Assert.ok(stub.calledOnce);
+ Assert.ok(stub.calledWithExactly(["foo.com", "bar.com", "custom"]));
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_getLinksWithDefaults_on_SearchService_init_failure() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed.refreshDefaults("https://foo.com");
+
+ gSearchServiceInitStub.rejects(new Error("Simulating search init failure"));
+
+ const result = await feed.getLinksWithDefaults();
+ Assert.ok(result);
+
+ gSearchServiceInitStub.resolves();
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_getLinksWithDefaults() {
+ NewTabUtils.activityStreamLinks.getTopSites.resetHistory();
+
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed.refreshDefaults("https://foo.com");
+
+ info("getLinksWithDefaults should get the links from NewTabUtils");
+ let result = await feed.getLinksWithDefaults();
+
+ const reference = FAKE_LINKS.map(site =>
+ Object.assign({}, site, {
+ hostname: shortURL(site),
+ typedBonus: true,
+ })
+ );
+
+ Assert.deepEqual(result, reference);
+ Assert.ok(NewTabUtils.activityStreamLinks.getTopSites.calledOnce);
+
+ info("getLinksWithDefaults should indicate the links get typed bonus");
+ Assert.ok(result[0].typedBonus, "Expected typed bonus property to be true.");
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_filterAdult() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should filter out non-pinned adult sites");
+
+ sandbox.stub(FilterAdult, "filter").returns([]);
+ const TEST_URL = "https://foo.com/";
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [{ url: TEST_URL }]);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const result = await feed.getLinksWithDefaults();
+ Assert.ok(FilterAdult.filter.calledOnce);
+ Assert.equal(result.length, 1);
+ Assert.equal(result[0].url, TEST_URL);
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_caching() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "getLinksWithDefaults should filter out the defaults that have been blocked"
+ );
+ // 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: shortURL({ url }),
+ typedBonus: true,
+ url,
+ };
+
+ const blockedDefaultSite = { url: "https://foo.com" };
+ gGetTopSitesStub.resolves([topsite]);
+ sandbox.stub(NewTabUtils.blockedLinks, "isBlocked").callsFake(site => {
+ return site.url === blockedDefaultSite.url;
+ });
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+ 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.equal(result.length, 1);
+ Assert.deepEqual(result[0], topsite);
+ let foundBlocked = result.find(site => site.url === blockedDefaultSite.url);
+ Assert.ok(!foundBlocked, "Should not have found blocked site.");
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_dedupe() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should call dedupe.group on the links");
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ let stub = sandbox.stub(feed.dedupe, "group").callsFake((...id) => id);
+ await feed.getLinksWithDefaults();
+
+ Assert.ok(stub.calledOnce, "dedupe.group was called once");
+ sandbox.restore();
+});
+
+add_task(async function test__dedupe_key() {
+ let sandbox = sinon.createSandbox();
+
+ info("_dedupeKey should dedupe on hostname instead of url");
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ let site = { url: "foo", hostname: "bar" };
+ let result = feed._dedupeKey(site);
+
+ Assert.equal(result, site.hostname, "deduped on hostname");
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_adds_defaults() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "getLinksWithDefaults should add defaults if there are are not enough links"
+ );
+ const TEST_LINKS = [{ frecency: FAKE_FRECENCY, url: "foo.com" }];
+ gGetTopSitesStub.resolves(TEST_LINKS);
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ let result = await feed.getLinksWithDefaults();
+
+ let reference = [...TEST_LINKS, ...DEFAULT_TOP_SITES].map(s =>
+ Object.assign({}, s, {
+ hostname: shortURL(s),
+ typedBonus: true,
+ })
+ );
+
+ Assert.deepEqual(result, reference);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(
+ async function test_getLinksWithDefaults_adds_defaults_for_visible_slots() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "getLinksWithDefaults should only add defaults up to the number of visible slots"
+ );
+ const numVisible = TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW;
+ let testLinks = [];
+ for (let i = 0; i < numVisible - 1; i++) {
+ testLinks.push({ frecency: FAKE_FRECENCY, url: `foo${i}.com` });
+ }
+ gGetTopSitesStub.resolves(testLinks);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ let result = await feed.getLinksWithDefaults();
+
+ let reference = [...testLinks, DEFAULT_TOP_SITES[0]].map(s =>
+ Object.assign({}, s, {
+ hostname: shortURL(s),
+ typedBonus: true,
+ })
+ );
+
+ Assert.equal(result.length, numVisible);
+ Assert.deepEqual(result, reference);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_getLinksWithDefaults_no_throw_on_no_links() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should not throw if NewTabUtils returns null");
+ gGetTopSitesStub.resolves(null);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ feed.getLinksWithDefaults();
+ Assert.ok(true, "getLinksWithDefaults did not throw");
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_get_more_on_request() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should get more if the user has asked for more");
+ let testLinks = new Array(4 * TOP_SITES_MAX_SITES_PER_ROW)
+ .fill(null)
+ .map((v, i) => ({
+ frecency: FAKE_FRECENCY,
+ url: `http://www.site${i}.com`,
+ }));
+ gGetTopSitesStub.resolves(testLinks);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const TEST_ROWS = 3;
+ feed.store.state.Prefs.values.topSitesRows = TEST_ROWS;
+
+ let result = await feed.getLinksWithDefaults();
+ Assert.equal(result.length, TEST_ROWS * TOP_SITES_MAX_SITES_PER_ROW);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_reuse_cache() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should reuse the cache on subsequent calls");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ gGetTopSitesStub.resetHistory();
+
+ await feed.getLinksWithDefaults();
+ await feed.getLinksWithDefaults();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getTopSites.calledOnce,
+ "getTopSites only called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_getLinksWithDefaults_ignore_cache_on_requesting_more() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should ignore the cache when requesting more");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ gGetTopSitesStub.resetHistory();
+
+ await feed.getLinksWithDefaults();
+ feed.store.state.Prefs.values.topSitesRows *= 3;
+ await feed.getLinksWithDefaults();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getTopSites.calledTwice,
+ "getTopSites called twice"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_getLinksWithDefaults_migrate_frecent_screenshot_data() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should migrate frecent screenshot data without getting screenshots again"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ gGetTopSitesStub.resetHistory();
+
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ await feed.getLinksWithDefaults();
+
+ let originalCallCount = Screenshots.getScreenshotForURL.callCount;
+ feed.frecentCache.expire();
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getTopSites.calledTwice,
+ "getTopSites called twice"
+ );
+ Assert.equal(
+ Screenshots.getScreenshotForURL.callCount,
+ originalCallCount,
+ "getScreenshotForURL was not called again."
+ );
+ Assert.equal(result[0].screenshot, FAKE_SCREENSHOT);
+
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_getLinksWithDefaults_migrate_pinned_favicon_data() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should migrate pinned favicon data without getting favicons again"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ gGetTopSitesStub.resetHistory();
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/" }]);
+
+ await feed.getLinksWithDefaults();
+
+ let originalCallCount =
+ NewTabUtils.activityStreamProvider._addFavicons.callCount;
+ feed.pinnedCache.expire();
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.equal(
+ NewTabUtils.activityStreamProvider._addFavicons.callCount,
+ originalCallCount,
+ "_addFavicons was not called again."
+ );
+ Assert.equal(result[0].favicon, FAKE_FAVICON);
+ Assert.equal(result[0].faviconSize, FAKE_FAVICON_SIZE);
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_getLinksWithDefaults_no_internal_properties() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should not expose internal link properties");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ let result = await feed.getLinksWithDefaults();
+
+ let internal = Object.keys(result[0]).filter(key => key.startsWith("__"));
+ Assert.equal(internal.join(""), "");
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_copy_frecent_screenshot() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should copy the screenshot of the frecent site if " +
+ "pinned site doesn't have customScreenshotURL"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const TEST_SCREENSHOT = "screenshot";
+
+ gGetTopSitesStub.resolves([
+ { url: "https://foo.com/", screenshot: TEST_SCREENSHOT },
+ ]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/" }]);
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.equal(result[0].screenshot, TEST_SCREENSHOT);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_no_copy_frecent_screenshot() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should not copy the frecent screenshot if " +
+ "customScreenshotURL is set"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ gGetTopSitesStub.resolves([
+ { url: "https://foo.com/", screenshot: "screenshot" },
+ ]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/", customScreenshotURL: "custom" }]);
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.equal(result[0].screenshot, undefined);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_persist_screenshot() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should keep the same screenshot if no frecent site is found"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const CUSTOM_SCREENSHOT = "custom";
+
+ gGetTopSitesStub.resolves([]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/", screenshot: CUSTOM_SCREENSHOT }]);
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.equal(result[0].screenshot, CUSTOM_SCREENSHOT);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(
+ async function test_getLinksWithDefaults_no_overwrite_pinned_screenshot() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should not overwrite pinned site screenshot");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const EXISTING_SCREENSHOT = "some-screenshot";
+
+ gGetTopSitesStub.resolves([{ url: "https://foo.com/", screenshot: "foo" }]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [
+ { url: "https://foo.com/", screenshot: EXISTING_SCREENSHOT },
+ ]);
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.equal(result[0].screenshot, EXISTING_SCREENSHOT);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_getLinksWithDefaults_no_searchTopSite_from_frecent() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should not set searchTopSite from frecent site");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ const EXISTING_SCREENSHOT = "some-screenshot";
+
+ gGetTopSitesStub.resolves([
+ {
+ url: "https://foo.com/",
+ searchTopSite: true,
+ screenshot: EXISTING_SCREENSHOT,
+ },
+ ]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/" }]);
+
+ let result = await feed.getLinksWithDefaults();
+
+ Assert.ok(!result[0].searchTopSite);
+ // But it should copy over other properties
+ Assert.equal(result[0].screenshot, EXISTING_SCREENSHOT);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_getLinksWithDefaults_concurrency_getTopSites() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults concurrent calls should call the backing data once"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ NewTabUtils.activityStreamLinks.getTopSites.resetHistory();
+
+ await Promise.all([feed.getLinksWithDefaults(), feed.getLinksWithDefaults()]);
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getTopSites.calledOnce,
+ "getTopSites only called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_getLinksWithDefaults_concurrency_getScreenshotForURL() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults concurrent calls should call the backing data once"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+
+ NewTabUtils.activityStreamLinks.getTopSites.resetHistory();
+ Screenshots.getScreenshotForURL.resetHistory();
+
+ await Promise.all([
+ feed.getLinksWithDefaults(),
+ feed.getLinksWithDefaults(),
+ ]);
+
+ Assert.ok(
+ NewTabUtils.activityStreamLinks.getTopSites.calledOnce,
+ "getTopSites only called once"
+ );
+
+ Assert.equal(
+ Screenshots.getScreenshotForURL.callCount,
+ FAKE_LINKS.length,
+ "getLinksWithDefaults concurrent calls should get screenshots once per link"
+ );
+
+ feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+
+ feed.refreshDefaults("https://foo.com");
+
+ sandbox.stub(feed, "_requestRichIcon");
+ await Promise.all([
+ feed.getLinksWithDefaults(),
+ feed.getLinksWithDefaults(),
+ ]);
+
+ Assert.equal(
+ feed.store.dispatch.callCount,
+ FAKE_LINKS.length,
+ "getLinksWithDefaults concurrent calls should dispatch once per link screenshot fetched"
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_getLinksWithDefaults_deduping_no_dedupe_pinned() {
+ let sandbox = sinon.createSandbox();
+ info("getLinksWithDefaults should not dedupe pinned sites");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults("https://foo.com");
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [
+ { url: "https://developer.mozilla.org/en-US/docs/Web" },
+ { url: "https://developer.mozilla.org/en-US/docs/Learn" },
+ ]);
+
+ let sites = await feed.getLinksWithDefaults();
+ Assert.equal(sites.length, 2 * TOP_SITES_MAX_SITES_PER_ROW);
+ Assert.equal(sites[0].url, NewTabUtils.pinnedLinks.links[0].url);
+ Assert.equal(sites[1].url, NewTabUtils.pinnedLinks.links[1].url);
+ Assert.equal(sites[0].hostname, sites[1].hostname);
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_prefer_pinned_sites() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should prefer pinned sites over links");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults();
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [
+ { url: "https://developer.mozilla.org/en-US/docs/Web" },
+ { url: "https://developer.mozilla.org/en-US/docs/Learn" },
+ ]);
+
+ const SECOND_TOP_SITE_URL = "https://www.mozilla.org/";
+
+ gGetTopSitesStub.resolves([
+ { frecency: FAKE_FRECENCY, url: "https://developer.mozilla.org/" },
+ { frecency: FAKE_FRECENCY, url: SECOND_TOP_SITE_URL },
+ ]);
+
+ let 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.equal(sites.length, 3);
+ Assert.equal(sites[0].url, NewTabUtils.pinnedLinks.links[0].url);
+ Assert.equal(sites[1].url, NewTabUtils.pinnedLinks.links[1].url);
+ Assert.equal(sites[2].url, SECOND_TOP_SITE_URL);
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_title_and_null() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should return sites that have a title");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults();
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://github.com/mozilla/activity-stream" }]);
+
+ let sites = await feed.getLinksWithDefaults();
+ for (let site of sites) {
+ Assert.ok(site.hostname);
+ }
+
+ info("getLinksWithDefaults should not throw for null entries");
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [null]);
+ await feed.getLinksWithDefaults();
+ Assert.ok(true, "getLinksWithDefaults didn't throw");
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_calls__fetchIcon() {
+ let sandbox = sinon.createSandbox();
+
+ info("getLinksWithDefaults should return sites that have a title");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults();
+
+ sandbox.spy(feed, "_fetchIcon");
+ let results = await feed.getLinksWithDefaults();
+ Assert.ok(results.length, "Got back some results");
+ Assert.equal(feed._fetchIcon.callCount, results.length);
+ for (let result of results) {
+ Assert.ok(feed._fetchIcon.calledWith(result));
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_calls__fetchScreenshot() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "getLinksWithDefaults should call _fetchScreenshot when customScreenshotURL is set"
+ );
+
+ gGetTopSitesStub.resolves([]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com", customScreenshotURL: "custom" }]);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults();
+
+ sandbox.stub(feed, "_fetchScreenshot");
+ await feed.getLinksWithDefaults();
+
+ Assert.ok(feed._fetchScreenshot.calledWith(sinon.match.object, "custom"));
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_getLinksWithDefaults_with_DiscoveryStream() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "getLinksWithDefaults should add a sponsored topsite from discoverystream to all the valid indices"
+ );
+
+ 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" }],
+ },
+ },
+ },
+ });
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.refreshDefaults();
+
+ 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");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_init() {
+ let sandbox = sinon.createSandbox();
+
+ sandbox.stub(NimbusFeatures.newtab, "onUpdate");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ sandbox.stub(feed, "refresh");
+ await feed.init();
+
+ info("TopSitesFeed.init should call refresh (broadcast: true)");
+ Assert.ok(feed.refresh.calledOnce, "refresh called once");
+ Assert.ok(
+ feed.refresh.calledWithExactly({
+ broadcast: true,
+ isStartup: true,
+ })
+ );
+
+ info("TopSitesFeed.init should initialise the storage");
+ Assert.ok(
+ feed.store.dbStorage.getDbTable.calledOnce,
+ "getDbTable called once"
+ );
+ Assert.ok(feed.store.dbStorage.getDbTable.calledWithExactly("sectionPrefs"));
+
+ info(
+ "TopSitesFeed.init should call onUpdate to set up Nimbus update listener"
+ );
+
+ Assert.ok(
+ NimbusFeatures.newtab.onUpdate.calledOnce,
+ "NimbusFeatures.newtab.onUpdate called once"
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_refresh() {
+ let sandbox = sinon.createSandbox();
+
+ sandbox.stub(NimbusFeatures.newtab, "onUpdate");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ info("TopSitesFeed.refresh should wait for tippytop to initialize");
+ feed._tippyTopProvider.initialized = false;
+ sandbox.stub(feed._tippyTopProvider, "init").resolves();
+
+ await feed.refresh();
+
+ Assert.ok(
+ feed._tippyTopProvider.init.calledOnce,
+ "feed._tippyTopProvider.init called once"
+ );
+
+ info(
+ "TopSitesFeed.refresh should not init the tippyTopProvider if already initialized"
+ );
+ feed._tippyTopProvider.initialized = true;
+ feed._tippyTopProvider.init.resetHistory();
+
+ await feed.refresh();
+
+ Assert.ok(
+ feed._tippyTopProvider.init.notCalled,
+ "tippyTopProvider not initted again"
+ );
+
+ info("TopSitesFeed.refresh should broadcast TOP_SITES_UPDATED");
+ feed.store.dispatch.resetHistory();
+ sandbox.stub(feed, "getLinksWithDefaults").resolves([]);
+
+ await feed.refresh({ broadcast: true });
+
+ Assert.ok(feed.store.dispatch.calledOnce, "dispatch called once");
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.BroadcastToContent({
+ type: at.TOP_SITES_UPDATED,
+ data: { links: [], pref: { collapsed: false } },
+ })
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_refresh_dispatch() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.refresh should dispatch an action with the links returned"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ await feed.refresh({ broadcast: true });
+ let reference = FAKE_LINKS.map(site =>
+ Object.assign({}, site, {
+ hostname: shortURL(site),
+ typedBonus: true,
+ })
+ );
+
+ Assert.ok(feed.store.dispatch.calledOnce, "Store.dispatch called once");
+ Assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.TOP_SITES_UPDATED
+ );
+ Assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.links, reference);
+
+ sandbox.restore();
+});
+
+add_task(async function test_refresh_empty_slots() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.refresh should handle empty slots in the resulting top sites array"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ gGetTopSitesStub.resolves([FAKE_LINKS[0]]);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [
+ null,
+ null,
+ FAKE_LINKS[1],
+ null,
+ null,
+ null,
+ null,
+ null,
+ FAKE_LINKS[2],
+ ]);
+
+ await feed.refresh({ broadcast: true });
+
+ Assert.ok(feed.store.dispatch.calledOnce, "Store.dispatch called once");
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_refresh_to_preloaded() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.refresh should dispatch AlsoToPreloaded when broadcast is false"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ gGetTopSitesStub.resolves([]);
+ await feed.refresh({ broadcast: false });
+
+ Assert.ok(feed.store.dispatch.calledOnce, "Store.dispatch called once");
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.AlsoToPreloaded({
+ type: at.TOP_SITES_UPDATED,
+ data: { links: [], pref: { collapsed: false } },
+ })
+ )
+ );
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ sandbox.restore();
+});
+
+add_task(async function test_refresh_init_storage() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.refresh should not init storage of it's already initialized"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ feed._storage.initialized = true;
+
+ await feed.refresh({ broadcast: false });
+
+ Assert.ok(feed._storage.init.notCalled, "feed._storage.init was not called.");
+ sandbox.restore();
+});
+
+add_task(async function test_refresh_handles_indexedDB_errors() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.refresh should dispatch AlsoToPreloaded when broadcast is false"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+
+ feed._storage.get.throws(new Error());
+
+ try {
+ await feed.refresh({ broadcast: false });
+ Assert.ok(true, "refresh should have succeeded");
+ } catch (e) {
+ Assert.ok(false, "Should not have thrown");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_updateSectionPrefs_on_UPDATE_SECTION_PREFS() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.onAction should call updateSectionPrefs on UPDATE_SECTION_PREFS"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "updateSectionPrefs");
+ feed.onAction({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: "topsites" },
+ });
+
+ Assert.ok(
+ feed.updateSectionPrefs.calledOnce,
+ "feed.updateSectionPrefs called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_updateSectionPrefs_dispatch_TOP_SITES_PREFS_UPDATED() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.updateSectionPrefs should dispatch TOP_SITES_PREFS_UPDATED"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.updateSectionPrefs({ collapsed: true });
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.BroadcastToContent({
+ type: at.TOP_SITES_PREFS_UPDATED,
+ data: { pref: { collapsed: true } },
+ })
+ )
+ );
+
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_allocatePositions() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.allocationPositions should allocate positions and dispatch"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let 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,
+ },
+ ],
+ },
+ ],
+ };
+
+ sandbox.stub(feed._contile, "sov").get(() => sov);
+
+ sandbox.stub(Sampling, "ratioSample");
+ Sampling.ratioSample.onCall(0).resolves(0);
+ Sampling.ratioSample.onCall(1).resolves(1);
+
+ await feed.allocatePositions();
+
+ Assert.ok(feed.store.dispatch.calledOnce, "feed.store.dispatch called once");
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.OnlyToMain({
+ type: at.SOV_UPDATED,
+ data: {
+ ready: true,
+ positions: [
+ { position: 1, assignedPartner: "amp" },
+ { position: 2, assignedPartner: "moz-sales" },
+ ],
+ },
+ })
+ )
+ );
+
+ Sampling.ratioSample.onCall(2).resolves(0);
+ Sampling.ratioSample.onCall(3).resolves(0);
+
+ await feed.allocatePositions();
+
+ Assert.ok(
+ feed.store.dispatch.calledTwice,
+ "feed.store.dispatch called twice"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.OnlyToMain({
+ type: at.SOV_UPDATED,
+ data: {
+ ready: true,
+ positions: [
+ { position: 1, assignedPartner: "amp" },
+ { position: 2, assignedPartner: "amp" },
+ ],
+ },
+ })
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_getScreenshotPreview() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.getScreenshotPreview should dispatch preview if request is succesful"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.getScreenshotPreview("custom", 1234);
+
+ Assert.ok(feed.store.dispatch.calledOnce);
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.OnlyToOneContent(
+ {
+ data: { preview: FAKE_SCREENSHOT, url: "custom" },
+ type: at.PREVIEW_RESPONSE,
+ },
+ 1234
+ )
+ )
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_getScreenshotPreview() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.getScreenshotPreview should return empty string if request fails"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ Screenshots.getScreenshotForURL.resolves(Promise.resolve(null));
+ await feed.getScreenshotPreview("custom", 1234);
+
+ Assert.ok(feed.store.dispatch.calledOnce);
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.OnlyToOneContent(
+ {
+ data: { preview: "", url: "custom" },
+ type: at.PREVIEW_RESPONSE,
+ },
+ 1234
+ )
+ )
+ );
+
+ Screenshots.getScreenshotForURL.resolves(FAKE_SCREENSHOT);
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_part_1() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.onAction should call getScreenshotPreview on PREVIEW_REQUEST"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "getScreenshotPreview");
+
+ feed.onAction({
+ type: at.PREVIEW_REQUEST,
+ data: { url: "foo" },
+ meta: { fromTarget: 1234 },
+ });
+
+ Assert.ok(
+ feed.getScreenshotPreview.calledOnce,
+ "feed.getScreenshotPreview called once"
+ );
+ Assert.ok(feed.getScreenshotPreview.calledWithExactly("foo", 1234));
+
+ info("TopSitesFeed.onAction should refresh on SYSTEM_TICK");
+ sandbox.stub(feed, "refresh");
+ feed.onAction({ type: at.SYSTEM_TICK });
+
+ Assert.ok(feed.refresh.calledOnce, "feed.refresh called once");
+ Assert.ok(feed.refresh.calledWithExactly({ broadcast: false }));
+
+ info(
+ "TopSitesFeed.onAction should call with correct parameters on TOP_SITES_PIN"
+ );
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+ sandbox.spy(feed, "pin");
+
+ let pinAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: { url: "foo.com" }, index: 7 },
+ };
+ feed.onAction(pinAction);
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledWithExactly(
+ pinAction.data.site,
+ pinAction.data.index
+ )
+ );
+ Assert.ok(
+ feed.pin.calledOnce,
+ "TopSitesFeed.onAction should call pin on TOP_SITES_PIN"
+ );
+
+ info(
+ "TopSitesFeed.onAction should unblock a previously blocked top site if " +
+ "we are now adding it manually via 'Add a Top Site' option"
+ );
+ sandbox.stub(NewTabUtils.blockedLinks, "unblock");
+ pinAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: { url: "foo.com" }, index: -1 },
+ };
+ feed.onAction(pinAction);
+ Assert.ok(
+ NewTabUtils.blockedLinks.unblock.calledWith({
+ url: pinAction.data.site.url,
+ })
+ );
+
+ info("TopSitesFeed.onAction should call insert on TOP_SITES_INSERT");
+ sandbox.stub(feed, "insert");
+ let addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.com" } },
+ };
+
+ feed.onAction(addAction);
+ Assert.ok(feed.insert.calledOnce, "TopSitesFeed.insert called once");
+
+ info(
+ "TopSitesFeed.onAction should call unpin with correct parameters " +
+ "on TOP_SITES_UNPIN"
+ );
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [
+ null,
+ null,
+ { url: "foo.com" },
+ null,
+ null,
+ null,
+ null,
+ null,
+ FAKE_LINKS[0],
+ ]);
+ sandbox.stub(NewTabUtils.pinnedLinks, "unpin");
+
+ let unpinAction = {
+ type: at.TOP_SITES_UNPIN,
+ data: { site: { url: "foo.com" } },
+ };
+ feed.onAction(unpinAction);
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.calledOnce,
+ "NewTabUtils.pinnedLinks.unpin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.unpin.calledWith(unpinAction.data.site));
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_part_2() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "TopSitesFeed.onAction should call refresh without a target if we clear " +
+ "history with PLACES_HISTORY_CLEARED"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "refresh");
+ feed.onAction({ type: at.PLACES_HISTORY_CLEARED });
+
+ Assert.ok(feed.refresh.calledOnce, "TopSitesFeed.refresh called once");
+ Assert.ok(feed.refresh.calledWithExactly({ broadcast: true }));
+
+ feed.refresh.resetHistory();
+
+ info(
+ "TopSitesFeed.onAction should call refresh without a target " +
+ "if we remove a Topsite from history"
+ );
+ feed.onAction({ type: at.PLACES_LINKS_DELETED });
+
+ Assert.ok(feed.refresh.calledOnce, "TopSitesFeed.refresh called once");
+ Assert.ok(feed.refresh.calledWithExactly({ broadcast: true }));
+
+ info("TopSitesFeed.onAction should call init on INIT action");
+ feed.onAction({ type: at.PLACES_LINKS_DELETED });
+ sandbox.stub(feed, "init");
+ feed.onAction({ type: at.INIT });
+ Assert.ok(feed.init.calledOnce, "TopSitesFeed.init called once");
+
+ info(
+ "TopSitesFeed.onAction should call refresh on PLACES_LINK_BLOCKED action"
+ );
+ feed.refresh.resetHistory();
+ await feed.onAction({ type: at.PLACES_LINK_BLOCKED });
+ Assert.ok(feed.refresh.calledOnce, "TopSitesFeed.refresh called once");
+ Assert.ok(feed.refresh.calledWithExactly({ broadcast: true }));
+
+ info(
+ "TopSitesFeed.onAction should call refresh on PLACES_LINKS_CHANGED action"
+ );
+ feed.refresh.resetHistory();
+ await feed.onAction({ type: at.PLACES_LINKS_CHANGED });
+ Assert.ok(feed.refresh.calledOnce, "TopSitesFeed.refresh called once");
+ Assert.ok(feed.refresh.calledWithExactly({ broadcast: false }));
+
+ info(
+ "TopSitesFeed.onAction should call pin with correct args on " +
+ "TOP_SITES_INSERT without an index specified"
+ );
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ let addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.bar", label: "foo" } },
+ };
+ feed.onAction(addAction);
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(addAction.data.site, 0));
+
+ info(
+ "TopSitesFeed.onAction should call pin with correct args on " +
+ "TOP_SITES_INSERT"
+ );
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ let dropAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.bar", label: "foo" }, index: 3 },
+ };
+ feed.onAction(dropAction);
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(dropAction.data.site, 3));
+
+ // feed.init needs to actually run in order to register the observers that'll
+ // be removed in the following UNINIT test, otherwise uninit will throw.
+ feed.init.restore();
+ feed.init();
+
+ info("TopSitesFeed.onAction should remove the expiration filter on UNINIT");
+ sandbox.stub(PageThumbs, "removeExpirationFilter");
+ feed.onAction({ type: "UNINIT" });
+ Assert.ok(
+ PageThumbs.removeExpirationFilter.calledOnce,
+ "PageThumbs.removeExpirationFilter called once"
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_onAction_part_3() {
+ let sandbox = sinon.createSandbox();
+
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ info(
+ "TopSitesFeed.onAction should call updatePinnedSearchShortcuts " +
+ "on UPDATE_PINNED_SEARCH_SHORTCUTS action"
+ );
+ sandbox.stub(feed, "updatePinnedSearchShortcuts");
+ let addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ await feed.onAction({
+ type: at.UPDATE_PINNED_SEARCH_SHORTCUTS,
+ data: { addedShortcuts },
+ });
+ Assert.ok(
+ feed.updatePinnedSearchShortcuts.calledOnce,
+ "TopSitesFeed.updatePinnedSearchShortcuts called once"
+ );
+
+ info(
+ "TopSitesFeed.onAction should refresh from Contile on " +
+ "SHOW_SPONSORED_PREF if Contile is enabled"
+ );
+ sandbox.spy(feed._contile, "refresh");
+ let prefChangeAction = {
+ type: at.PREF_CHANGED,
+ data: { name: SHOW_SPONSORED_PREF },
+ };
+ sandbox.stub(NimbusFeatures.newtab, "getVariable").returns(true);
+ feed.onAction(prefChangeAction);
+
+ Assert.ok(
+ feed._contile.refresh.calledOnce,
+ "TopSitesFeed._contile.refresh called once"
+ );
+
+ info(
+ "TopSitesFeed.onAction should not refresh from Contile on " +
+ "SHOW_SPONSORED_PREF if Contile is disabled"
+ );
+ NimbusFeatures.newtab.getVariable.returns(false);
+ feed._contile.refresh.resetHistory();
+ feed.onAction(prefChangeAction);
+
+ Assert.ok(
+ !feed._contile.refresh.calledOnce,
+ "TopSitesFeed._contile.refresh never called"
+ );
+
+ info(
+ "TopSitesFeed.onAction 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,
+ Math.round(Date.now() / 1000)
+ );
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF, 15 * 60);
+ prefChangeAction = {
+ type: at.PREF_CHANGED,
+ data: { name: SHOW_SPONSORED_PREF, value: false },
+ };
+ NimbusFeatures.newtab.getVariable.returns(true);
+ feed._contile.refresh.resetHistory();
+
+ feed.onAction(prefChangeAction);
+ Assert.ok(!Services.prefs.prefHasUserValue(CONTILE_CACHE_PREF));
+ Assert.ok(!Services.prefs.prefHasUserValue(CONTILE_CACHE_LAST_FETCH_PREF));
+ Assert.ok(
+ !Services.prefs.prefHasUserValue(CONTILE_CACHE_VALID_FOR_SECONDS_PREF)
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_insert_part_1() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info(
+ "TopSitesFeed.insert should pin site in first slot of empty pinned list"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ Screenshots.getScreenshotForURL.resolves(Promise.resolve(null));
+ await feed.getScreenshotPreview("custom", 1234);
+
+ Assert.ok(feed.store.dispatch.calledOnce);
+ Assert.ok(
+ feed.store.dispatch.calledWithExactly(
+ ac.OnlyToOneContent(
+ {
+ data: { preview: "", url: "custom" },
+ type: at.PREVIEW_RESPONSE,
+ },
+ 1234
+ )
+ )
+ );
+
+ Screenshots.getScreenshotForURL.resolves(FAKE_SCREENSHOT);
+ }
+
+ {
+ info(
+ "TopSitesFeed.insert should pin site in first slot of pinned list with " +
+ "empty first slot"
+ );
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, { url: "example.com" }]);
+ let site = { url: "foo.bar", label: "foo" };
+ await feed.insert({ data: { site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.insert should move a pinned site in first slot to the " +
+ "next slot: part 1"
+ );
+ let site1 = { url: "example.com" };
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [site1]);
+ let feed = getTopSitesFeedForTest(sandbox);
+ let site = { url: "foo.bar", label: "foo" };
+
+ await feed.insert({ data: { site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site1, 1));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.insert should move a pinned site in first slot to the " +
+ "next slot: part 2"
+ );
+ let site1 = { url: "example.com" };
+ let site2 = { url: "example.org" };
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [site1, null, site2]);
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.insert({ data: { site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site1, 1));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_insert_part_2() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info(
+ "TopSitesFeed.insert should unpin the last site if all slots are " +
+ "already pinned"
+ );
+ let site1 = { url: "example.com" };
+ let site2 = { url: "example.org" };
+ let site3 = { url: "example.net" };
+ let site4 = { url: "example.biz" };
+ let site5 = { url: "example.info" };
+ let site6 = { url: "example.news" };
+ let site7 = { url: "example.lol" };
+ let site8 = { url: "example.golf" };
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [site1, site2, site3, site4, site5, site6, site7, site8]);
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values.topSitesRows = 1;
+ let site = { url: "foo.bar", label: "foo" };
+ await feed.insert({ data: { site } });
+ Assert.equal(
+ NewTabUtils.pinnedLinks.pin.callCount,
+ 8,
+ "NewTabUtils.pinnedLinks.pin called 8 times"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site1, 1));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site2, 2));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site3, 3));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site4, 4));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site5, 5));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site6, 6));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site7, 7));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info("TopSitesFeed.insert should trigger refresh on TOP_SITES_INSERT");
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "refresh");
+ let addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.com" } },
+ };
+
+ await feed.insert(addAction);
+
+ Assert.ok(feed.refresh.calledOnce, "feed.refresh called once");
+ }
+
+ {
+ info("TopSitesFeed.insert should correctly handle different index values");
+ let index = -1;
+ let site = { url: "foo.bar", label: "foo" };
+ let action = { data: { index, site } };
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ await feed.insert(action);
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+
+ index = undefined;
+ await feed.insert(action);
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 0));
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_insert_part_3() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info("TopSitesFeed.insert should pin site in specified slot that is free");
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, { url: "example.com" }]);
+
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ await feed.insert({ data: { index: 2, site, draggedFromIndex: 0 } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 2));
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.insert should move a pinned site in specified slot " +
+ "to the next slot"
+ );
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, null, { url: "example.com" }]);
+
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ await feed.insert({ data: { index: 2, site, draggedFromIndex: 3 } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 2));
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledWith({ url: "example.com" }, 3)
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.insert should move pinned sites in the direction " +
+ "of the dragged site"
+ );
+
+ let site1 = { url: "foo.bar", label: "foo" };
+ let site2 = { url: "example.com", label: "example" };
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, null, site2]);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ await feed.insert({ data: { index: 2, site: site1, draggedFromIndex: 0 } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site1, 2));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site2, 1));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+
+ await feed.insert({ data: { index: 2, site: site1, draggedFromIndex: 5 } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site1, 2));
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site2, 3));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info("TopSitesFeed.insert should not insert past the visible top sites");
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ let site1 = { url: "foo.bar", label: "foo" };
+ await feed.insert({
+ data: { index: 42, site: site1, draggedFromIndex: 0 },
+ });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.notCalled,
+ "NewTabUtils.pinnedLinks.pin wasn't called"
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_pin_part_1() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info(
+ "TopSitesFeed.pin should pin site in specified slot empty pinned " +
+ "list"
+ );
+ let site = {
+ url: "foo.bar",
+ label: "foo",
+ customScreenshotURL: "screenshot",
+ };
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.pin({ data: { index: 2, site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 2));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should lookup the link object to update the custom " +
+ "screenshot"
+ );
+ let site = {
+ url: "foo.bar",
+ label: "foo",
+ customScreenshotURL: "screenshot",
+ };
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.spy(feed.pinnedCache, "request");
+ await feed.pin({ data: { index: 2, site } });
+
+ Assert.ok(
+ feed.pinnedCache.request.calledOnce,
+ "feed.pinnedCache.request called once"
+ );
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should lookup the link object to update the custom " +
+ "screenshot when the custom screenshot is initially null"
+ );
+ let site = {
+ url: "foo.bar",
+ label: "foo",
+ customScreenshotURL: null,
+ };
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.spy(feed.pinnedCache, "request");
+ await feed.pin({ data: { index: 2, site } });
+
+ Assert.ok(
+ feed.pinnedCache.request.calledOnce,
+ "feed.pinnedCache.request called once"
+ );
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should not do a link object lookup if custom " +
+ "screenshot field is not set"
+ );
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.spy(feed.pinnedCache, "request");
+ await feed.pin({ data: { index: 2, site } });
+
+ Assert.ok(
+ !feed.pinnedCache.request.called,
+ "feed.pinnedCache.request never called"
+ );
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should pin site in specified slot of pinned " +
+ "list that is free"
+ );
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, { url: "example.com" }]);
+
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.pin({ data: { index: 2, site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 2));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_pin_part_2() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info("TopSitesFeed.pin should save the searchTopSite attribute if set");
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, { url: "example.com" }]);
+
+ let site = { url: "foo.bar", label: "foo", searchTopSite: true };
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.pin({ data: { index: 2, site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.firstCall.args[0].searchTopSite);
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should NOT move a pinned site in specified " +
+ "slot to the next slot"
+ );
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [null, null, { url: "example.com" }]);
+
+ let site = { url: "foo.bar", label: "foo" };
+ let feed = getTopSitesFeedForTest(sandbox);
+ await feed.pin({ data: { index: 2, site } });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(NewTabUtils.pinnedLinks.pin.calledWith(site, 2));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.pin should properly update LinksCache object " +
+ "properties between migrations"
+ );
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "https://foo.com/" }]);
+
+ let feed = getTopSitesFeedForTest(sandbox);
+ 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.equal(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.equal(pinnedLinks[0].screenshot, "bar");
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_pin_part_3() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+
+ {
+ info("TopSitesFeed.pin should call insert if index < 0");
+ let site = { url: "foo.bar", label: "foo" };
+ let action = { data: { index: -1, site } };
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.spy(feed, "insert");
+ await feed.pin(action);
+
+ Assert.ok(feed.insert.calledOnce, "feed.insert called once");
+ Assert.ok(feed.insert.calledWithExactly(action));
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info("TopSitesFeed.pin should not call insert if index == 0");
+ let site = { url: "foo.bar", label: "foo" };
+ let action = { data: { index: 0, site } };
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.spy(feed, "insert");
+ await feed.pin(action);
+
+ Assert.ok(!feed.insert.called, "feed.insert not called");
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ {
+ info("TopSitesFeed.pin should trigger refresh on TOP_SITES_PIN");
+ let feed = getTopSitesFeedForTest(sandbox);
+ sandbox.stub(feed, "refresh");
+ let pinExistingAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: FAKE_LINKS[4], index: 4 },
+ };
+
+ await feed.pin(pinExistingAction);
+
+ Assert.ok(feed.refresh.calledOnce, "feed.refresh called once");
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_integration() {
+ let sandbox = sinon.createSandbox();
+
+ info("Test adding a pinned site and removing it with actions");
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let resolvers = [];
+ feed.store.dispatch = sandbox.stub().callsFake(() => {
+ resolvers.shift()();
+ });
+ feed._startedUp = true;
+ sandbox.stub(feed, "_fetchScreenshot");
+
+ let forDispatch = action =>
+ new Promise(resolve => {
+ resolvers.push(resolve);
+ feed.onAction(action);
+ });
+
+ feed._requestRichIcon = sandbox.stub();
+ let url = "https://pin.me";
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin").callsFake(link => {
+ NewTabUtils.pinnedLinks.links.push(link);
+ });
+
+ await forDispatch({ type: at.TOP_SITES_INSERT, data: { site: { url } } });
+ NewTabUtils.pinnedLinks.links.pop();
+ await forDispatch({ type: at.PLACES_LINK_BLOCKED });
+
+ Assert.ok(
+ feed.store.dispatch.calledTwice,
+ "feed.store.dispatch called twice"
+ );
+ 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
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_improvesearch_noDefaultSearchTile_experiment() {
+ let sandbox = sinon.createSandbox();
+ const NO_DEFAULT_SEARCH_TILE_PREF = "improvesearch.noDefaultSearchTile";
+
+ sandbox.stub(SearchService.prototype, "getDefault").resolves({
+ identifier: "google",
+ searchForm: "google.com",
+ });
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should filter out alexa top 5 " +
+ "search from the default sites"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+ let top5Test = [
+ "https://google.com",
+ "https://search.yahoo.com",
+ "https://yahoo.com",
+ "https://bing.com",
+ "https://ask.com",
+ "https://duckduckgo.com",
+ ];
+
+ gGetTopSitesStub.resolves([
+ { url: "https://amazon.com" },
+ ...top5Test.map(url => ({ url })),
+ ]);
+
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ Assert.ok(
+ urlsReturned.includes("https://amazon.com"),
+ "amazon included in default links"
+ );
+ top5Test.forEach(url =>
+ Assert.ok(!urlsReturned.includes(url), `Should not include ${url}`)
+ );
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should not filter out alexa, default " +
+ "search from the query results if the experiment pref is off"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = false;
+
+ gGetTopSitesStub.resolves([
+ { url: "https://google.com" },
+ { url: "https://foo.com" },
+ { url: "https://duckduckgo" },
+ ]);
+ let urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+
+ Assert.ok(urlsReturned.includes("https://google.com"));
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should filter out the current " +
+ "default search from the default sites"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+
+ sandbox.stub(feed, "_currentSearchHostname").get(() => "amazon");
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "google.com,amazon.com" },
+ });
+ gGetTopSitesStub.resolves([{ url: "https://foo.com" }]);
+
+ let urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ Assert.ok(!urlsReturned.includes("https://amazon.com"));
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should not filter out current " +
+ "default search from pinned sites even if it matches the current " +
+ "default search"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+
+ sandbox
+ .stub(NewTabUtils.pinnedLinks, "links")
+ .get(() => [{ url: "google.com" }]);
+ gGetTopSitesStub.resolves([{ url: "https://foo.com" }]);
+
+ let urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ Assert.ok(urlsReturned.includes("google.com"));
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ sandbox.restore();
+});
+
+add_task(
+ async function test_improvesearch_noDefaultSearchTile_experiment_part_2() {
+ let sandbox = sinon.createSandbox();
+ const NO_DEFAULT_SEARCH_TILE_PREF = "improvesearch.noDefaultSearchTile";
+
+ sandbox.stub(SearchService.prototype, "getDefault").resolves({
+ identifier: "google",
+ searchForm: "google.com",
+ });
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should call refresh and set " +
+ "._currentSearchHostname to the new engine hostname when the " +
+ "default search engine has been set"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+ sandbox.stub(feed, "refresh");
+
+ feed.observe(null, "browser-search-engine-modified", "engine-default");
+ Assert.equal(feed._currentSearchHostname, "duckduckgo");
+ Assert.ok(feed.refresh.calledOnce, "feed.refresh called once");
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info(
+ "TopSitesFeed.getLinksWithDefaults should call refresh when the " +
+ "experiment pref has changed"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+ sandbox.stub(feed, "refresh");
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: NO_DEFAULT_SEARCH_TILE_PREF, value: true },
+ });
+ Assert.ok(feed.refresh.calledOnce, "feed.refresh was called once");
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: NO_DEFAULT_SEARCH_TILE_PREF, value: false },
+ });
+ Assert.ok(feed.refresh.calledTwice, "feed.refresh was called twice");
+
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ sandbox.restore();
+ }
+);
+
+// eslint-disable-next-line max-statements
+add_task(async function test_improvesearch_topSitesSearchShortcuts() {
+ let sandbox = sinon.createSandbox();
+ let searchEngines = [{ aliases: ["@google"] }, { aliases: ["@amazon"] }];
+ sandbox
+ .stub(SearchService.prototype, "getAppProvidedEngines")
+ .resolves(searchEngines);
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin").callsFake((site, index) => {
+ NewTabUtils.pinnedLinks.links[index] = site;
+ });
+
+ let prepFeed = feed => {
+ 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] = "";
+ return feed;
+ };
+
+ {
+ info(
+ "TopSitesFeed should updateCustomSearchShortcuts when experiment " +
+ "pref is turned on"
+ );
+ let feed = prepFeed(getTopSitesFeedForTest(sandbox));
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT_PREF] = false;
+ feed.updateCustomSearchShortcuts = sandbox.spy();
+
+ // turn the experiment on
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: SEARCH_SHORTCUTS_EXPERIMENT_PREF, value: true },
+ });
+
+ Assert.ok(
+ feed.updateCustomSearchShortcuts.calledOnce,
+ "feed.updateCustomSearchShortcuts called once"
+ );
+ }
+
+ {
+ info(
+ "TopSitesFeed should filter out default top sites that match a " +
+ "hostname of a search shortcut if previously blocked"
+ );
+ let feed = prepFeed(getTopSitesFeedForTest(sandbox));
+ feed.refreshDefaults("https://amazon.ca");
+ sandbox
+ .stub(NewTabUtils.blockedLinks, "links")
+ .value([{ url: "https://amazon.com" }]);
+ sandbox.stub(NewTabUtils.blockedLinks, "isBlocked").callsFake(site => {
+ return NewTabUtils.blockedLinks.links[0].url === site.url;
+ });
+
+ let urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ Assert.ok(!urlsReturned.includes("https://amazon.ca"));
+ }
+
+ {
+ info("TopSitesFeed should update frecent search topsite icon");
+ let feed = prepFeed(getTopSitesFeedForTest(sandbox));
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ gGetTopSitesStub.resolves([{ url: "https://google.com" }]);
+
+ let urlsReturned = await feed.getLinksWithDefaults();
+
+ let defaultSearchTopsite = urlsReturned.find(
+ s => s.url === "https://google.com"
+ );
+ Assert.ok(defaultSearchTopsite.searchTopSite);
+ Assert.equal(defaultSearchTopsite.tippyTopIcon, "icon.png");
+ Assert.equal(defaultSearchTopsite.backgroundColor, "#fff");
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info("TopSitesFeed should update default search topsite icon");
+ let feed = prepFeed(getTopSitesFeedForTest(sandbox));
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ gGetTopSitesStub.resolves([{ url: "https://foo.com" }]);
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "google.com,amazon.com" },
+ });
+
+ let urlsReturned = await feed.getLinksWithDefaults();
+
+ let defaultSearchTopsite = urlsReturned.find(
+ s => s.url === "https://amazon.com"
+ );
+ Assert.ok(defaultSearchTopsite.searchTopSite);
+ Assert.equal(defaultSearchTopsite.tippyTopIcon, "icon.png");
+ Assert.equal(defaultSearchTopsite.backgroundColor, "#fff");
+ gGetTopSitesStub.resolves(FAKE_LINKS);
+ }
+
+ {
+ info(
+ "TopSitesFeed should dispatch UPDATE_SEARCH_SHORTCUTS on " +
+ "updateCustomSearchShortcuts"
+ );
+ let feed = prepFeed(getTopSitesFeedForTest(sandbox));
+ feed.store.state.Prefs.values["improvesearch.noDefaultSearchTile"] = true;
+ await feed.updateCustomSearchShortcuts();
+ Assert.ok(
+ feed.store.dispatch.calledOnce,
+ "feed.store.dispatch called once"
+ );
+ Assert.ok(
+ feed.store.dispatch.calledWith({
+ data: {
+ searchShortcuts: [
+ {
+ keyword: "@google",
+ shortURL: "google",
+ url: "https://google.com",
+ backgroundColor: undefined,
+ smallFavicon:
+ "chrome://activity-stream/content/data/content/tippytop/favicons/google-com.ico",
+ tippyTopIcon:
+ "chrome://activity-stream/content/data/content/tippytop/images/google-com@2x.png",
+ },
+ {
+ keyword: "@amazon",
+ shortURL: "amazon",
+ url: "https://amazon.com",
+ backgroundColor: undefined,
+ smallFavicon:
+ "chrome://activity-stream/content/data/content/tippytop/favicons/amazon.ico",
+ tippyTopIcon:
+ "chrome://activity-stream/content/data/content/tippytop/images/amazon@2x.png",
+ },
+ ],
+ },
+ meta: {
+ from: "ActivityStream:Main",
+ to: "ActivityStream:Content",
+ isStartup: false,
+ },
+ type: "UPDATE_SEARCH_SHORTCUTS",
+ })
+ );
+ }
+
+ sandbox.restore();
+});
+
+add_task(async function test_updatePinnedSearchShortcuts() {
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(NewTabUtils.pinnedLinks, "pin");
+ sandbox.stub(NewTabUtils.pinnedLinks, "unpin");
+
+ {
+ info(
+ "TopSitesFeed.updatePinnedSearchShortcuts should unpin a " +
+ "shortcut in deletedShortcuts"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let deletedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ let addedShortcuts = [];
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [
+ null,
+ null,
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ]);
+
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.notCalled,
+ "NewTabUtils.pinnedLinks.pin not called"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.calledOnce,
+ "NewTabUtils.pinnedLinks.unpin called once"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.calledWith({
+ url: "https://google.com",
+ })
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ NewTabUtils.pinnedLinks.unpin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.updatePinnedSearchShortcuts should pin a shortcut " +
+ "in addedShortcuts"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ let deletedShortcuts = [];
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [
+ null,
+ null,
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ]);
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.notCalled,
+ "NewTabUtils.pinnedLinks.unpin not called"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledOnce,
+ "NewTabUtils.pinnedLinks.pin called once"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledWith(
+ {
+ label: "google",
+ searchTopSite: true,
+ searchVendor: "google",
+ url: "https://google.com",
+ },
+ 0
+ )
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ NewTabUtils.pinnedLinks.unpin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.updatePinnedSearchShortcuts should pin and unpin " +
+ "in the same action"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ {
+ url: "https://ebay.com",
+ searchVendor: "ebay",
+ label: "ebay",
+ searchTopSite: true,
+ },
+ ];
+ let deletedShortcuts = [
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ];
+
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => [
+ { url: "https://foo.com" },
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ]);
+
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.calledOnce,
+ "NewTabUtils.pinnedLinks.unpin called once"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledTwice,
+ "NewTabUtils.pinnedLinks.pin called twice"
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ NewTabUtils.pinnedLinks.unpin.resetHistory();
+ }
+
+ {
+ info(
+ "TopSitesFeed.updatePinnedSearchShortcuts should pin a shortcut in " +
+ "addedShortcuts even if pinnedLinks is full"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ let addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ let deletedShortcuts = [];
+ sandbox.stub(NewTabUtils.pinnedLinks, "links").get(() => FAKE_LINKS);
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+
+ Assert.ok(
+ NewTabUtils.pinnedLinks.unpin.notCalled,
+ "NewTabUtils.pinnedLinks.unpin not called"
+ );
+ Assert.ok(
+ NewTabUtils.pinnedLinks.pin.calledWith(
+ { label: "google", searchTopSite: true, url: "https://google.com" },
+ 0
+ ),
+ "NewTabUtils.pinnedLinks.unpin not called"
+ );
+
+ NewTabUtils.pinnedLinks.pin.resetHistory();
+ NewTabUtils.pinnedLinks.unpin.resetHistory();
+ }
+
+ sandbox.restore();
+});
+
+// eslint-disable-next-line max-statements
+add_task(async function test_ContileIntegration() {
+ let sandbox = sinon.createSandbox();
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+ sandbox.stub(NimbusFeatures.newtab, "getVariable").returns(true);
+
+ let prepFeed = feed => {
+ feed.store.state.Prefs.values[SHOW_SPONSORED_PREF] = true;
+ let fetchStub = sandbox.stub(feed, "fetch");
+ return { feed, fetchStub };
+ };
+
+ {
+ info("TopSitesFeed._fetchSites should fetch sites from Contile");
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ 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",
+ },
+ ],
+ }),
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+ }
+
+ {
+ info("TopSitesFeed._fetchSites should call allocatePositions");
+ let { feed } = prepFeed(getTopSitesFeedForTest(sandbox));
+ sandbox.stub(feed, "allocatePositions").resolves();
+ await feed._contile.refresh();
+
+ Assert.ok(
+ feed.allocatePositions.calledOnce,
+ "feed.allocatePositions called once"
+ );
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should fetch SOV (Share-of-Voice) " +
+ "settings from Contile"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ let 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",
+ },
+ ],
+ }),
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(fetched);
+ Assert.deepEqual(feed._contile.sov, sov);
+ Assert.equal(feed._contile.sites.length, 2);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should not fetch from Contile if " +
+ "it's not enabled"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ NimbusFeatures.newtab.getVariable.reset();
+ NimbusFeatures.newtab.getVariable.returns(false);
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(fetchStub.notCalled, "TopSitesFeed.fetch was not called");
+ Assert.ok(!fetched);
+ Assert.equal(feed._contile.sites.length, 0);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should still return two tiles when Contile " +
+ "provides more than 2 tiles and filtering results in more than 2 tiles"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ NimbusFeatures.newtab.getVariable.reset();
+ NimbusFeatures.newtab.getVariable.onCall(0).returns(true);
+ NimbusFeatures.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",
+ },
+ ],
+ }),
+ });
+
+ let 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");
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should still return two tiles with " +
+ "replacement if the Nimbus variable was unset"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ NimbusFeatures.newtab.getVariable.reset();
+ NimbusFeatures.newtab.getVariable.onCall(0).returns(true);
+ NimbusFeatures.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",
+ },
+ ],
+ }),
+ });
+
+ let 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");
+ }
+
+ {
+ info("TopSitesFeed._fetchSites should filter the blocked sponsors");
+ NimbusFeatures.newtab.getVariable.returns(true);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ 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",
+ },
+ ],
+ }),
+ });
+
+ let 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");
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should return false when Contile returns " +
+ "with error status and no values are stored in cache prefs"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, "[]");
+ Services.prefs.setIntPref(CONTILE_CACHE_LAST_FETCH_PREF, 0);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(!fetched);
+ Assert.ok(!feed._contile.sites.length);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should return false when Contile " +
+ "returns with error status and cached tiles are expried"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, "[]");
+ const THIRTY_MINUTES_AGO_IN_SECONDS =
+ Math.round(Date.now() / 1000) - 60 * 30;
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ THIRTY_MINUTES_AGO_IN_SECONDS
+ );
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF, 60 * 15);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(!fetched);
+ Assert.ok(!feed._contile.sites.length);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should handle invalid payload " +
+ "properly from Contile"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ unknown: [],
+ }),
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(!fetched);
+ Assert.ok(!feed._contile.sites.length);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should handle empty payload properly " +
+ "from Contile"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ headers: new Map([
+ ["cache-control", "private, max-age=859, stale-if-error=10463"],
+ ]),
+ json: () =>
+ Promise.resolve({
+ tiles: [],
+ }),
+ });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(fetched);
+ Assert.ok(!feed._contile.sites.length);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should handle no content properly " +
+ "from Contile"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ fetchStub.resolves({ ok: true, status: 204 });
+
+ let fetched = await feed._contile._fetchSites();
+
+ Assert.ok(!fetched);
+ Assert.ok(!feed._contile.sites.length);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should set Caching Prefs after " +
+ "a successful request"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ let 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,
+ }),
+ });
+
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(
+ Services.prefs.getStringPref(CONTILE_CACHE_PREF),
+ JSON.stringify(tiles)
+ );
+ Assert.equal(
+ Services.prefs.getIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF),
+ 11322
+ );
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should return cached valid tiles " +
+ "when Contile returns error status"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ let 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",
+ },
+ ];
+
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, JSON.stringify(tiles));
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF, 60 * 15);
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ Math.round(Date.now() / 1000)
+ );
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ let 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");
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should not be successful when contile " +
+ "returns an error and no valid tiles are cached"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, "[]");
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF, 0);
+ Services.prefs.setIntPref(CONTILE_CACHE_LAST_FETCH_PREF, 0);
+
+ fetchStub.resolves({
+ status: 500,
+ });
+
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(!fetched);
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should return cached valid tiles " +
+ "filtering blocked tiles when Contile returns error status"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ let 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",
+ },
+ ];
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, JSON.stringify(tiles));
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_SECONDS_PREF, 60 * 15);
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ Math.round(Date.now() / 1000)
+ );
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ let 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");
+ }
+
+ {
+ info(
+ "TopSitesFeed._fetchSites should still return 3 tiles when nimbus " +
+ "variable overrides max num of sponsored contile tiles"
+ );
+ NimbusFeatures.newtab.getVariable.returns(true);
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox));
+
+ sandbox.stub(NimbusFeatures.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",
+ },
+ ],
+ }),
+ });
+
+ let 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");
+ }
+
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_TopSitesFeed_glean.js b/browser/components/newtab/test/xpcshell/test_TopSitesFeed_glean.js
new file mode 100644
index 0000000000..5d13df0eb0
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_TopSitesFeed_glean.js
@@ -0,0 +1,2023 @@
+/* Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+ChromeUtils.defineESModuleGetters(this, {
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+ sinon: "resource://testing-common/Sinon.sys.mjs",
+ SearchService: "resource://gre/modules/SearchService.sys.mjs",
+ TopSitesFeed: "resource://activity-stream/lib/TopSitesFeed.sys.mjs",
+});
+
+const SHOW_SPONSORED_PREF = "showSponsoredTopSites";
+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";
+const NIMBUS_VARIABLE_MAX_SPONSORED = "topSitesMaxSponsored";
+const NIMBUS_VARIABLE_CONTILE_POSITIONS = "contileTopsitesPositions";
+const NIMBUS_VARIABLE_CONTILE_ENABLED = "topSitesContileEnabled";
+const NIMBUS_VARIABLE_CONTILE_MAX_NUM_SPONSORED = "topSitesContileMaxSponsored";
+
+let contileTile1 = {
+ id: 74357,
+ name: "Brand1",
+ url: "https://www.brand1.com",
+ click_url: "https://clickurl.com",
+ image_url: "https://contile-images.jpg",
+ image_size: 200,
+ impression_url: "https://impression_url.com",
+};
+let contileTile2 = {
+ id: 74925,
+ name: "Brand2",
+ url: "https://www.brand2.com",
+ click_url: "https://click_url.com",
+ image_url: "https://contile-images.jpg",
+ image_size: 200,
+ impression_url: "https://impression_url.com",
+};
+let contileTile3 = {
+ id: 75001,
+ name: "Brand3",
+ url: "https://www.brand3.com",
+ click_url: "https://click_url.com",
+ image_url: "https://contile-images.jpg",
+ image_size: 200,
+ impression_url: "https://impression_url.com",
+};
+let mozSalesTile = [
+ {
+ label: "MozSales Title",
+ title: "MozSales Title",
+ url: "https://mozsale.net",
+ sponsored_position: 1,
+ partner: "moz-sales",
+ },
+];
+
+function getTopSitesFeedForTest(sandbox) {
+ let feed = new TopSitesFeed();
+ const storage = {
+ init: sandbox.stub().resolves(),
+ get: sandbox.stub().resolves(),
+ set: sandbox.stub().resolves(),
+ };
+
+ 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) },
+ };
+
+ return feed;
+}
+
+function prepFeed(feed, sandbox) {
+ feed.store.state.Prefs.values[SHOW_SPONSORED_PREF] = true;
+ let fetchStub = sandbox.stub(feed, "fetch");
+ return { feed, fetchStub };
+}
+
+function setNimbusVariablesForNumTiles(nimbusPocketStub, numTiles) {
+ nimbusPocketStub.withArgs(NIMBUS_VARIABLE_MAX_SPONSORED).returns(numTiles);
+ nimbusPocketStub
+ .withArgs(NIMBUS_VARIABLE_CONTILE_MAX_NUM_SPONSORED)
+ .returns(numTiles);
+ // when setting num tiles to > 2 need to set the positions or the > 2 has no effect.
+ // can be defaulted to undefined
+ let positionsArray = Array.from(
+ { length: numTiles },
+ (value, index) => index
+ );
+ nimbusPocketStub
+ .withArgs(NIMBUS_VARIABLE_CONTILE_POSITIONS)
+ .returns(positionsArray.toString());
+}
+
+add_setup(async () => {
+ do_get_profile();
+ Services.fog.initializeFOG();
+
+ let sandbox = sinon.createSandbox();
+ sandbox.stub(SearchService.prototype, "init").resolves();
+
+ const nimbusStub = sandbox.stub(NimbusFeatures.newtab, "getVariable");
+ nimbusStub.withArgs(NIMBUS_VARIABLE_CONTILE_ENABLED).returns(true);
+
+ sandbox.spy(Glean.topsites.sponsoredTilesConfigured, "set");
+ sandbox.spy(Glean.topsites.sponsoredTilesReceived, "set");
+
+ // Temporarily setting isInAutomation to false.
+ // If Cu.isInAutomation is true then the check for Cu.isInAutomation in
+ // ContileIntegration._readDefaults passes, bypassing Contile, resulting in
+ // not being able use stubbed values.
+ if (Cu.isInAutomation) {
+ Services.prefs.setBoolPref(
+ "security.turn_off_all_security_so_that_viruses_can_take_over_this_computer",
+ false
+ );
+
+ if (Cu.isInAutomation) {
+ // This condition is unexpected, because it is enforced at:
+ // https://searchfox.org/mozilla-central/rev/ea65de7c/js/xpconnect/src/xpcpublic.h#753-759
+ throw new Error("Failed to set isInAutomation to false");
+ }
+ }
+ registerCleanupFunction(() => {
+ if (!Cu.isInAutomation) {
+ Services.prefs.setBoolPref(
+ "security.turn_off_all_security_so_that_viruses_can_take_over_this_computer",
+ true
+ );
+
+ if (!Cu.isInAutomation) {
+ // This condition is unexpected, because it is enforced at:
+ // https://searchfox.org/mozilla-central/rev/ea65de7c/js/xpconnect/src/xpcpublic.h#753-759
+ throw new Error("Failed to set isInAutomation to true");
+ }
+ }
+
+ sandbox.restore();
+ });
+});
+
+add_task(async function test_set_contile_tile_to_oversold() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_moz_sale_tile_to_oversold() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "determineFilteredTilesAndSetToOversold should set moz-sale tile to oversold when_contile tiles are displayed"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2]);
+ feed._telemetryUtility.setTiles(mozSalesTile);
+
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "mozsales title",
+ provider: "moz-sales",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_contile_tile_to_oversold() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "determineFilteredTilesAndSetToOversold should set contile tile to oversold when moz-sale tile is displayed"
+ );
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2]);
+ feed._telemetryUtility.setTiles(mozSalesTile);
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ label: "MozSales Title",
+ title: "MozSales Title",
+ url: "https://mozsale.net",
+ sponsored_position: 2,
+ partner: "moz-sales",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ {
+ advertiser: "mozsales title",
+ provider: "moz-sales",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_contile_tiles_to_dismissed() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToDismissed(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_all_contile_tiles_to_dismissed() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ let mergedTiles = [];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToDismissed(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_moz_sales_tiles_to_dismissed() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2]);
+ feed._telemetryUtility.setTiles(mozSalesTile);
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToDismissed(mergedTiles);
+ feed._telemetryUtility.finalizeNewtabPingFields(mergedTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "mozsales title",
+ provider: "moz-sales",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_tiles_to_dismissed_then_updated() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+
+ // Step 1: Set initial tiles
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ // Step 2: Set all tiles to dismissed
+ feed._telemetryUtility.determineFilteredTilesAndSetToDismissed([]);
+
+ let updatedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+
+ // Step 3: Finalize with the updated list of tiles.
+ feed._telemetryUtility.finalizeNewtabPingFields(updatedTiles);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_tile_positions_after_updated_list() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+
+ // Step 1: Set initial tiles
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ // Step 2: Set 1 tile to oversold (brand3)
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+
+ // Step 3: Finalize with the updated list of tiles.
+ let updatedTiles = [
+ {
+ url: "https://www.replacement.com",
+ label: "replacement",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.finalizeNewtabPingFields(updatedTiles);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_tile_positions_after_updated_list_all_tiles() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+
+ // Step 1: Set initial tiles
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ // Step 2: Set 1 tile to oversold (brand3)
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+
+ // Step 3: Finalize with the updated list of tiles.
+ let updatedTiles = [
+ {
+ url: "https://www.replacement.com",
+ label: "replacement",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.replacement2.com",
+ label: "replacement2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.finalizeNewtabPingFields(updatedTiles);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(
+ async function test_set_tile_positions_after_no_refresh_no_tiles_changed() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+
+ // Step 1: Set initial tiles
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ // Step 2: Set 1 tile to oversold (brand3)
+ let mergedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(mergedTiles);
+
+ // Step 3: Finalize with the updated list of tiles.
+ let updatedTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ ];
+ feed._telemetryUtility.finalizeNewtabPingFields(updatedTiles);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_set_contile_tile_to_unresolved() {
+ let sandbox = sinon.createSandbox();
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ // Create the error state, need to bypass existing checks.
+ feed._telemetryUtility.allSponsoredTiles = {
+ ampbrand1: {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: "oversold",
+ },
+ ampbrand2: {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: null,
+ },
+ };
+
+ feed._telemetryUtility._detectErrorConditionAndSetUnresolved();
+
+ let result = JSON.stringify({
+ sponsoredTilesReceived: Object.values(
+ feed._telemetryUtility.allSponsoredTiles
+ ),
+ });
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "unresolved",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "unresolved",
+ },
+ ],
+ };
+ Assert.equal(result, JSON.stringify(expectedResult));
+ sandbox.restore();
+});
+
+add_task(async function test_set_position_to_value_gt_3() {
+ let sandbox = sinon.createSandbox();
+ info("Test setTilePositions uses sponsored_position value, not array index.");
+ let feed = getTopSitesFeedForTest(sandbox);
+
+ feed._telemetryUtility.setSponsoredTilesConfigured();
+ feed._telemetryUtility.setTiles([contileTile1, contileTile2, contileTile3]);
+
+ let filteredContileTiles = [
+ {
+ url: "https://www.brand1.com",
+ label: "brand1",
+ sponsored_position: 1,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand2.com",
+ label: "brand2",
+ sponsored_position: 2,
+ partner: "amp",
+ },
+ {
+ url: "https://www.brand3.com",
+ label: "brand3",
+ sponsored_position: 6,
+ partner: "amp",
+ },
+ ];
+
+ feed._telemetryUtility.determineFilteredTilesAndSetToOversold(
+ filteredContileTiles
+ );
+ feed._telemetryUtility.finalizeNewtabPingFields(filteredContileTiles);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 6,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_all_tiles_displayed() {
+ let sandbox = sinon.createSandbox();
+ info("if all provided tiles are displayed, the display_fail_reason is null");
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_one_tile_display_fail_reason_to_oversold() {
+ let sandbox = sinon.createSandbox();
+
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brnad3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_set_one_tile_display_fail_reason_to_dismissed() {
+ let sandbox = sinon.createSandbox();
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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://foo.com",
+ image_url: "images/foo.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brnad2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
+
+add_task(
+ async function test_set_one_tile_to_dismissed_and_one_tile_to_oversold() {
+ let sandbox = sinon.createSandbox();
+ let { feed, fetchStub } = prepFeed(
+ getTopSitesFeedForTest(sandbox),
+ sandbox
+ );
+
+ 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://foo.com",
+ image_url: "images/foo.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ {
+ url: "https://www.brand4.com",
+ image_url: "images/brand4-com.png",
+ click_url: "https://www.brand4-click.com",
+ impression_url: "https://www.brand4-impression.com",
+ name: "brand4",
+ },
+ ],
+ }),
+ });
+
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand4",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+ }
+);
+
+add_task(
+ async function test_set_one_cached_tile_display_fail_reason_to_dismissed() {
+ let sandbox = sinon.createSandbox();
+ info("confirm the telemetry is valid when using cached tiles.");
+
+ let { feed, fetchStub } = prepFeed(
+ getTopSitesFeedForTest(sandbox),
+ sandbox
+ );
+
+ const tiles = [
+ {
+ url: "https://www.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ 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",
+ },
+ ];
+
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, JSON.stringify(tiles));
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_PREF, 60 * 15);
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ Math.round(Date.now() / 1000)
+ );
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 1);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_update_tile_count() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "the tile count should update when topSitesMaxSponsored is updated by Nimbus"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+
+ // 1. Initially the Nimbus pref is set to 2 tiles
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ // 2. Set the Numbus pref to 3, confirm previous count still used.
+ const nimbusPocketStub = sandbox.stub(
+ NimbusFeatures.pocketNewtab,
+ "getVariable"
+ );
+ setNimbusVariablesForNumTiles(nimbusPocketStub, 3);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ // 3. Confirm the new count is applied when data pulled from Contile., 3 tiles displayed
+ fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 3);
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 3);
+
+ expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 3,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ sandbox.restore();
+});
+
+add_task(async function test_update_tile_count_sourced_from_cache() {
+ let sandbox = sinon.createSandbox();
+
+ info(
+ "the tile count should update from cache when topSitesMaxSponsored is updated by Nimbus"
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ const tiles = [
+ {
+ url: "https://www.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ];
+
+ Services.prefs.setStringPref(CONTILE_CACHE_PREF, JSON.stringify(tiles));
+ Services.prefs.setIntPref(CONTILE_CACHE_VALID_FOR_PREF, 60 * 15);
+ Services.prefs.setIntPref(
+ CONTILE_CACHE_LAST_FETCH_PREF,
+ Math.round(Date.now() / 1000)
+ );
+
+ fetchStub.resolves({
+ status: 304,
+ });
+
+ // 1. Initially the Nimbus pref is set to 2 tiles
+ // Ensure ContileIntegration._fetchSites is working populate _sites and initilize TelemetryUtility
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 3);
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ // 2. Set the Numbus pref to 3, confirm previous count still used.
+ const nimbusPocketStub = sandbox.stub(
+ NimbusFeatures.pocketNewtab,
+ "getVariable"
+ );
+ setNimbusVariablesForNumTiles(nimbusPocketStub, 3);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ // 3. Confirm the new count is applied when data pulled from Contile, 3 tiles displayed
+ fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 3);
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 3);
+
+ expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 3,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(
+ async function test_update_telemetry_fields_if_dismissed_brands_list_is_updated() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "if the user dismisses a brand, that dismissed tile shoudl be represented in the next ping."
+ );
+ let { feed, fetchStub } = prepFeed(
+ getTopSitesFeedForTest(sandbox),
+ sandbox
+ );
+
+ 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://foo.com",
+ image_url: "images/foo.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar","brand2"]`
+ );
+
+ fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 1);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+ }
+);
+
+add_task(async function test_sponsoredTilesReceived_not_set() {
+ let sandbox = sinon.createSandbox();
+ info("sponsoredTilesReceived should be empty if tiles service returns 204");
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ fetchStub.resolves({ ok: true, status: 204 });
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(!fetched);
+ Assert.ok(!feed._contile.sites.length);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+ let expectedResult = { sponsoredTilesReceived: [] };
+
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
+
+add_task(async function test_telemetry_data_updates() {
+ let sandbox = sinon.createSandbox();
+ info("sponsoredTilesReceived should update when new tiles received.");
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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://foo.com",
+ image_url: "images/foo.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ 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://foo.com",
+ image_url: "images/foo.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://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "brand3",
+ },
+ ],
+ }),
+ });
+
+ await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 1);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "bar",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
+
+add_task(async function test_reset_telemetry_data() {
+ let sandbox = sinon.createSandbox();
+ info(
+ "sponsoredTilesReceived should be cleared when no tiles received and cache refreshed."
+ );
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ 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://foo.com",
+ image_url: "images/foo.png",
+ click_url: "https://www.foo-click.com",
+ impression_url: "https://www.foo-impression.com",
+ name: "foo",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ {
+ url: "https://www.brand3.com",
+ image_url: "images/brand3-com.png",
+ click_url: "https://www.brand3-click.com",
+ impression_url: "https://www.brand3-impression.com",
+ name: "test3",
+ },
+ ],
+ }),
+ });
+ Services.prefs.setStringPref(
+ TOP_SITES_BLOCKED_SPONSORS_PREF,
+ `["foo","bar"]`
+ );
+
+ let fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "foo",
+ provider: "amp",
+ display_position: null,
+ display_fail_reason: "dismissed",
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand3",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+
+ fetchStub.resolves({ ok: true, status: 204 });
+
+ fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.ok(!feed._contile.sites.length);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+
+ expectedResult = { sponsoredTilesReceived: [] };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ Services.prefs.clearUserPref(TOP_SITES_BLOCKED_SPONSORS_PREF);
+ sandbox.restore();
+});
+
+add_task(async function test_set_telemetry_for_moz_sales_tiles() {
+ let sandbox = sinon.createSandbox();
+ let { feed, fetchStub } = prepFeed(getTopSitesFeedForTest(sandbox), sandbox);
+
+ sandbox.stub(feed, "fetchDiscoveryStreamSpocs").returns([
+ {
+ label: "MozSales Title",
+ title: "MozSales Title",
+ url: "https://mozsale.net",
+ sponsored_position: 1,
+ partner: "moz-sales",
+ },
+ ]);
+
+ 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.brand1.com",
+ image_url: "images/brand1-com.png",
+ click_url: "https://www.brand1-click.com",
+ impression_url: "https://www.brand1-impression.com",
+ name: "brand1",
+ },
+ {
+ url: "https://www.brand2.com",
+ image_url: "images/brand2-com.png",
+ click_url: "https://www.brand2-click.com",
+ impression_url: "https://www.brand2-impression.com",
+ name: "brand2",
+ },
+ ],
+ }),
+ });
+ const fetched = await feed._contile._fetchSites();
+ Assert.ok(fetched);
+ Assert.equal(feed._contile.sites.length, 2);
+
+ await feed._readDefaults();
+ await feed.getLinksWithDefaults(false);
+
+ Assert.equal(Glean.topsites.sponsoredTilesConfigured.testGetValue(), 2);
+ let expectedResult = {
+ sponsoredTilesReceived: [
+ {
+ advertiser: "brand1",
+ provider: "amp",
+ display_position: 1,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "brand2",
+ provider: "amp",
+ display_position: 2,
+ display_fail_reason: null,
+ },
+ {
+ advertiser: "mozsales title",
+ provider: "moz-sales",
+ display_position: null,
+ display_fail_reason: "oversold",
+ },
+ ],
+ };
+ Assert.equal(
+ Glean.topsites.sponsoredTilesReceived.testGetValue(),
+ JSON.stringify(expectedResult)
+ );
+ sandbox.restore();
+});
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.toml b/browser/components/newtab/test/xpcshell/xpcshell.toml
new file mode 100644
index 0000000000..a8470913af
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/xpcshell.toml
@@ -0,0 +1,34 @@
+[DEFAULT]
+firefox-appdir = "browser"
+skip-if = ["os == '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 = ["topstories.json"]
+skip-if = ["socketprocess_networking"] # Bug 1759035
+
+["test_AboutNewTab.js"]
+
+["test_AboutWelcomeAttribution.js"]
+
+["test_AboutWelcomeTelemetry.js"]
+
+["test_AboutWelcomeTelemetry_glean.js"]
+
+["test_HighlightsFeed.js"]
+
+["test_PlacesFeed.js"]
+
+["test_Store.js"]
+
+["test_TelemetryFeed.js"]
+support-files = ["../schemas/*.schema.json"]
+
+["test_TopSitesFeed.js"]
+
+["test_TopSitesFeed_glean.js"]
diff --git a/browser/components/newtab/tools/resourceUriPlugin.js b/browser/components/newtab/tools/resourceUriPlugin.js
new file mode 100644
index 0000000000..938822f410
--- /dev/null
+++ b/browser/components/newtab/tools/resourceUriPlugin.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/. */
+
+// This plugin supports finding files with particular resource:// URIs
+// and translating the uri into a relative filesytem path where the file may be
+// found when running within the Karma / Mocha test framework.
+
+module.exports = {
+ ResourceUriPlugin: class ResourceUriPlugin {
+ /**
+ * @typedef {RegEx} ResourceReplacement0
+ * A regular expression matching a resource:// URI substring to be
+ * replaced.
+ * @typedef {string} ResourceReplacement1
+ * A string to replace the matched substring with.
+ * @typedef {[ResourceReplacement0, ResourceReplacement1]} ResourceReplacement
+ */
+
+ /**
+ * Maps regular expressions representing resource URIs to strings that
+ * should replace matches for those regular expressions.
+ *
+ * @type {ResourceReplacement[]}
+ */
+ #resourcePathRegExes;
+
+ /**
+ * @param {object} options
+ * @param {ResourceReplacement[]} options.resourcePathRegExes
+ * An array of regex/string tuples to perform replacements on for
+ * imports involving resource:// URIs.
+ */
+ constructor({ resourcePathRegExes }) {
+ this.#resourcePathRegExes = resourcePathRegExes;
+ }
+
+ apply(compiler) {
+ compiler.hooks.compilation.tap(
+ "ResourceUriPlugin",
+ (compilation, { normalModuleFactory }) => {
+ normalModuleFactory.hooks.resolveForScheme
+ .for("resource")
+ .tap("ResourceUriPlugin", resourceData => {
+ const url = new URL(resourceData.resource);
+
+ for (let [regex, replacement] of this.#resourcePathRegExes) {
+ if (!url.href.match(regex)) {
+ continue;
+ }
+ const pathname = url.href.replace(regex, replacement);
+ resourceData.path = pathname;
+ resourceData.query = url.search;
+ resourceData.fragment = url.hash;
+ resourceData.resource = pathname + url.search + url.hash;
+ return true;
+ }
+
+ 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.sys.mjs b/browser/components/newtab/vendor/Redux.sys.mjs
new file mode 100644
index 0000000000..850b23ea44
--- /dev/null
+++ b/browser/components/newtab/vendor/Redux.sys.mjs
@@ -0,0 +1,691 @@
+/**
+ * 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 self = this;
+
+export const 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;
+ } else {
+ root = { "Symbol": undefined };
+ }
+
+ 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.system-addon.config.js b/browser/components/newtab/webpack.system-addon.config.js
new file mode 100644
index 0000000000..8f54186ab4
--- /dev/null
+++ b/browser/components/newtab/webpack.system-addon.config.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/. */
+
+const path = require("path");
+const webpack = require("webpack");
+const { ResourceUriPlugin } = require("./tools/resourceUriPlugin");
+
+const absolute = relPath => path.join(__dirname, relPath);
+
+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 to paths on the filesystem.
+ new ResourceUriPlugin({
+ resourcePathRegExes: [
+ [
+ new RegExp("^resource://activity-stream/"),
+ path.join(__dirname, "./"),
+ ],
+ ],
+ }),
+ 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"],
+ },
+ },
+ ],
+ },
+ // This resolve config allows us to import with paths relative to the root directory, e.g. "lib/ActivityStream.sys.mjs"
+ 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..a0666840e3
--- /dev/null
+++ b/browser/components/newtab/yamscripts.yml
@@ -0,0 +1,60 @@
+# 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
+ 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
+
+ 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
+
+ # script for the `source-test-node-newtab-unit-tests` task on taskcluster.
+ # this is what appears as `newtab` in treeherder results after pushing to try.
+ # so this npm script allows us to run the same tests locally that patches will
+ # be run against in CI.
+ try: node ./bin/try-runner.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