From a6cb22f73858bcd58030e77b2820b7ca601c3908 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Wed, 16 Oct 2024 10:36:27 +0200 Subject: [PATCH] Memoize pattern objects returned from getAllowedPatterns Co-authored-by: jsnajdr Co-authored-by: youknowriad Co-authored-by: andrewserong Co-authored-by: ndiego Co-authored-by: colorful-tones Co-authored-by: kevin940726 Co-authored-by: ramonjd Co-authored-by: madhusudhand Co-authored-by: getdave Co-authored-by: annezazu --- packages/block-editor/src/store/selectors.js | 24 +++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js index 1e5dad86eb12ad..c34d96ecf53b85 100644 --- a/packages/block-editor/src/store/selectors.js +++ b/packages/block-editor/src/store/selectors.js @@ -2363,6 +2363,21 @@ const getAllowedPatternsDependants = ( select ) => ( state, rootClientId ) => [ ...getInsertBlockTypeDependants( state, rootClientId ), ]; +const patternsWithParsedBlocks = new WeakMap(); +function enhancePatternWithParsedBlocks( pattern ) { + let enhancedPattern = patternsWithParsedBlocks.get( pattern ); + if ( ! enhancedPattern ) { + enhancedPattern = { + ...pattern, + get blocks() { + return getParsedPattern( pattern ).blocks; + }, + }; + patternsWithParsedBlocks.set( pattern, enhancedPattern ); + } + return enhancedPattern; +} + /** * Returns the list of allowed patterns for inner blocks children. * @@ -2379,14 +2394,7 @@ export const __experimentalGetAllowedPatterns = createRegistrySelector( const { allowedBlockTypes } = getSettings( state ); const parsedPatterns = patterns .filter( ( { inserter = true } ) => !! inserter ) - .map( ( pattern ) => { - return { - ...pattern, - get blocks() { - return getParsedPattern( pattern ).blocks; - }, - }; - } ); + .map( enhancePatternWithParsedBlocks ); const availableParsedPatterns = parsedPatterns.filter( ( pattern ) =>