Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when a block is duplicated

I want to give my blocks a unique ID that remains the same along post updates.

edit: class extends Component {
   constructor(props) {
      if(!props.blockID) this.props.setAttributes({ blockID: 'blk'+(new Date()).getTime() });
   }
}

But when the user duplicates de block, causes the ID being twice on the page.

I need some way to detect the duplication and give a new ID to the block.

Thanks.

like image 720
Albin Avatar asked Nov 07 '25 17:11

Albin


1 Answers

I hope this would help You

import { createHigherOrderComponent } from '@wordpress/compose';
import { useEffect } from '@wordpress/element';
import { simpleHash } from '../../helpers/simple-hash';
import { v1 as uuidv1 } from 'uuid';
import { select } from '@wordpress/data';
import { addFilter } from '@wordpress/hooks';

const isBlockIdReserved = ( blockId, clientId ) => {
    const blocksClientIds = select( 'core/block-editor' ).getClientIdsWithDescendants();
    return blocksClientIds.some( ( _clientId ) => {
        const { blockId: _blockId } = select( 'core/block-editor' ).getBlockAttributes( _clientId );
        return clientId !== _clientId && blockId === _blockId;
    } );
};

const addBlockEditAttributes = createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {
        const { attributes, setAttributes, clientId } = props;

        const {
            blockId,
        } = attributes;

        const setFreshBlockId = () => {
            const freshBlockId = simpleHash( uuidv1() );
            setAttributes( {
                blockId: freshBlockId,
            } );
        };

        useEffect( () => {
            if ( ! blockId ) {
                setFreshBlockId();
                return;
            }

            if ( isBlockIdReserved( blockId, clientId ) ) {
                // eslint-disable-next-line no-console
                console.log( `Block with id '${ blockId }' already exists. Regenerating...`, blockId );
                setFreshBlockId();
            }
        }, [ blockId ] );

        return <BlockEdit { ...props } />;
    };
}, 'addBlockEditAttributes' );



addFilter(
    'editor.BlockEdit',
    'my-plugin/add-block-edit-attributes',
    addBlockEditAttributes
);

like image 130
rootkowsky Avatar answered Nov 10 '25 15:11

rootkowsky