Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern block: Update block to retain wrapper #50272

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
202975e
Initial attempt to leave a pattern block wrapped around a pattern
glendaviesnz Apr 20, 2023
f5e64f8
Add a wrapper div
glendaviesnz Apr 21, 2023
65a852a
Add rough prototype of sync versus unsynced
glendaviesnz Apr 21, 2023
0da8eba
add pattern experiment
glendaviesnz May 11, 2023
6b60cd4
Add default layout attributes and change sync status to enum
glendaviesnz Apr 25, 2023
03b49e7
Remove wrapper div from frontend
glendaviesnz Apr 27, 2023
ea0b808
Pattern Enhancements: Render unsynced pattern content (#50114)
aaronrobertshaw Apr 27, 2023
de7183d
Use a fixed custom align attrib so block toolbar align button doesn't…
glendaviesnz Apr 27, 2023
a81ed2d
Fix issue with duplicated block toolbar and inspector controls by clo…
glendaviesnz Apr 30, 2023
18852ff
Add wrapper to frontend and add pattern slug to use as selector
glendaviesnz May 1, 2023
0fe7893
Add ability to sync and unsync
glendaviesnz May 2, 2023
7ebe8a0
Make reverting to `Sync` revert to saved pattern blocks
glendaviesnz May 2, 2023
618edc3
Change default syncStatus to unsynced for barckwards compat
glendaviesnz May 3, 2023
8e690a7
Get widest align from child blocks (#50230)
glendaviesnz May 3, 2023
604e67a
Switch to using template lock to denote different edit statuses of pa…
glendaviesnz May 3, 2023
7c5f361
Add wrapper to frontend
glendaviesnz May 3, 2023
94d7780
Wrap patterns in the inserter with the pattern block
kevin940726 May 3, 2023
177b85a
Fix issue with block invalidation on first load
glendaviesnz May 3, 2023
e70dc51
Switch to only adding a wrapper and contentOnly if syncStatus === par…
glendaviesnz May 11, 2023
86afac2
Revert "Switch to only adding a wrapper and contentOnly if syncStatus…
glendaviesnz May 11, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,8 +464,8 @@ Show a block pattern. ([Source](https://github.com/WordPress/gutenberg/tree/trun

- **Name:** core/pattern
- **Category:** theme
- **Supports:** ~~html~~, ~~inserter~~
- **Attributes:** slug
- **Supports:**
- **Attributes:** forcedAlignment, layout, slug, templateLock

## Post Author

Expand Down
3 changes: 3 additions & 0 deletions lib/experimental/editor-settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ function gutenberg_enable_experiments() {
if ( $gutenberg_experiments && array_key_exists( 'gutenberg-theme-previews', $gutenberg_experiments ) ) {
wp_add_inline_script( 'wp-block-editor', 'window.__experimentalEnableThemePreviews = true', 'before' );
}
if ( $gutenberg_experiments && array_key_exists( 'gutenberg-pattern-enhancements', $gutenberg_experiments ) ) {
wp_add_inline_script( 'wp-block-editor', 'window.__experimentalEnablePatternEnhancements = true', 'before' );
}

}

Expand Down
12 changes: 12 additions & 0 deletions lib/experiments-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,18 @@ function gutenberg_initialize_experiments_settings() {
)
);

add_settings_field(
'gutenberg-pattern-enhancements',
__( 'Pattern enhancements', 'gutenberg' ),
'gutenberg_display_experiment_field',
'gutenberg-experiments',
'gutenberg_experiments_section',
array(
'label' => __( 'Test the Pattern block enhancements', 'gutenberg' ),
'id' => 'gutenberg-pattern-enhancements',
)
);

register_setting(
'gutenberg-experiments',
'gutenberg-experiments'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* WordPress dependencies
*/
import { useCallback } from '@wordpress/element';
import { cloneBlock } from '@wordpress/blocks';
import { createBlock, cloneBlock } from '@wordpress/blocks';
import { useDispatch, useSelect } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
Expand Down Expand Up @@ -35,10 +35,25 @@ const usePatternsState = ( onInsert, rootClientId ) => {
);
const { createSuccessNotice } = useDispatch( noticesStore );
const onClickPattern = useCallback( ( pattern, blocks ) => {
onInsert(
( blocks ?? [] ).map( ( block ) => cloneBlock( block ) ),
pattern.name
);
if ( window?.__experimentalEnablePatternEnhancements ) {
onInsert(
blocks
? [
createBlock(
'core/pattern',
{ slug: pattern.name },
blocks.map( ( block ) => cloneBlock( block ) )
),
]
: [],
pattern.name
);
} else {
onInsert(
( blocks ?? [] ).map( ( block ) => cloneBlock( block ) ),
pattern.name
);
}
createSuccessNotice(
sprintf(
/* translators: %s: block pattern title. */
Expand Down
20 changes: 18 additions & 2 deletions packages/block-library/src/pattern/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,29 @@
"category": "theme",
"description": "Show a block pattern.",
"supports": {
"html": false,
"inserter": false
"__experimentalLayout": {
"allowEditing": false
}
},
"textdomain": "default",
"attributes": {
"slug": {
"type": "string"
},
"forcedAlignment": {
"type": "string",
"default": "full"
},
"layout": {
"type": "object",
"default": {
"type": "constrained"
}
},
"templateLock": {
"type": [ "string", "boolean" ],
"enum": [ "contentOnly", false ],
"default": "contentOnly"
}
}
}
104 changes: 88 additions & 16 deletions packages/block-library/src/pattern/edit.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,118 @@
/**
* WordPress dependencies
*/
import { cloneBlock } from '@wordpress/blocks';
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect } from '@wordpress/element';
import {
store as blockEditorStore,
useBlockProps,
useInnerBlocksProps,
BlockControls,
} from '@wordpress/block-editor';
import { ToolbarButton } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const PatternEdit = ( { attributes, clientId } ) => {
const selectedPattern = useSelect(
( select ) =>
select( blockEditorStore ).__experimentalGetParsedPattern(
attributes.slug
),
[ attributes.slug ]
const PatternEdit = ( { attributes, clientId, setAttributes } ) => {
const { inheritedAlignment, slug, templateLock } = attributes;
const { selectedPattern, innerBlocks } = useSelect(
( select ) => {
return {
selectedPattern:
select( blockEditorStore ).__experimentalGetParsedPattern(
slug
),
innerBlocks:
select( blockEditorStore ).getBlock( clientId )
?.innerBlocks,
};
},
[ slug, clientId ]
);

const { replaceBlocks, __unstableMarkNextChangeAsNotPersistent } =
const { replaceInnerBlocks, __unstableMarkNextChangeAsNotPersistent } =
useDispatch( blockEditorStore );

// Run this effect when the component loads.
// This adds the Pattern's contents to the post.
// This change won't be saved.
// It will continue to pull from the pattern file unless changes are made to its respective template part.
useEffect( () => {
if ( selectedPattern?.blocks ) {
if ( selectedPattern?.blocks && ! innerBlocks?.length ) {
// We batch updates to block list settings to avoid triggering cascading renders
// for each container block included in a tree and optimize initial render.
// Since the above uses microtasks, we need to use a microtask here as well,
// because nested pattern blocks cannot be inserted if the parent block supports
// inner blocks but doesn't have blockSettings in the state.
window.queueMicrotask( () => {
__unstableMarkNextChangeAsNotPersistent();
replaceBlocks( clientId, selectedPattern.blocks );
replaceInnerBlocks(
clientId,
selectedPattern.blocks.map( ( block ) =>
cloneBlock( block )
)
);
} );
}
}, [ clientId, selectedPattern?.blocks ] );
}, [
clientId,
selectedPattern?.blocks,
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
innerBlocks,
] );

useEffect( () => {
const alignments = [ 'wide', 'full' ];
const blocks = innerBlocks;
if ( ! blocks || blocks.length === 0 ) {
return;
}
// Determine the widest setting of all the contained blocks.
const widestAlignment = blocks.reduce( ( accumulator, block ) => {
const { align } = block.attributes;
return alignments.indexOf( align ) >
alignments.indexOf( accumulator )
? align
: accumulator;
}, undefined );

const props = useBlockProps();
// Set the attribute of the Pattern block to match the widest
// alignment.
setAttributes( {
inheritedAlignment: widestAlignment ?? '',
} );
}, [
innerBlocks,
selectedPattern?.blocks,
setAttributes,
inheritedAlignment,
] );

return <div { ...props } />;
const blockProps = useBlockProps( {
className: inheritedAlignment && `align${ inheritedAlignment }`,
} );
const innerBlocksProps = useInnerBlocksProps( blockProps, {
templateLock: templateLock === 'contentOnly' ? 'contentOnly' : false,
} );

const handleSync = () => {
if ( templateLock === false ) {
setAttributes( { templateLock: 'contentOnly' } );
} else {
setAttributes( { templateLock: false } );
}
};

return (
<>
<div { ...innerBlocksProps } />
<BlockControls group="other">
<ToolbarButton onClick={ handleSync }>
{ templateLock === false
? __( 'Edit content only' )
: __( 'Edit all' ) }
</ToolbarButton>
</BlockControls>
</>
);
};

export default PatternEdit;
10 changes: 6 additions & 4 deletions packages/block-library/src/pattern/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
*/
import initBlock from '../utils/init-block';
import metadata from './block.json';
import PatternEdit from './edit';
import PatternEditV1 from './v1/edit';
import PatternEditV2 from './edit';
import PatternSave from './save';

const { name } = metadata;
export { metadata, name };

export const settings = {
edit: PatternEdit,
};
export const settings = window?.__experimentalEnablePatternEnhancements
? { edit: PatternEditV2, save: PatternSave }
: { edit: PatternEditV1 };

export const init = () => initBlock( { name, metadata, settings } );
13 changes: 10 additions & 3 deletions packages/block-library/src/pattern/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,30 @@ function register_block_core_pattern() {
/**
* Renders the `core/pattern` block on the server.
*
* @param array $attributes Block attributes.
* @param array $attributes Block attributes.
* @param string $content The block rendered content.
*
* @return string Returns the output of the pattern.
*/
function render_block_core_pattern( $attributes ) {
function render_block_core_pattern( $attributes, $content ) {
if ( empty( $attributes['slug'] ) ) {
return '';
}

$wrapper = '<div class="align' . $attributes['forcedAlignment'] . '" data-pattern-slug="' . $attributes['slug'] . '">%s</div>';

if ( isset( $attributes['syncStatus'] ) && 'unsynced' === $attributes['syncStatus'] ) {
return sprintf( $wrapper, $content );
}

$slug = $attributes['slug'];
$registry = WP_Block_Patterns_Registry::get_instance();
if ( ! $registry->is_registered( $slug ) ) {
return '';
}

$pattern = $registry->get_registered( $slug );
return do_blocks( $pattern['content'] );
return sprintf( $wrapper, do_blocks( $pattern['content'] ) );
}

add_action( 'init', 'register_block_core_pattern' );
18 changes: 18 additions & 0 deletions packages/block-library/src/pattern/save.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* WordPress dependencies
*/
import { useBlockProps, useInnerBlocksProps } from '@wordpress/block-editor';

export default function save( {
attributes: { inheritedAlignment },
innerBlocks,
} ) {
if ( innerBlocks?.length === 0 ) {
return;
}
const blockProps = useBlockProps.save( {
className: inheritedAlignment && `align${ inheritedAlignment }`,
} );
const innerBlocksProps = useInnerBlocksProps.save( blockProps );
return <div { ...innerBlocksProps }>{ innerBlocksProps.children }</div>;
}
51 changes: 51 additions & 0 deletions packages/block-library/src/pattern/v1/edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* WordPress dependencies
*/
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect } from '@wordpress/element';
import {
store as blockEditorStore,
useBlockProps,
} from '@wordpress/block-editor';

const PatternEdit = ( { attributes, clientId } ) => {
const selectedPattern = useSelect(
( select ) =>
select( blockEditorStore ).__experimentalGetParsedPattern(
attributes.slug
),
[ attributes.slug ]
);

const { replaceBlocks, __unstableMarkNextChangeAsNotPersistent } =
useDispatch( blockEditorStore );

// Run this effect when the component loads.
// This adds the Pattern's contents to the post.
// This change won't be saved.
// It will continue to pull from the pattern file unless changes are made to its respective template part.
useEffect( () => {
if ( selectedPattern?.blocks ) {
// We batch updates to block list settings to avoid triggering cascading renders
// for each container block included in a tree and optimize initial render.
// Since the above uses microtasks, we need to use a microtask here as well,
// because nested pattern blocks cannot be inserted if the parent block supports
// inner blocks but doesn't have blockSettings in the state.
window.queueMicrotask( () => {
__unstableMarkNextChangeAsNotPersistent();
replaceBlocks( clientId, selectedPattern.blocks );
} );
}
}, [
clientId,
selectedPattern?.blocks,
__unstableMarkNextChangeAsNotPersistent,
replaceBlocks,
] );

const props = useBlockProps();

return <div { ...props } />;
};

export default PatternEdit;
7 changes: 6 additions & 1 deletion test/integration/fixtures/blocks/core__pattern.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
"name": "core/pattern",
"isValid": true,
"attributes": {
"slug": "core/text-two-columns"
"forcedAlignment": "full",
"layout": {
"type": "constrained"
},
"slug": "core/text-two-columns",
"syncStatus": "synced"
},
"innerBlocks": []
}
Expand Down