0

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?

Geza Kerecsenyi
  • 1,127
  • 10
  • 27
  • I don't have enough time to set up a test case, but does this code work for you? const contentsBeforeClearing = workspace.undoStack_ ? workspace.undoStack_.slice() : []; workspace.clear(); workspace.undoStack_ = contentsBeforeClearing ? If not then my next inclination would be to try some XML-related shenanigans, but you might be better off making a feature request on the Github or asking around on the google group (https://groups.google.com/forum/#!forum/blockly) – Amber B. Jan 13 '20 at 14:03
  • 1
    @AmberB. thanks. Unfortunately, this seems to have the exact same issue: the bin still contains the items, and even though `contentsBeforeClearing` is both `const`ed and shallow cloned with `.slice`, the value appears to have mutated after running `workspace.clear()`: it seems that Blockly has some super-aggressive getter-setters in place. I'll try the dev forum: they've been pretty responsive in the past; I don't know why I didn't think of that this time. Thanks for the help! – Geza Kerecsenyi Jan 13 '20 at 20:45

0 Answers0