22import { useSelect , useDispatch } from '@wordpress/data' ;
33import classnames from 'classnames' ;
44import { track } from '../utils/rest' ;
5- import { useMemo } from '@wordpress/element' ;
5+ import { useMemo , useEffect } from '@wordpress/element' ;
66
77const CategoryButtons = ( { categories, style } ) => {
88 const data = useSelect ( ( select ) => ( {
99 category : select ( 'ti-onboarding' ) . getCurrentCategory ( ) ,
1010 query : select ( 'ti-onboarding' ) . getSearchQuery ( ) ,
1111 trackingId : select ( 'ti-onboarding' ) . getTrackingId ( ) ,
1212 step : select ( 'ti-onboarding' ) . getCurrentStep ( ) ,
13+ sitesMetadata : select ( 'ti-onboarding' ) . getSites ( ) ,
14+ editor : select ( 'ti-onboarding' ) . getCurrentEditor ( ) ,
1315 } ) ) ;
1416
1517 const { setOnboardingStep, setCategory } = useDispatch ( 'ti-onboarding' ) ;
1618
17- // Show "All" and "Free" categories after user selection.
1819 const availableCategories = useMemo ( ( ) => {
1920 return Object . keys ( categories ) . filter ( ( key ) =>
21+ // Show "All" and "Free" categories after user selection.
2022 data . category || ( key !== 'all' && key !== 'free' )
21- ) ;
22- } , [ categories , data . category ] ) ;
23+ ) . filter ( ( key ) => {
24+ // Hide "Free" is there is not free template available on the selected editor.
25+ if ( key !== 'free' ) {
26+ return true ;
27+ }
28+ return Object . values ( data . sitesMetadata . sites ?. [ data . editor ] ) ?. some ( ( s ) => ! s ?. upsell ) ;
29+ } ) ;
30+ } , [ categories , data . category , data . sitesMetadata , data . editor ] ) ;
2331
2432 const onClick = ( newCategory ) => {
2533 setCategory ( newCategory ) ;
@@ -44,6 +52,15 @@ const CategoryButtons = ( { categories, style } ) => {
4452 }
4553 } ;
4654
55+ /**
56+ * Default the category to 'all' when the current category is unavailable.
57+ */
58+ useEffect ( ( ) => {
59+ if ( data . category && ! availableCategories . includes ( data . category ) ) {
60+ setCategory ( 'all' ) ;
61+ }
62+ } , [ data . category , availableCategories , setCategory ] ) ;
63+
4764 return (
4865 < div className = "ob-cat-wrap" style = { style } >
4966 { availableCategories . map ( ( catSlug ) => {
0 commit comments