diff --git a/demos/blockfactory/app_controller.js b/demos/blockfactory/app_controller.js index baf106ac7..ac69780b2 100644 --- a/demos/blockfactory/app_controller.js +++ b/demos/blockfactory/app_controller.js @@ -199,7 +199,9 @@ AppController.prototype.formatBlockLibraryForImport_ = function(xmlText) { xmlText = Blockly.Xml.domToText(xmlDom); // All block types should be lowercase. var blockType = this.getBlockTypeFromXml_(xmlText).toLowerCase(); - + // Some names are invalid so fix them up. + blockType = FactoryUtils.cleanBlockType(blockType); + blockXmlTextMap[blockType] = xmlText; } diff --git a/demos/blockfactory/block_library_controller.js b/demos/blockfactory/block_library_controller.js index fc5398c8c..1066ab127 100644 --- a/demos/blockfactory/block_library_controller.js +++ b/demos/blockfactory/block_library_controller.js @@ -64,8 +64,8 @@ BlockLibraryController = function(blockLibraryName, opt_blockLibraryStorage) { BlockLibraryController.prototype.getCurrentBlockType = function() { var rootBlock = FactoryUtils.getRootBlock(BlockFactory.mainWorkspace); var blockType = rootBlock.getFieldValue('NAME').trim().toLowerCase(); - // Replace white space with underscores - return blockType.replace(/\W/g, '_').replace(/^(\d)/, '_\\1'); + // Replace invalid characters. + return FactoryUtils.cleanBlockType(blockType); }; /** diff --git a/demos/blockfactory/factory_utils.js b/demos/blockfactory/factory_utils.js index 89495d4ce..5da02f9c4 100644 --- a/demos/blockfactory/factory_utils.js +++ b/demos/blockfactory/factory_utils.js @@ -44,7 +44,7 @@ goog.provide('FactoryUtils'); * @return {string} Block definition. */ FactoryUtils.getBlockDefinition = function(blockType, rootBlock, format, workspace) { - blockType = blockType.replace(/\W/g, '_').replace(/^(\d)/, '_\\1'); + blockType = FactoryUtils.cleanBlockType(blockType); switch (format) { case 'JSON': var code = FactoryUtils.formatJson_(blockType, rootBlock); @@ -56,6 +56,19 @@ FactoryUtils.getBlockDefinition = function(blockType, rootBlock, format, workspa return code; }; +/** + * Convert invalid block name to a valid one. Replaces whitespace + * and prepend names that start with a digit with an '_'. + * @param {string} blockType Type of block. + * @return {string} Cleaned up block type. + */ +FactoryUtils.cleanBlockType = function(blockType) { + if (!blockType) { + return ''; + } + return blockType.replace(/\W/g, '_').replace(/^(\d)/, '_$1'); +}; + /** * Get the generator code for a given block. * @param {!Blockly.Block} block Rendered block in preview workspace.