import { recordTracksEvent } from '@automattic/calypso-analytics'; import config from '@automattic/calypso-config'; import { FEATURE_INSTALL_THEMES } from '@automattic/calypso-products'; import page from '@automattic/calypso-router'; import clsx from 'clsx'; import { localize } from 'i18n-calypso'; import { compact, pickBy } from 'lodash'; import PropTypes from 'prop-types'; import { createRef, Component } from 'react'; import { InView } from 'react-intersection-observer'; import { connect } from 'react-redux'; import AsyncLoad from 'calypso/components/async-load'; import QueryProductsList from 'calypso/components/data/query-products-list'; import QuerySitePlans from 'calypso/components/data/query-site-plans'; import QuerySitePurchases from 'calypso/components/data/query-site-purchases'; import QueryThemeFilters from 'calypso/components/data/query-theme-filters'; import { SearchThemes } from 'calypso/components/search-themes'; import ThemeDesignYourOwnModal from 'calypso/components/theme-design-your-own-modal'; import ThemeSiteSelectorModal from 'calypso/components/theme-site-selector-modal'; import { THEME_TIERS } from 'calypso/components/theme-tier/constants'; import PageViewTracker from 'calypso/lib/analytics/page-view-tracker'; import { THEME_COLLECTIONS } from 'calypso/my-sites/themes/collections/collection-definitions'; import ShowcaseThemeCollection from 'calypso/my-sites/themes/collections/showcase-theme-collection'; import ThemeCollectionViewHeader from 'calypso/my-sites/themes/collections/theme-collection-view-header'; import { getCurrentUserSiteCount, isUserLoggedIn } from 'calypso/state/current-user/selectors'; import getSiteEditorUrl from 'calypso/state/selectors/get-site-editor-url'; import getSiteFeaturesById from 'calypso/state/selectors/get-site-features'; import isAtomicSite from 'calypso/state/selectors/is-site-automated-transfer'; import siteHasFeature from 'calypso/state/selectors/site-has-feature'; import { isSiteOnWooExpress, isSiteOnECommerceTrial } from 'calypso/state/sites/plans/selectors'; import { getSite, getSiteSlug } from 'calypso/state/sites/selectors'; import { setBackPath } from 'calypso/state/themes/actions'; import { STATIC_FILTERS, DEFAULT_STATIC_FILTER } from 'calypso/state/themes/constants'; import { arePremiumThemesEnabled, getThemeFilterTerms, getThemeFilterToTermTable, prependThemeFilterKeys, isUpsellCardDisplayed as isUpsellCardDisplayedSelector, getThemeTiers, } from 'calypso/state/themes/selectors'; import { getThemesBookmark } from 'calypso/state/themes/themes-ui/selectors'; import EligibilityWarningModal from './atomic-transfer-dialog'; import { CustomSelectWrapper } from './custom-select-wrapper'; import { addTracking, getSubjectsFromTermTable, trackClick, localizeThemesPath, isStaticFilter, constructThemeShowcaseUrl, } from './helpers'; import ThemeErrors from './theme-errors'; import ThemePreview from './theme-preview'; import ThemeShowcaseHeader from './theme-showcase-header'; import ThemesSelection from './themes-selection'; import ThemesToolbarGroup from './themes-toolbar-group'; import './theme-showcase.scss'; const optionShape = PropTypes.shape( { label: PropTypes.string, header: PropTypes.string, getUrl: PropTypes.func, action: PropTypes.func, } ); class ThemeShowcase extends Component { state = { isDesignThemeModalVisible: false, isSiteSelectorModalVisible: false, shouldThemeControlsSticky: false, }; constructor( props ) { super( props ); this.scrollRef = createRef(); this.bookmarkRef = createRef(); this.showcaseRef = createRef(); this.subjectFilters = this.getSubjectFilters( props ); this.subjectTermTable = getSubjectsFromTermTable( props.filterToTermTable ); } static propTypes = { tier: PropTypes.oneOf( [ '', ...Object.keys( THEME_TIERS ) ] ), search: PropTypes.string, isCollectionView: PropTypes.bool, pathName: PropTypes.string, // Connected props options: PropTypes.objectOf( optionShape ), defaultOption: optionShape, secondaryOption: optionShape, getScreenshotOption: PropTypes.func, siteCanInstallThemes: PropTypes.bool, siteCount: PropTypes.number, siteSlug: PropTypes.string, upsellBanner: PropTypes.any, loggedOutComponent: PropTypes.bool, isAtomicSite: PropTypes.bool, isJetpackSite: PropTypes.bool, isSiteECommerceFreeTrial: PropTypes.bool, isSiteWooExpress: PropTypes.bool, isSiteWooExpressOrEcomFreeTrial: PropTypes.bool, }; static defaultProps = { tier: '', search: '', upsellBanner: false, showUploadButton: true, }; componentDidMount() { const { themesBookmark } = this.props; // Scroll to bookmark if applicable. if ( themesBookmark ) { // Timeout to move this to the end of the event queue or it won't work here. setTimeout( () => { const lastTheme = this.bookmarkRef.current; if ( lastTheme ) { lastTheme.scrollIntoView( { behavior: 'auto', block: 'center', inline: 'center', } ); } } ); } } componentDidUpdate( prevProps ) { if ( prevProps.search !== this.props.search || prevProps.filter !== this.props.filter || prevProps.tier !== this.props.tier ) { this.scrollToSearchInput(); } } componentWillUnmount() { this.props.setBackPath( this.constructUrl() ); } isThemeDiscoveryEnabled = () => config.isEnabled( 'themes/discovery' ); getStaticFilters() { const { translate } = this.props; return { MYTHEMES: { key: STATIC_FILTERS.MYTHEMES, get text() { return translate( 'My Themes' ); }, }, RECOMMENDED: { key: STATIC_FILTERS.RECOMMENDED, get text() { return translate( 'Recommended' ); }, }, ALL: { key: STATIC_FILTERS.ALL, get text() { return translate( 'All' ); }, }, }; } getDefaultStaticFilter = () => Object.values( this.getStaticFilters() ).find( ( staticFilter ) => staticFilter.key === DEFAULT_STATIC_FILTER ); isStaticFilter = ( tabFilter ) => isStaticFilter( tabFilter.key ); getSubjectFilters = ( props ) => { const { subjects } = props; return Object.fromEntries( Object.entries( subjects ).map( ( [ key, filter ] ) => [ key, { key, text: filter.name } ] ) ); }; getTabFilters = () => { const { translate } = this.props; const staticFilters = this.getStaticFilters(); if ( this.props.siteId && ! this.props.areSiteFeaturesLoaded ) { return null; } if ( this.props.isSiteWooExpress ) { return { MYTHEMES: staticFilters.MYTHEMES, RECOMMENDED: { ...staticFilters.RECOMMENDED, text: translate( 'All Themes' ), }, }; } const shouldShowMyThemesFilter = !! this.props.siteId; return { ...( shouldShowMyThemesFilter && { MYTHEMES: staticFilters.MYTHEMES } ), RECOMMENDED: staticFilters.RECOMMENDED, ALL: staticFilters.ALL, ...this.subjectFilters, }; }; getTiers = () => { const { themeTiers, translate } = this.props; const tiers = Object.keys( themeTiers ).reduce( ( availableTiers, tier ) => { if ( ! THEME_TIERS[ tier ]?.isFilterable ) { return availableTiers; } return [ ...availableTiers, { key: tier, name: THEME_TIERS[ tier ].label, }, ]; }, [] ); return [ { key: 'all', get name() { return translate( 'All' ); }, }, ...tiers, ]; }; findTabFilter = ( tabFilters, filterKey ) => Object.values( tabFilters ).find( ( filter ) => filter.key === filterKey ) || this.getDefaultStaticFilter(); getSelectedTabFilter = () => { const filter = this.props.filter ?? ''; const filterArray = filter.split( '+' ); const staticFilters = this.getStaticFilters(); const matches = Object.values( this.subjectTermTable ).filter( ( value ) => filterArray.includes( value ) ); if ( ! matches.length ) { return this.findTabFilter( staticFilters, this.props.category ); } const filterKey = matches[ matches.length - 1 ].split( ':' ).pop(); return this.findTabFilter( this.subjectFilters, filterKey ); }; scrollToSearchInput = () => { // Scroll to the top of the showcase if ( this.showcaseRef.current && this.state.shouldThemeControlsSticky ) { this.showcaseRef.current.scrollIntoView( { behavior: 'instant', block: 'start', } ); } let y = 0; if ( ! this.props.loggedOutComponent && this.scrollRef && this.scrollRef.current ) { // If you are a larger screen where the theme info is displayed horizontally. if ( window.innerWidth > 600 ) { return; } const headerHeight = document .getElementsByClassName( 'masterbar' )[ 0 ] ?.getBoundingClientRect().height; const screenOptionTab = document .getElementsByClassName( 'screen-options-tab__button' )[ 0 ] ?.getBoundingClientRect().height; const yOffset = -( headerHeight + screenOptionTab ); // Total height of admin bar and screen options on mobile. const elementBoundary = this.scrollRef.current.getBoundingClientRect(); y = elementBoundary.top + window.pageYOffset + yOffset; } window.scrollTo( { top: y } ); }; doSearch = ( searchBoxContent ) => { const filterRegex = /([\w-]*):([\w-]*)/g; const { filterToTermTable, subjectStringFilter, isLoggedIn } = this.props; const staticFilters = this.getStaticFilters(); const searchString = `${ searchBoxContent } ${ ! isLoggedIn ? subjectStringFilter : '' }`; const filters = searchString.match( filterRegex ) || []; const validFilters = filters.map( ( filter ) => filterToTermTable[ filter ] ); const filterString = compact( validFilters ).join( '+' ); const search = searchBoxContent.replace( filterRegex, '' ).replace( /\s+/g, ' ' ).trim(); const url = this.constructUrl( { filter: filterString, // Strip filters and excess whitespace search, ...( ( this.isThemeDiscoveryEnabled() && ! this.props.category && search ) || ( filterString && { category: staticFilters.ALL.key, } ) ), // If a category isn't selected we search in the all category. ...( search && ! subjectStringFilter && { category: staticFilters.ALL.key, } ), } ); page( url ); this.scrollToSearchInput(); }; /** * Returns a full showcase url from current props. * @param {Object} sections fields from this object will override current props. * @param {string} sections.vertical override vertical prop * @param {string} sections.tier override tier prop * @param {string} sections.filter override filter prop * @param {string} sections.siteSlug override siteSlug prop * @param {string} sections.search override search prop * @param {string} sections.isCollectionView should display the collection view. * @returns {string} Theme showcase url */ constructUrl = ( sections ) => { return constructThemeShowcaseUrl( { ...this.props, ...sections, } ); }; onTierSelectFilter = ( attrs ) => { const tier = attrs.selectedItem.key; recordTracksEvent( 'calypso_themeshowcase_filter_pricing_click', { tier } ); trackClick( 'search bar filter', tier ); const category = tier !== 'all' && ! this.props.category ? '' : this.props.category; const showCollection = this.isThemeDiscoveryEnabled() && ! this.props.filterString && ! category && tier !== 'all'; const staticFilters = this.getStaticFilters(); const url = this.constructUrl( { tier, category, search: showCollection ? '' : this.props.search, // Due to the search backend limitation, "My Themes" can only have "All" tier. ...( tier !== 'all' && this.props.category === staticFilters.MYTHEMES.key && { category: staticFilters.RECOMMENDED.key, } ), } ); page( url ); this.scrollToSearchInput(); }; onFilterClick = ( tabFilter ) => { recordTracksEvent( 'calypso_themeshowcase_filter_category_click', { category: tabFilter.key } ); trackClick( 'section nav filter', tabFilter ); const staticFilters = this.getStaticFilters(); const { filter = '', filterToTermTable } = this.props; const subjectFilters = Object.values( this.subjectTermTable ); const filterWithoutSubjects = filter .split( '+' ) .filter( ( key ) => ! subjectFilters.includes( key ) ) .join( '+' ); const newUrlParams = {}; if ( this.isStaticFilter( tabFilter ) ) { newUrlParams.category = tabFilter.key; newUrlParams.filter = filterWithoutSubjects; // Due to the search backend limitation, "My Themes" can only have "All" tier. if ( tabFilter.key === staticFilters.MYTHEMES.key && this.props.tier !== 'all' ) { newUrlParams.tier = 'all'; } } else { const subjectTerm = filterToTermTable[ `subject:${ tabFilter.key }` ]; newUrlParams.filter = [ filterWithoutSubjects, subjectTerm ].join( '+' ); newUrlParams.category = null; } page( this.constructUrl( newUrlParams ) ); this.scrollToSearchInput(); }; shouldShowCollections = () => { const { category, search, filter, isCollectionView, tier } = this.props; if ( this.props.isJetpackSite && ! this.props.isAtomicSite ) { return false; } return ( ! ( category || search || filter || isCollectionView ) && tier === '' && this.isThemeDiscoveryEnabled() ); }; allThemes = ( { themeProps } ) => { const { filter, isCollectionView, tier } = this.props; // In Collection View of pricing tiers (e.g. Partner themes), prevent requesting only recommended themes. const themesSelectionProps = { ...themeProps, ...( isCollectionView && tier && ! filter && { tabFilter: '' } ), }; const themeCollection = THEME_COLLECTIONS.partner; return (