Skip to content

Commit

Permalink
fix: support xml serialized blocks in setContents() of workspace-back… (
Browse files Browse the repository at this point in the history
#1835)

* fix: support xml serialized blocks in setContents() of workspace-backpack

* fix: remove extraneous ! for block Xml string type workspace-backpack's blockXmlToJsonString()

* fix: dispose workspace at the end of blockXmlToJsonString() in workspace-backpack
  • Loading branch information
johnnyoshika authored Aug 2, 2023
1 parent 1bc6714 commit 43718ce
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion plugins/workspace-backpack/src/backpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,29 @@ export class Backpack extends Blockly.DragTarget {
return JSON.stringify(json);
}

/**
* Converts serialized XML to its equivalent serialized JSON string
* @param {string} blockXml The XML serialized block.
* @returns {string} The JSON object as a string.
* @private
*/
blockXmlToJsonString(blockXml) {
if (!blockXml.startsWith('<block')) {
throw new Error('Unrecognized XML format');
}

const workspace = new Blockly.Workspace();
try {
const block = Blockly.Xml.domToBlock(
Blockly.utils.xml.textToDom(blockXml),
workspace,
);
return this.blockToJsonString(block);
} finally {
workspace.dispose();
}
}

/**
* Returns whether the backpack contains a duplicate of the provided Block.
* @param {!Blockly.Block} block The block to check.
Expand Down Expand Up @@ -574,7 +597,12 @@ export class Backpack extends Blockly.DragTarget {
*/
setContents(contents) {
this.contents_ = [];
this.contents_ = this.filterDuplicates_(contents);
this.contents_ = this.filterDuplicates_(
// Support XML serialized content for backwards compatiblity: https://github.com/google/blockly-samples/issues/1827
contents.map((content) => content.startsWith('<block') ?
this.blockXmlToJsonString(content) :
content)
);
this.onContentChange_();
}

Expand Down

0 comments on commit 43718ce

Please sign in to comment.