summaryrefslogtreecommitdiff
path: root/blockly/demos/blocklyfactory/block_exporter_tools.js
blob: 1396800a36024893fc6594b3de54d56b7040f9b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2016 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Javascript for the BlockExporter Tools class, which generates
 * block definitions and generator stubs for given block types. Also generates
 * toolbox xml for the exporter's workspace. Depends on the FactoryUtils for
 * its code generation functions.
 *
 * @author quachtina96 (Tina Quach)
 */
'use strict';

goog.provide('BlockExporterTools');

goog.require('FactoryUtils');
goog.require('BlockOption');
goog.require('goog.dom');
goog.require('goog.dom.xml');

/**
* Block Exporter Tools Class
* @constructor
*/
BlockExporterTools = function() {
  // Create container for hidden workspace.
  this.container = goog.dom.createDom('div', {
    'id': 'blockExporterTools_hiddenWorkspace'
  }, ''); // Empty quotes for empty div.
  // Hide hidden workspace.
  this.container.style.display = 'none';
  goog.dom.appendChild(document.body, this.container);
  /**
   * Hidden workspace for the Block Exporter that holds pieces that make
   * up the block
   * @type {Blockly.Workspace}
   */
  this.hiddenWorkspace = Blockly.inject(this.container.id,
      {collapse: false,
       media: '../../media/'});
};

/**
 * Get Blockly Block object from xml that encodes the blocks used to design
 * the block.
 * @private
 *
 * @param {!Element} xml - Xml element that encodes the blocks used to design
 *    the block. For example, the block xmls saved in block library.
 * @return {!Blockly.Block} - Root block (factory_base block) which contains
 *    all information needed to generate block definition or null.
 */
BlockExporterTools.prototype.getRootBlockFromXml_ = function(xml) {
  // Render xml in hidden workspace.
  this.hiddenWorkspace.clear();
  Blockly.Xml.domToWorkspace(xml, this.hiddenWorkspace);
  // Get root block.
  var rootBlock = this.hiddenWorkspace.getTopBlocks()[0] || null;
  return rootBlock;
};

/**
 * Return the given language code of each block type in an array.
 *
 * @param {!Object} blockXmlMap - Map of block type to xml.
 * @param {string} definitionFormat - 'JSON' or 'JavaScript'
 * @return {string} The concatenation of each block's language code in the
 *    desired format.
 */
BlockExporterTools.prototype.getBlockDefinitions =
    function(blockXmlMap, definitionFormat) {
  var blockCode = [];
  for (var blockType in blockXmlMap) {
    var xml = blockXmlMap[blockType];
    if (xml) {
      // Render and get block from hidden workspace.
      var rootBlock = this.getRootBlockFromXml_(xml);
      if (rootBlock) {
        // Generate the block's definition.
        var code = FactoryUtils.getBlockDefinition(blockType, rootBlock,
            definitionFormat, this.hiddenWorkspace);
        // Add block's definition to the definitions to return.
      } else {
        // Append warning comment and write to console.
        var code = '// No block definition generated for ' + blockType +
          '. Could not find root block in xml stored for this block.';
        console.log('No block definition generated for ' + blockType +
          '. Could not find root block in xml stored for this block.');
      }
    } else {
      // Append warning comment and write to console.
      var code = '// No block definition generated for ' + blockType +
        '. Block was not found in Block Library Storage.';
      console.log('No block definition generated for ' + blockType +
        '. Block was not found in Block Library Storage.');
    }
    blockCode.push(code);
  }
  return blockCode.join("\n\n");
};

/**
 * Return the generator code of each block type in an array in a given language.
 *
 * @param {!Object} blockXmlMap - Map of block type to xml.
 * @param {string} generatorLanguage - e.g.'JavaScript', 'Python', 'PHP', 'Lua',
 *     'Dart'
 * @return {string} The concatenation of each block's generator code in the
 * desired format.
 */
BlockExporterTools.prototype.getGeneratorCode =
    function(blockXmlMap, generatorLanguage) {
  var multiblockCode = [];
  // Define the custom blocks in order to be able to create instances of
  // them in the exporter workspace.
  this.addBlockDefinitions(blockXmlMap);

  for (var blockType in blockXmlMap) {
    var xml = blockXmlMap[blockType];
    if (xml) {
      // Render the preview block in the hidden workspace.
      var tempBlock =
          FactoryUtils.getDefinedBlock(blockType, this.hiddenWorkspace);
      // Get generator stub for the given block and add to  generator code.
      var blockGenCode =
          FactoryUtils.getGeneratorStub(tempBlock, generatorLanguage);
    } else {
      // Append warning comment and write to console.
      var blockGenCode = '// No generator stub generated for ' + blockType +
        '. Block was not found in Block Library Storage.';
      console.log('No block generator stub generated for ' + blockType +
        '. Block was not found in Block Library Storage.');
    }
    multiblockCode.push(blockGenCode);
  }
  return multiblockCode.join("\n\n");
};

/**
 * Evaluates block definition code of each block in given object mapping
 * block type to xml. Called in order to be able to create instances of the
 * blocks in the exporter workspace.
 *
 * @param {!Object} blockXmlMap - Map of block type to xml.
 */
BlockExporterTools.prototype.addBlockDefinitions = function(blockXmlMap) {
  var blockDefs = this.getBlockDefinitions(blockXmlMap, 'JavaScript');
  eval(blockDefs);
};

/**
 * Pulls information about all blocks in the block library to generate xml
 * for the selector workpace's toolbox.
 *
 * @param {!BlockLibraryStorage} blockLibStorage - Block Library Storage object.
 * @return {!Element} Xml representation of the toolbox.
 */
BlockExporterTools.prototype.generateToolboxFromLibrary
    = function(blockLibStorage) {
  // Create DOM for XML.
  var xmlDom = goog.dom.createDom('xml', {
    'id' : 'blockExporterTools_toolbox',
    'style' : 'display:none'
  });

  var allBlockTypes = blockLibStorage.getBlockTypes();
  // Object mapping block type to XML.
  var blockXmlMap = blockLibStorage.getBlockXmlMap(allBlockTypes);

  // Define the custom blocks in order to be able to create instances of
  // them in the exporter workspace.
  this.addBlockDefinitions(blockXmlMap);

  for (var blockType in blockXmlMap) {
    // Get block.
    var block = FactoryUtils.getDefinedBlock(blockType, this.hiddenWorkspace);
    var category = FactoryUtils.generateCategoryXml([block], blockType);
    xmlDom.appendChild(category);
  }

  // If there are no blocks in library and the map is empty, append dummy
  // category.
  if (Object.keys(blockXmlMap).length == 0) {
    var category = goog.dom.createDom('category');
    category.setAttribute('name','Next Saved Block');
    xmlDom.appendChild(category);
  }
  return xmlDom;
};

/**
 * Generate xml for the workspace factory's category from imported block
 * definitions.
 *
 * @param {!BlockLibraryStorage} blockLibStorage - Block Library Storage object.
 * @return {!Element} Xml representation of a category.
 */
BlockExporterTools.prototype.generateCategoryFromBlockLib =
    function(blockLibStorage) {
  var allBlockTypes = blockLibStorage.getBlockTypes();
  // Object mapping block type to XML.
  var blockXmlMap = blockLibStorage.getBlockXmlMap(allBlockTypes);

  // Define the custom blocks in order to be able to create instances of
  // them in the exporter workspace.
  this.addBlockDefinitions(blockXmlMap);

  // Get array of defined blocks.
  var blocks = [];
  for (var blockType in blockXmlMap) {
    var block = FactoryUtils.getDefinedBlock(blockType, this.hiddenWorkspace);
    blocks.push(block);
  }

  return FactoryUtils.generateCategoryXml(blocks,'Block Library');
};

/**
 * Generate selector dom from block library storage. For each block in the
 * library, it has a block option, which consists of a checkbox, a label,
 * and a fixed size preview workspace.
 *
 * @param {!BlockLibraryStorage} blockLibStorage - Block Library Storage object.
 * @param {!string} blockSelectorID - ID of the div element that will contain
 *    the block options.
 * @return {!Object} Map of block type to Block Option object.
 */
BlockExporterTools.prototype.createBlockSelectorFromLib =
    function(blockLibStorage, blockSelectorID) {
  // Object mapping each stored block type to XML.
  var allBlockTypes = blockLibStorage.getBlockTypes();
  var blockXmlMap = blockLibStorage.getBlockXmlMap(allBlockTypes);

  // Define the custom blocks in order to be able to create instances of
  // them in the exporter workspace.
  this.addBlockDefinitions(blockXmlMap);

  var blockSelector = goog.dom.getElement(blockSelectorID);
  // Clear the block selector.
  goog.dom.removeChildren(blockSelector);

  // Append each block option's dom to the selector.
  var blockOptions = Object.create(null);
  for (var blockType in blockXmlMap) {
    // Get preview block's xml.
    var block = FactoryUtils.getDefinedBlock(blockType, this.hiddenWorkspace);
    var previewBlockXml = Blockly.Xml.workspaceToDom(this.hiddenWorkspace);

    // Create block option, inject block into preview workspace, and append
    // option to block selector.
    var blockOpt = new BlockOption(blockSelector, blockType, previewBlockXml);
    blockOpt.createDom();
    goog.dom.appendChild(blockSelector, blockOpt.dom);
    blockOpt.showPreviewBlock();
    blockOptions[blockType] = blockOpt;
  }
  return blockOptions;
};