feat: add block factory export in json (#8051)

This commit is contained in:
Maribeth Bottorff
2024-04-29 16:41:09 -07:00
committed by GitHub
parent 5a5184ab4f
commit da97e782c4
3 changed files with 40 additions and 0 deletions

View File

@@ -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',

View File

@@ -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.

View File

@@ -339,6 +339,9 @@
<button id="localSaveButton" title="Save block library XML to a local file.">
<span>Download Block Library</span>
</button>
<button id="exportAsJson" title="Export block library for import into the new Block Factory.">
<span>Export Block Library</span>
</button>
</td>
</tr>
</table>