Skip to content

Commit

Permalink
Simplify and fix in site editor
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad committed May 29, 2024
1 parent 4da5e6b commit 276e906
Showing 1 changed file with 4 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,9 @@ import { __ } from '@wordpress/i18n';
import { store as blockEditorStore } from '../../store';
import Warning from '../warning';

/**
* Recursively find very first block of an specific block type.
*
* @param {Object[]} blocks List of blocks.
* @param {string} name Block name to search.
*
* @return {Object|undefined} Return block object or undefined.
*/
function findFirstOfSameType( blocks, name ) {
if ( ! Array.isArray( blocks ) || ! blocks.length ) {
return;
}

for ( const block of blocks ) {
if ( block.name === name ) {
return block;
}

// Search inside innerBlocks.
const firstBlock = findFirstOfSameType( block.innerBlocks, name );

if ( firstBlock ) {
return firstBlock;
}
}
}

export function useOriginalBlockOnlyUseOnce( clientId ) {
return useSelect( ( select ) => {
const { getBlockName } = select( blockEditorStore );
const { getBlockName, getBlocksByName } = select( blockEditorStore );
const blockName = getBlockName( clientId );
const multiple = hasBlockSupport( blockName, 'multiple', true );

Expand All @@ -50,14 +23,10 @@ export function useOriginalBlockOnlyUseOnce( clientId ) {
if ( multiple ) {
return false;
}

// Otherwise, only pass `originalBlockClientId` if it refers to a different
// block from the current one.
const blocks = select( blockEditorStore ).getBlocks();
const firstOfSameType = findFirstOfSameType( blocks, blockName );
const blocksWithSameName = getBlocksByName( blockName );
const isInvalid =
firstOfSameType && firstOfSameType.clientId !== clientId;
return isInvalid ? firstOfSameType.clientId : false;
blocksWithSameName.length && blocksWithSameName[ 0 ] !== clientId;
return isInvalid ? blocksWithSameName[ 0 ] : false;
} );
}

Expand Down

0 comments on commit 276e906

Please sign in to comment.