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

Shuffle blocks for contentOnly patterns #45618

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
150 changes: 124 additions & 26 deletions packages/block-editor/src/hooks/content-lock-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ import { useDispatch, useSelect } from '@wordpress/data';
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
import { useEffect, useRef, useCallback } from '@wordpress/element';
import { store as blocksStore } from '@wordpress/blocks';

/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../store';
import { BlockControls, BlockSettingsMenuControls } from '../components';
import {
flattenBlocks,
replaceContentsInBlocks,
areBlocksAlike,
} from './utils';
/**
* External dependencies
*/
Expand Down Expand Up @@ -41,6 +47,89 @@ function StopEditingAsBlocksOnOutsideSelect( {
return null;
}

function ShufflePatternsToolbarItem( { clientId } ) {
// TODO: Probably worth to add this to blocks' selectors.
const getFlattenContentBlocks = useSelect( ( select ) => {
const contentBlockNames = select( blocksStore )
.getBlockTypes()
.filter(
( blockType ) =>
blockType.name !== 'core/list-item' &&
Object.values( blockType.attributes ).some(
( attribute ) =>
attribute.__experimentalRole === 'content'
)
)
.map( ( blockType ) => blockType.name );

return ( blocks ) =>
flattenBlocks( blocks ).filter( ( block ) =>
contentBlockNames.includes( block.name )
);
}, [] );
const { contentBlocks, patterns } = useSelect(
( select ) => {
const blocks =
select( blockEditorStore ).getBlocksByClientId( clientId );
const _contentBlocks = getFlattenContentBlocks( blocks );
const allPatterns =
select( blockEditorStore ).__experimentalGetAllowedPatterns();

return {
contentBlocks: _contentBlocks,
patterns: allPatterns
.filter( ( pattern ) => {
const patternContentBlocks = getFlattenContentBlocks(
pattern.blocks
);
return (
patternContentBlocks.length ===
_contentBlocks.length &&
_contentBlocks.every(
( block, index ) =>
block.name ===
patternContentBlocks[ index ].name
)
);
} )
.filter(
( pattern ) =>
! areBlocksAlike( blocks, pattern.blocks )
),
kevin940726 marked this conversation as resolved.
Show resolved Hide resolved
};
},
[ clientId, getFlattenContentBlocks ]
);
const { replaceBlocks } = useDispatch( blockEditorStore );

function shuffle() {
// We're not using `Math.random` for instance ids here.
// eslint-disable-next-line no-restricted-syntax
const randomNumber = Math.floor( Math.random() * patterns.length );
const pattern = patterns[ randomNumber ];
const replacedPatternBlocks = replaceContentsInBlocks(
pattern.blocks,
contentBlocks
).map( ( block ) => {
block.attributes.templateLock = 'contentOnly';
return block;
} );
replaceBlocks( clientId, replacedPatternBlocks );
}

if ( patterns.length === 0 ) {
return null;
}

return (
<BlockControls group="other">
<ToolbarButton onClick={ shuffle }>
{ __( 'Shuffle' ) }
</ToolbarButton>
</BlockControls>
);
}

export const withBlockControls = createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
const { getBlockListSettings, getSettings } =
Expand Down Expand Up @@ -124,33 +213,42 @@ export const withBlockControls = createHigherOrderComponent(
</>
) }
{ ! isEditingAsBlocks && isContentLocked && props.isSelected && (
<BlockSettingsMenuControls>
{ ( { onClose } ) => (
<MenuItem
onClick={ () => {
__unstableMarkNextChangeAsNotPersistent();
updateBlockAttributes( props.clientId, {
templateLock: undefined,
} );
updateBlockListSettings( props.clientId, {
...getBlockListSettings(
<>
<BlockSettingsMenuControls>
{ ( { onClose } ) => (
<MenuItem
onClick={ () => {
__unstableMarkNextChangeAsNotPersistent();
updateBlockAttributes( props.clientId, {
templateLock: undefined,
} );
updateBlockListSettings(
props.clientId,
{
...getBlockListSettings(
props.clientId
),
templateLock: false,
}
);
focusModeToRevert.current =
getSettings().focusMode;
updateSettings( { focusMode: true } );
__unstableSetTemporarilyEditingAsBlocks(
props.clientId
),
templateLock: false,
} );
focusModeToRevert.current =
getSettings().focusMode;
updateSettings( { focusMode: true } );
__unstableSetTemporarilyEditingAsBlocks(
props.clientId
);
onClose();
} }
>
{ __( 'Modify' ) }
</MenuItem>
) }
</BlockSettingsMenuControls>
);
onClose();
} }
>
{ __( 'Modify' ) }
</MenuItem>
) }
</BlockSettingsMenuControls>

<ShufflePatternsToolbarItem
clientId={ props.clientId }
/>
</>
) }
<BlockEdit
{ ...props }
Expand Down
86 changes: 84 additions & 2 deletions packages/block-editor/src/hooks/utils.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/**
* External dependencies
*/
import { isEmpty, mapValues, get, setWith, clone } from 'lodash';
import { isEmpty, mapValues, get, setWith, clone, isEqual } from 'lodash';

/**
* WordPress dependencies
*/
import { getBlockSupport } from '@wordpress/blocks';
import { getBlockSupport, getBlockType, createBlock } from '@wordpress/blocks';

/**
* Removed falsy values from nested object.
Expand Down Expand Up @@ -111,3 +111,85 @@ export function shouldSkipSerialization( blockType, featureSet, feature ) {

return skipSerialization;
}

export function flattenBlocks( blocks ) {
return blocks.flatMap( ( block ) => [
block,
...flattenBlocks( block.innerBlocks ),
] );
}

export function replaceContentsInBlocks( sourceBlocks, contentBlocks ) {
const [ contentBlock, ...restContentBlocks ] = contentBlocks;
return sourceBlocks.map( ( block ) => {
if ( block.name !== contentBlock.name ) {
return createBlock(
block.name,
block.attributes,
replaceContentsInBlocks( block.innerBlocks, contentBlocks )
);
}

const blockTypeAttributes = getBlockType( block.name ).attributes;
return createBlock(
block.name,
Object.keys( block.attributes ).reduce(
( attributes, attributeName ) => {
if (
blockTypeAttributes[ attributeName ]
.__experimentalRole === 'content'
) {
attributes[ attributeName ] =
contentBlock.attributes[ attributeName ];
} else {
attributes[ attributeName ] =
block.attributes[ attributeName ];
}
return attributes;
},
{}
),
replaceContentsInBlocks( block.innerBlocks, restContentBlocks )
);
} );
}

export function areBlocksAlike( sourceBlocks, targetBlocks ) {
if ( sourceBlocks.length !== targetBlocks.length ) {
return false;
}

for ( let index = 0; index < sourceBlocks.length; index += 1 ) {
const sourceBlock = sourceBlocks[ index ];
const targetBlock = targetBlocks[ index ];

if ( sourceBlock.name !== targetBlock.name ) {
return false;
}

const blockTypeAttributes = getBlockType( sourceBlock.name ).attributes;

if (
Object.keys( blockTypeAttributes ).some(
( attribute ) =>
attribute !== 'templateLock' &&
blockTypeAttributes[ attribute ].__experimentalRole !==
'content' &&
! isEqual(
sourceBlock.attributes[ attribute ],
targetBlock.attributes[ attribute ]
)
)
) {
return false;
}

if (
! areBlocksAlike( sourceBlock.innerBlocks, targetBlock.innerBlocks )
) {
return false;
}
}

return true;
}