Skip to content

Commit

Permalink
Patterns: Inject the theme name into the block attributes (#54595)
Browse files Browse the repository at this point in the history
* Patterns: Inject the theme name into the block attributes when a pattern is loaded in the start template screen

* Add a comment to make it clear what code is duplicated
  • Loading branch information
scruffian authored Sep 21, 2023
1 parent 883ac8e commit dd7e10a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/block-library/src/pattern/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const PatternEdit = ( { attributes, clientId } ) => {
const { getBlockRootClientId, getBlockEditingMode } =
useSelect( blockEditorStore );

// Duplicated in packages/edit-site/src/components/start-template-options/index.js.
function injectThemeAttributeInBlockTemplateContent( block ) {
if (
block.innerBlocks.find(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,37 @@ function useStartPatterns( fallbackContent ) {
};
}, [] );

const currentThemeStylesheet = useSelect(
( select ) => select( coreStore ).getCurrentTheme().stylesheet
);

// Duplicated from packages/block-library/src/pattern/edit.js.
function injectThemeAttributeInBlockTemplateContent( block ) {
if (
block.innerBlocks.find(
( innerBlock ) => innerBlock.name === 'core/template-part'
)
) {
block.innerBlocks = block.innerBlocks.map( ( innerBlock ) => {
if (
innerBlock.name === 'core/template-part' &&
innerBlock.attributes.theme === undefined
) {
innerBlock.attributes.theme = currentThemeStylesheet;
}
return innerBlock;
} );
}

if (
block.name === 'core/template-part' &&
block.attributes.theme === undefined
) {
block.attributes.theme = currentThemeStylesheet;
}
return block;
}

return useMemo( () => {
// filter patterns that are supposed to be used in the current template being edited.
return [
Expand All @@ -68,7 +99,12 @@ function useStartPatterns( fallbackContent ) {
);
} )
.map( ( pattern ) => {
return { ...pattern, blocks: parse( pattern.content ) };
return {
...pattern,
blocks: parse( pattern.content ).map( ( block ) =>
injectThemeAttributeInBlockTemplateContent( block )
),
};
} ),
];
}, [ fallbackContent, slug, patterns ] );
Expand Down

0 comments on commit dd7e10a

Please sign in to comment.