diff --git a/demos/blockfactory/app_controller.js b/demos/blockfactory/app_controller.js index 5698033fe12..fcfa2296dcf 100644 --- a/demos/blockfactory/app_controller.js +++ b/demos/blockfactory/app_controller.js @@ -126,6 +126,16 @@ AppController.prototype.exportBlockLibraryToFile = function() { } }; +AppController.prototype.exportBlockLibraryAsJson = function() { + const blockJson = this.blockLibraryController.getBlockLibraryAsJson(); + if (blockJson.length === 0) { + alert('No blocks in library to export'); + return; + } + const filename = 'legacy_block_factory_export.txt'; + FactoryUtils.createAndDownloadFile(JSON.stringify(blockJson), filename, 'plain'); +}; + /** * Converts an object mapping block type to XML to text file for output. * @param {!Object} blockXmlMap Object mapping block type to XML. @@ -491,6 +501,10 @@ AppController.prototype.assignBlockFactoryClickHandlers = function() { self.exportBlockLibraryToFile(); }); + document.getElementById('exportAsJson').addEventListener('click', function() { + self.exportBlockLibraryAsJson(); + }); + document.getElementById('helpButton').addEventListener('click', function() { open('https://developers.google.com/blockly/custom-blocks/block-factory', diff --git a/demos/blockfactory/block_library_controller.js b/demos/blockfactory/block_library_controller.js index 2192a7bdd11..7bb34e8d623 100644 --- a/demos/blockfactory/block_library_controller.js +++ b/demos/blockfactory/block_library_controller.js @@ -173,6 +173,29 @@ BlockLibraryController.prototype.getBlockLibrary = function() { return this.storage.getBlockXmlTextMap(); }; +/** + * @return {Object[]} Array of JSON data, where each item is the data for one block type. + */ +BlockLibraryController.prototype.getBlockLibraryAsJson = function() { + const xmlBlocks = this.storage.getBlockXmlMap(this.storage.getBlockTypes()); + const jsonBlocks = []; + const headlessWorkspace = new Blockly.Workspace(); + + for (const blockName in xmlBlocks) { + // Load the block XML into a workspace so we can save it as JSON + headlessWorkspace.clear(); + const blockXml = xmlBlocks[blockName]; + Blockly.Xml.domToWorkspace(blockXml, headlessWorkspace); + const block = headlessWorkspace.getBlocksByType('factory_base', false)[0]; + + if (!block) continue; + + const json = Blockly.serialization.blocks.save(block, {addCoordinates: false, saveIds: false}); + jsonBlocks.push(json); + } + return jsonBlocks; +} + /** * Return stored XML of a given block type. * @param {string} blockType The type of block. diff --git a/demos/blockfactory/index.html b/demos/blockfactory/index.html index 9f33aa4fbc4..c72efb7faf7 100644 --- a/demos/blockfactory/index.html +++ b/demos/blockfactory/index.html @@ -339,6 +339,9 @@