| 1 |
import { select } from '@wordpress/data'; |
| 2 |
export const handleUniqueId = ({ uniqueId, setAttributes, clientId }) => { |
| 3 |
const generateUniqueId = 'gut' + '-' + Math.random().toString(36).substr(2, 9); |
| 4 |
|
| 5 |
/** |
| 6 |
* Define and Generate Unique Block ID |
| 7 |
*/ |
| 8 |
if (!uniqueId) { |
| 9 |
setAttributes({ uniqueId: generateUniqueId }); |
| 10 |
return; |
| 11 |
} |
| 12 |
|
| 13 |
/** |
| 14 |
* Assign New Unique ID when duplicate uniqueId found |
| 15 |
* Mostly happens when User Duplicate a Block |
| 16 |
*/ |
| 17 |
|
| 18 |
const allBlocks = select('core/block-editor').getBlocks(); |
| 19 |
|
| 20 |
let duplicateFound = false; |
| 21 |
const fixDuplicateUniqueId = blocks => { |
| 22 |
if (duplicateFound) return; |
| 23 |
for (const item of blocks) { |
| 24 |
const { innerBlocks } = item; |
| 25 |
if (item.attributes.uniqueId === generateUniqueId) { |
| 26 |
if (item.clientId !== clientId) { |
| 27 |
setAttributes({ uniqueId: generateUniqueId }); |
| 28 |
duplicateFound = true; |
| 29 |
return; |
| 30 |
} else if (innerBlocks.length > 0) { |
| 31 |
fixDuplicateUniqueId(innerBlocks); |
| 32 |
} |
| 33 |
} else if (innerBlocks.length > 0) { |
| 34 |
fixDuplicateUniqueId(innerBlocks); |
| 35 |
} |
| 36 |
} |
| 37 |
}; |
| 38 |
|
| 39 |
fixDuplicateUniqueId(allBlocks); |
| 40 |
}; |
| 41 |
|