From 0985d9cf31ae99e7375f60f42aa74d99146f0ae4 Mon Sep 17 00:00:00 2001 From: Ryan Kienstra Date: Thu, 19 Jan 2023 08:59:50 -0600 Subject: [PATCH 1/6] Add a notion of filtered patterns --- .../js/src/components/ThemePatterns/index.tsx | 41 ++++++++----------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/wp-modules/app/js/src/components/ThemePatterns/index.tsx b/wp-modules/app/js/src/components/ThemePatterns/index.tsx index 62002f6f7..a8f77a9db 100644 --- a/wp-modules/app/js/src/components/ThemePatterns/index.tsx +++ b/wp-modules/app/js/src/components/ThemePatterns/index.tsx @@ -29,32 +29,25 @@ type Props = { export default function ThemePatterns( { isVisible }: Props ) { const { patterns } = usePmContext(); const [ currentCategory, setCurrentCategory ] = useState( 'all-patterns' ); - const [ themePatterns, setThemePatterns ] = useState< Patterns >( - createPatternsWithUncategorized( patterns ) - ); + const [ filteredPatterns, setFilteredPatterns ] = useState( createPatternsWithUncategorized( patterns.data ) ); - const patternsRef = useRef( themePatterns ); + function setNewFilteredPatterns( newPatterns: Patterns ) { + setFilteredPatterns( createPatternsWithUncategorized( newPatterns ) ); + } /** Catch pattern deletion since themePatterns is no longer derived. */ - useEffect( () => { - const updatedPatternData = createPatternsWithUncategorized( patterns ); - setThemePatterns( updatedPatternData ); - patternsRef.current = updatedPatternData; - }, [ patterns.data ] ); /** Create an object for included_patterns that includes an 'uncategorized' category. */ - function createPatternsWithUncategorized( { - data: patternData, - }: typeof patterns ): Patterns { - return Object.keys( patternData ).reduce( + function createPatternsWithUncategorized( patterns: Patterns ) { + return Object.keys( patterns ).reduce( ( acc, patternName ) => ( { ...acc, [ patternName ]: { - ...patternData[ patternName ], + ...patterns[ patternName ], categories: [ // Spread in the categories, or 'uncategorized' if empty. - ...( patternData[ patternName ].categories?.length - ? patternData[ patternName ].categories + ...( patterns[ patternName ].categories?.length + ? patterns[ patternName ].categories : [ 'uncategorized' ] ), ], }, @@ -77,11 +70,11 @@ export default function ThemePatterns( { isVisible }: Props ) { ...sortAlphabetically( [ // Array of unique category names. - ...Object.keys( themePatterns ) + ...Object.keys( filteredPatterns ) .reduce( ( acc, patternName ) => { return [ ...acc, - ...themePatterns[ patternName ]?.categories?.filter( + ...filteredPatterns[ patternName ]?.categories?.filter( ( category ) => { return ! acc.includes( category ); } @@ -104,7 +97,7 @@ export default function ThemePatterns( { isVisible }: Props ) { return (