I would like to use code to clear a Blockly workspace, and in some cases overwrite with new Blockly XML. The issue I am facing, however, is that Workspace.clear()
moves current items to trash, which can be annoying when trying to reset a workspace, or overwrite it with blocks (which means clearing it first, as otherwise the current blocks would be overwritten). I have found that I am able to clear the trashcan with workspace.trashcan.contents = []
, but this results in some unexpected behaviour regarding the rendering of the lid, which appears slightly ajar despite it being empty.
Even if I could find a way to clear the trashcan, this would still result in clearing all previous items in there, while all I'm looking for is to do a single clear action without impacting the trashcan. I've tried looking at docs for Workspace.Clear
, but they don't seem to give any semantic way to do this. I've also tried looping through Workspace.getTopBlocks()
with Events.Delete
, but that also results in moving items to the trashcan.
I've also tried to implement a manual solution, something along the lines of:
const contentsBeforeClearing = workspace.trashcan.contents_;
workspace.clear();
workspace.trashcan.contents_ = contentsBeforeClearing;
For the first line, I've also tried Object.assign([], workspace.trashcan.contents_)
and workspace.trashcan.contents_.slice()
, but in all three cases (including the top one), the end result is equivalent to simply calling workspace.clear
. I'm guessing this is something to do with getter-setters manipulating contentsBeforeClearing
(as the variable's value has changed if you test it in the console after the clearing to have the deleted block(s)), but how to get around that is beyond me.
How can I clear the workspace without manipulating (not just resetting) trashcan contents?