add/remove blocks

This commit is contained in:
Ray Elliott 2022-07-22 11:46:02 +01:00
parent 87afd2d60b
commit 15a57bfd9e
1 changed files with 31 additions and 7 deletions

View File

@ -18,16 +18,37 @@ export default function Edit({ clientId }) {
select("core/block-editor").getBlock(clientId) select("core/block-editor").getBlock(clientId)
); );
const [removedBlocks, setRemovedBlocks] = useState([]);
const [count, setCount] = useState(innerBlocks.length); 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) => { const onCountChange = (value) => {
if (value > count) { if (value > count) {
const orbiter = createBlock("red-block/red-orbiter"); addBlock();
const index = count; } else if (value < count) {
dispatch("core/editor").insertBlock(orbiter, index, clientId); removeBlock();
}
if (value < count) {
// remove block and append to deleted blocks list
} }
setCount(value); setCount(value);
}; };
@ -84,7 +105,10 @@ export default function Edit({ clientId }) {
</div> </div>
<div class="block-list"> <div class="block-list">
<InnerBlocks renderAppender={false} allowedBlocks={['red-block/red-orbiter']} /> <InnerBlocks
renderAppender={false}
allowedBlocks={["red-block/red-orbiter"]}
/>
</div> </div>
</div> </div>
</> </>