diff --git a/src/edit.js b/src/edit.js index 4215118..3764c7d 100644 --- a/src/edit.js +++ b/src/edit.js @@ -18,16 +18,37 @@ export default function Edit({ clientId }) { select("core/block-editor").getBlock(clientId) ); + const [removedBlocks, setRemovedBlocks] = useState([]); const [count, setCount] = useState(innerBlocks.length); + const addBlock = () => { + const index = count; + + if (removedBlocks.length > 0) { + const block = removedBlocks[removedBlocks.length - 1]; + setRemovedBlocks(removedBlocks.slice(0, -1)); + dispatch("core/block-editor").insertBlock(block, index, clientId); + } else { + const orbiter = createBlock("red-block/red-orbiter"); + dispatch("core/block-editor").insertBlock(orbiter, index, clientId); + } + }; + + const removeBlock = () => { + const block = innerBlocks[count - 1]; + dispatch("core/block-editor").removeBlock(block.clientId, false); + + // append to removed blocks list + const removedBlocksUpdate = removedBlocks; + removedBlocksUpdate.push(block); + setRemovedBlocks(removedBlocksUpdate); + }; + const onCountChange = (value) => { if (value > count) { - const orbiter = createBlock("red-block/red-orbiter"); - const index = count; - dispatch("core/editor").insertBlock(orbiter, index, clientId); - } - if (value < count) { - // remove block and append to deleted blocks list + addBlock(); + } else if (value < count) { + removeBlock(); } setCount(value); }; @@ -84,7 +105,10 @@ export default function Edit({ clientId }) {
- +