Files
blockly/demos/blockfactory/factory_utils.js
Rachel Fenichel 3ca7bcc3df Develop to master (#1209)
* Adding new minimap demo

* Basic code style changes. Adding a few more comments. Return early if disableScrollChange in onScrollChange listener.

* Adding horizontal scrolling. Changed scroll change callbacks from onScroll_ to setHandlePosition. onScroll_ is not challed when workspace is dragged.

* Registering mousemove and mouseup listener in mousedown event. Mousemove and Mouseup events are now listening over document.

* Adding the remove variable modal and functionality to accessible Blockly. (#1011)

* Minimap position bug fix for browsers other than chrome. Added touch support.

* Adding an add variable modal to accessible Blockly. (#1015)

* Adding the remove variable modal and functionality to accessible Blockly.

* Adding the add variable modal for accessible Blockly.

* Block browser context menu in the toolbox and flyout

* Add links to the dev registration form and contributor guidelines

* Miscellaneous comment cleanup

* Adding the common modal class. (#1017)

Centralizes accessible modal behavior.

* - Changed error message referencing 'procedure' instead of 'function' (#1019)

- Added iOS specific UI messages
- Fixed bug with js_to_json.py script where it didn't recognize ' character

* - Allows use of Blockly's messaging format for category name, colour,… (#1028)

...in toolbox XML.
- Updated code editor demo to use this message format
- Re-built blockly_compressed.js

* Making text_count use a text color (like text_length, which also returns a number). (#1027)

* Enable google/blockly with continuous build on travis ci (#1023) (#1035)

* create .travis for ci job

* initial checkin for blocky-web travis ci job

* rename file to .travis.yaml for typo

* remove after_script

* added cache

* rename .travis.yaml to .travis.yml

* Update .travis.yml

* include build script

* fix yaml file format issue

* debug install part

* debug build issue

* Update .travis.yml

* remove cache for now

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* more debug info

* Update .travis.yml

* Update .travis.yml

* fix typo

* installing chrome browser

* remove chrome setting config

* run build.py as part of npm install

* Update .travis.yml

* update karma dependency

* use karma as test runner

* fix typo

* remove karma test for now

* Update .travis.yml

* Update package.json

* add npm test target

* add browserstack-runner depdendency

* update browser support

* fix typo for test target

* fix chrome typo

* added closure dependency

* add google-closure-library

* include blockly_uncompressed.js and core.js dependency

* uncomment out core/*.js files

* add kama job as part of install

* remove browserstack add on for now

* fix karma config typo

* add karma-closure

* add os support

* remove typo config

* include more closure files

* change os back to linux

* use closure-library from node_modules

* change log level back to INFO

* change npm test target to use open browser command instead of karma

* change travis test target to use open command instead of karma

* list current directory

* find what's in current dir

* typo command

* Update .travis.yml

* typo again

* open right index.html

* use right path for index.html

* xdg-open to open default browser on travis

* exit browser after 5s wait

* change timeout to 1 min

* exit after opening up browser

* use browser only

* use karma

* remove un-needed dependency

* clean up script section

* fix typo

* update build status on readme

* initial commit for selenium integration tests

* update selenium jar path

* fix test_runner.js typo

* add more debug info

* check java version

* add && instead of 9288

* fix java path

* add logic to check if selenium is running or not

* add some deugging info

* initial commit to get chromedriver

* add chromedriver flag

* add get_chromedriver.sh to package.json and .travel

* change browser to chrome for now

* fix path issue

* update chromdriver path

* fix path issue again

* more debugging

* add debug msg

* fix typo

* minor fix for getting chromedriver

* install latest chrome browser

* clean up pakcage.json

* use npm target for test run

* remove removing trailing comma

* fix another trailing comma

* updated travis test target

* clean up scripts

* not sure nmp run preinstall

* redirect selenium log to tmp file

* revert writing console log to file

* update test summary

* more clean up

* minor clean up before pull request

* resolved closure-library conflict

1. add closure-library to dependencies instead of devDependencies.
2. add lint back in scripts block

* fix typo (adding comma) in script section

* Renames Blockly.workspaceDragSurface to Blockly.WorkspaceDragSurface.

Fixes #880.

* Ensure useDragSurface is a boolean.

Fixed #988

* use pretest instead of preinstall in package.json (#1043)

* cherry pick for pretest fix

* put pretest target to test_setup.sh

* fix conflict

* cherry pick for get_chromedriver.sh

* add some sleep to wait download to finish

* use node.js stable

* use npm test target

* field_angle renders degree symbol consistently.

Fixes #973

* bumpNeighbours_ function moved to block_svg.

Fixed #1009

* Update RegEx in js-to-json to match windowi eol (#1050)

The current regex only works with the "\n" line endings as it expects no characters after the optional ";" at the end of the line. In windows, if it adds the "\r" it counts as a characters and is not part of the line terminator so it doesn't match.

* Fix French translation of "colour with rgb" block (#1053)

"colorier", which is currently used, is a verb and proposed "couleur" is
a noun: the block in question does not change colour of anything, it
creates new colour instead, thus noun is more applicable.

Also, noun is used in French translation of "random colour" block:
"couleur aléatoire".

* Enforcing non-empty names on value inputs and statement inputs. (#1054)

* Correcting #1054 (#1056)

single quotes. better logic.

* Created a variable model with name, id, and type.

Created a jsunit test file for variable model.

* Change how blockly handles cursors.  The old way was quite slow becau… (#1057)

* Change how blockly handles cursors.  The old way was quite slow because it changed the stylesheet directly.  See issue #981 for more details on implementation and tradeoffs.  This changes makes the following high level changes: deprecate Blockly.Css.setCursor, use built in open and closed hand cursor instead of custom .cur files, add css to draggable objects to set the open and closed hand cursors.

* Rebuild blockly_uncompressed to pick up a testing change to make travis happy.  Fix a build warning from a multi-line string in the process. (#1059)

* Merge master into develop (#1063)

- pick up translation changes
- clean up trailing spaces

* use goog.string.startswith instead of string.startswith (#1065)

* New jsinterpreter demo includes wait block. Both demos have improved UI for clarity. (#1001)

Refactor of interpreter demo
 * Renamed demos/interpreter/index.html as demos/interpreter/step-execution.html (including redirect), and added demos/interpreter/async-execution.html.
 * Refactored code to automatically generate/parse the blocks, eliminating the need for a "Parse JavaScript" button. Code is still shown in alert upon stepping to the first statement. Print statements now write to output <textarea> instead of modal dialogs.

* VariableMap and functions added.

* Create separate file for VariableMap and its functions.

* Fix #1069 (#1073)

* VariableMap and functions added.

* Fix #1051 (#1084)

* Improve errors when validating JSON block definitions. (#1086)

goog.asserts to not run from blockly_compressed.js. User data validation should always run.

* Dragging changes, rebased on develop (#1078)

* Add block drag surface translateSurfaceBy

* Add dragged connection manager

* Add gesture.js

* Add GestureHandler

* Implemented gesture skeleton

* Most basic workspace dragging

* Add dragged connection manager

* cleanup

* doc

* more cleanup

* Add gesture handler

* Add translateSurfaceInternal

* core/block_dragger.js

* cleanup

* Pull in changes to dragged connection manager

* Pull in changes to dragged connection manager

* comments

* more annotations

* Add workspace dragger

* Add coordinate annotations

* Start on block dragging

* Limit number of concurrent gestures

* Add some TODOs

* start using dragged connection manager

* Set origin correctly for dragging blocks

* Connect or delete at the end of a block drag.

* cleanup

* handle field clicks and block + workspace right-clicks

* move code into BlockDragger class, but still reach into Gesture internals a lot

* Clean up block dragger

* Call blockDragger constructor with correct arguments

* Enable block dragging in a mutator workspace

* Add workspace dragger

* click todos

* Drag flyout with background

* more dragging from flyout

* nit

* fix dragging from flyouts

* Remove unused code and rename gestureHandler to gestureDB

* Rename gesture handler

* Added some jsdoc in gesture.js

* Update some docs

* Move some code to block_svg and clean up code

* Lots of coordinate annotations

* Fix block dragging when zoomed.

* Remove built files from branch

* More dragging work (#1026)

-- Drag bubbles while dragging blocks
-- Use bindEventWithChecks to work in touch on Android. Not tested anywhere else yet.
-- Handle dragging blocks while zoomed
-- Handle dragging blocks in mutators
-- Handle right-clicks (I hope)
-- Removed lots of unused code

* More dragging work (#1048)

- Removed gestureDB
- Removing uses of terminateDrag
- Cleaned up disposal code

* Dragging bugfixes (#1058)

- Get rid of flyout.dragMode_ and blockly.dragMode_
- Make drags from the flyout start from the top block in the group
- Block tooltips from being scheduled or shown during gestures
- Don't resize mutator bubbles mid-drag

* Fix events in new dragging (#1060)

* rebuild for testing

* unbuild

* Fix events

* rebuild

* Fix up cursors

* Use language files from develop

* Remove handled TODOS

* attempt to fix IE rerendering bug, and recalculate workspace positions on scroll

* Rebuild all the things

* Comment cleanup; annotations; delete unused variables.

* Tidy up context menu code. (#1081)

* add osx travis test run job (#1074)

* Names are correctly fetched from VariableModels!

* add more wait time for test setup (#1091)

* Work around timing issue with travis osx issue (#1092)

* add more wait time for test setup

* increase selenium wait time

* add more wait

* Fix #1077 by adding a rule to cover the toolbox labels too. (#1099)

* Assign variable UUID to field_variable dropdown.

* Change registration link to a static one (#1106)

This lets us redirect to a different form if we change it in the future.

* Edit generators to read in Variable Models.

* Add VariableMap requirement to workspace.

* Changed parameter name in workspace for clarity.

* Add type, id, and info to the generated xml.

Add xml tests for fieldToDom.
Update workspace tests to pass with new changes.

* Fix apostrophe in tooltips and helpurls (#1111)

* Click events on shadow blocks have the correct id (#1089)

* Add image_onclick option (#1080)

* Cleanup: semicolons, spacing, etc. (#1116)

* Spelling.  Spelling is hard.

* Add variable info to xml generated in variables.js

* Add missing CLAs info to the contributing file (#1119)

* Add missing CLAs info to the contributing file

* Added larger changes paragraph

* Replacing latest prettifier hosted in repo with latest version at rawgit CDN. (#1120)

* Forgot update code demo (#1121)

* Move audio code to a new file (#1122)

* move audio code to a new file

* dispose

* null check

* Make flyout get variables from target workspace's variableMap.

* Require VariableModel in field_variable.js.

* Update contributing.md (#1126)

* Include variables at top of serialization.

* Move blockSvg.getHeightWidth to block_render_svg.js (#1118)

* Deserialization variables at top.

* Create grid object (#1131)

* Create grid object

* Doc

* Units!  Thanks @RoboErikG

* Appease eslint: semicolons and such.

* Deserialization variables at top.

* Setting up accessible Blockly for Closure compilation. (#1134)

Moving closure compilation into the build file.

Fixing up goog.requires for accessible blockly. Adding accessible to the build script.

* Fix #1109

* Adding command-line options to the buildscript. (#1136)

* Fix for travis-ci testing failure (#1141)

It looks like the default configuration for Travis might have changed. Adding a manual step to install webdriverio.

* Convert text_join block to JSON + mutator format (#1140)

* Clean up and create test utilities file.

* Add BLOCK events and constructor tests.

* Convert more text blocks to json (#1147)

* Convert more text blocks to json

Converts the mutator blocks for text_join and the text_append block
to JSON format.

* Fixing modals so they're announced on focus, and changing variables t… (#1030)

* Fixing modals so they're announced on focus, and changing variables to only react to enter, not onChange.

* Adding a temp index.

* Whoops - added it in the wrong spot.

* Adding automatically-generated variable lists to the accessible toolbox. (#1149)

Fixing a bug with the core-only uncompressed file not finding its own directory.

* Field Variable setValue() looks up variable.

* Wrap Error in Try Finally Block.

* Changing the build file to allow forced rebuilding of the msg files. (#1158)

* Split flyout into flyout_base, flyout_horizontal, and flyou_vertical

* Rename flyout to flyout_base

* flyout_base minus horizontal and vertical code

* Add flyout_vertical and flyout_horizontal

* review fixes + toolbox and workspace use

* Fix hat block case

* rebuild uncompressed

* Fix travis problem

* Fix build problem

* Add VAR events.

* Correctly named block events called.

* Fire VAR events and test.

* Create utility function for checking variable values.

* In DropdownCreate check for Msg.DELETE_VARIABLE.

* Test Delete Variable Twice.

* Convert more text blocks to JSON format (#1163)

* Convert more text blocks to JSON format

Converts text_charAt, text_indexOf, text_isEmpty, and text_length
to JSON.

Includes a rebuild to pick up message changes.

* Fixing the accessible variable stuff so it interacts correctly with (#1170)

variableMap.

* createVariable in workspaceSvg takes in id and type.

* Followup RefreshToolbox.

* Fixing an error with block messages and ordering. (#1171)

* Remove out of date todo comments.

* Fix checkbox delete bug.

* Fixing variable dropdowns so they select the correct option. (#1184)

* Always open flyout fields are editable.

* Fixing the tree service so it doesn't treat unknown block deletion (#1182)

as an error, and turning off keypresses on the workspace when the
variable modals are open.

* Revamping mostly gesture tests.

* Merge master to develop (#1189)



* Merge master into develop (#1063)

- pick up translation changes
- clean up trailing spaces

* Rebuild for translations

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Cherrypick a fix for #1069 and rebuild (#1075)

* Fix #1069 (#1073)

* rebuild

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Localisation updates from https://translatewiki.net.

* Rebuild compressed files

* Add some translatewiki annotations back into msg/messages.js

* Rebuild msg files

* Fix flyout dropdown bug.

* Fix python and php procedures.

* Dropdown Create does not create a missing variable twice.

* Fire field variable change event with variable value, not name.

* Fix #1160 (#1197)

Fix "Connection UI Effect not playing on block connect"

* Only add a block in the flyout if it is not disabled (#1204)

* Only add a block in the flyout if it is not disabled

* PR feedback

* remove previous fix

* Fix issue with compression stripping dropdown options (#1207)

* Get some accessible files back from develop

* rebuild
2017-06-30 16:50:04 -07:00

1000 lines
34 KiB
JavaScript

/**
* @license
* Blockly Demos: Block Factory
*
* 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 FactoryUtils is a namespace that holds block starter code
* generation functions shared by the Block Factory, Workspace Factory, and
* Exporter applications within Blockly Factory. Holds functions to generate
* block definitions and generator stubs and to create and download files.
*
* @author fraser@google.com (Neil Fraser), quachtina96 (Tina Quach)
*/
'use strict';
/**
* Namespace for FactoryUtils.
*/
goog.provide('FactoryUtils');
/**
* Get block definition code for the current block.
* @param {string} blockType Type of block.
* @param {!Blockly.Block} rootBlock RootBlock from main workspace in which
* user uses Block Factory Blocks to create a custom block.
* @param {string} format 'JSON' or 'JavaScript'.
* @param {!Blockly.Workspace} workspace Where the root block lives.
* @return {string} Block definition.
*/
FactoryUtils.getBlockDefinition = function(blockType, rootBlock, format, workspace) {
blockType = FactoryUtils.cleanBlockType(blockType);
switch (format) {
case 'JSON':
var code = FactoryUtils.formatJson_(blockType, rootBlock);
break;
case 'JavaScript':
var code = FactoryUtils.formatJavaScript_(blockType, rootBlock, workspace);
break;
}
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.
* @param {string} generatorLanguage 'JavaScript', 'Python', 'PHP', 'Lua',
* 'Dart'.
* @return {string} Generator code for multiple blocks.
*/
FactoryUtils.getGeneratorStub = function(block, generatorLanguage) {
function makeVar(root, name) {
name = name.toLowerCase().replace(/\W/g, '_');
return ' var ' + root + '_' + name;
}
// The makevar function lives in the original update generator.
var language = generatorLanguage;
var code = [];
code.push("Blockly." + language + "['" + block.type +
"'] = function(block) {");
// Generate getters for any fields or inputs.
for (var i = 0, input; input = block.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
var name = field.name;
if (!name) {
continue;
}
if (field instanceof Blockly.FieldVariable) {
// Subclass of Blockly.FieldDropdown, must test first.
code.push(makeVar('variable', name) +
" = Blockly." + language +
".variableDB_.getName(block.getFieldValue('" + name +
"'), Blockly.Variables.NAME_TYPE);");
} else if (field instanceof Blockly.FieldAngle) {
// Subclass of Blockly.FieldTextInput, must test first.
code.push(makeVar('angle', name) +
" = block.getFieldValue('" + name + "');");
} else if (Blockly.FieldDate && field instanceof Blockly.FieldDate) {
// Blockly.FieldDate may not be compiled into Blockly.
code.push(makeVar('date', name) +
" = block.getFieldValue('" + name + "');");
} else if (field instanceof Blockly.FieldColour) {
code.push(makeVar('colour', name) +
" = block.getFieldValue('" + name + "');");
} else if (field instanceof Blockly.FieldCheckbox) {
code.push(makeVar('checkbox', name) +
" = block.getFieldValue('" + name + "') == 'TRUE';");
} else if (field instanceof Blockly.FieldDropdown) {
code.push(makeVar('dropdown', name) +
" = block.getFieldValue('" + name + "');");
} else if (field instanceof Blockly.FieldNumber) {
code.push(makeVar('number', name) +
" = block.getFieldValue('" + name + "');");
} else if (field instanceof Blockly.FieldTextInput) {
code.push(makeVar('text', name) +
" = block.getFieldValue('" + name + "');");
}
}
var name = input.name;
if (name) {
if (input.type == Blockly.INPUT_VALUE) {
code.push(makeVar('value', name) +
" = Blockly." + language + ".valueToCode(block, '" + name +
"', Blockly." + language + ".ORDER_ATOMIC);");
} else if (input.type == Blockly.NEXT_STATEMENT) {
code.push(makeVar('statements', name) +
" = Blockly." + language + ".statementToCode(block, '" +
name + "');");
}
}
}
// Most languages end lines with a semicolon. Python does not.
var lineEnd = {
'JavaScript': ';',
'Python': '',
'PHP': ';',
'Dart': ';'
};
code.push(" // TODO: Assemble " + language + " into code variable.");
if (block.outputConnection) {
code.push(" var code = '...';");
code.push(" // TODO: Change ORDER_NONE to the correct strength.");
code.push(" return [code, Blockly." + language + ".ORDER_NONE];");
} else {
code.push(" var code = '..." + (lineEnd[language] || '') + "\\n';");
code.push(" return code;");
}
code.push("};");
return code.join('\n');
};
/**
* Update the language code as JSON.
* @param {string} blockType Name of block.
* @param {!Blockly.Block} rootBlock Factory_base block.
* @return {string} Generanted language code.
* @private
*/
FactoryUtils.formatJson_ = function(blockType, rootBlock) {
var JS = {};
// Type is not used by Blockly, but may be used by a loader.
JS.type = blockType;
// Generate inputs.
var message = [];
var args = [];
var contentsBlock = rootBlock.getInputTargetBlock('INPUTS');
var lastInput = null;
while (contentsBlock) {
if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) {
var fields = FactoryUtils.getFieldsJson_(
contentsBlock.getInputTargetBlock('FIELDS'));
for (var i = 0; i < fields.length; i++) {
if (typeof fields[i] == 'string') {
message.push(fields[i].replace(/%/g, '%%'));
} else {
args.push(fields[i]);
message.push('%' + args.length);
}
}
var input = {type: contentsBlock.type};
// Dummy inputs don't have names. Other inputs do.
if (contentsBlock.type != 'input_dummy') {
input.name = contentsBlock.getFieldValue('INPUTNAME');
}
var check = JSON.parse(
FactoryUtils.getOptTypesFrom(contentsBlock, 'TYPE') || 'null');
if (check) {
input.check = check;
}
var align = contentsBlock.getFieldValue('ALIGN');
if (align != 'LEFT') {
input.align = align;
}
args.push(input);
message.push('%' + args.length);
lastInput = contentsBlock;
}
contentsBlock = contentsBlock.nextConnection &&
contentsBlock.nextConnection.targetBlock();
}
// Remove last input if dummy and not empty.
if (lastInput && lastInput.type == 'input_dummy') {
var fields = lastInput.getInputTargetBlock('FIELDS');
if (fields && FactoryUtils.getFieldsJson_(fields).join('').trim() != '') {
var align = lastInput.getFieldValue('ALIGN');
if (align != 'LEFT') {
JS.lastDummyAlign0 = align;
}
args.pop();
message.pop();
}
}
JS.message0 = message.join(' ');
if (args.length) {
JS.args0 = args;
}
// Generate inline/external switch.
if (rootBlock.getFieldValue('INLINE') == 'EXT') {
JS.inputsInline = false;
} else if (rootBlock.getFieldValue('INLINE') == 'INT') {
JS.inputsInline = true;
}
// Generate output, or next/previous connections.
switch (rootBlock.getFieldValue('CONNECTIONS')) {
case 'LEFT':
JS.output =
JSON.parse(
FactoryUtils.getOptTypesFrom(rootBlock, 'OUTPUTTYPE') || 'null');
break;
case 'BOTH':
JS.previousStatement =
JSON.parse(
FactoryUtils.getOptTypesFrom(rootBlock, 'TOPTYPE') || 'null');
JS.nextStatement =
JSON.parse(
FactoryUtils.getOptTypesFrom(rootBlock, 'BOTTOMTYPE') || 'null');
break;
case 'TOP':
JS.previousStatement =
JSON.parse(
FactoryUtils.getOptTypesFrom(rootBlock, 'TOPTYPE') || 'null');
break;
case 'BOTTOM':
JS.nextStatement =
JSON.parse(
FactoryUtils.getOptTypesFrom(rootBlock, 'BOTTOMTYPE') || 'null');
break;
}
// Generate colour.
var colourBlock = rootBlock.getInputTargetBlock('COLOUR');
if (colourBlock && !colourBlock.disabled) {
var hue = parseInt(colourBlock.getFieldValue('HUE'), 10);
JS.colour = hue;
}
JS.tooltip = FactoryUtils.getTooltipFromRootBlock_(rootBlock);
JS.helpUrl = FactoryUtils.getHelpUrlFromRootBlock_(rootBlock);
return JSON.stringify(JS, null, ' ');
};
/**
* Update the language code as JavaScript.
* @param {string} blockType Name of block.
* @param {!Blockly.Block} rootBlock Factory_base block.
* @param {!Blockly.Workspace} workspace Where the root block lives.
* @return {string} Generated language code.
* @private
*/
FactoryUtils.formatJavaScript_ = function(blockType, rootBlock, workspace) {
var code = [];
code.push("Blockly.Blocks['" + blockType + "'] = {");
code.push(" init: function() {");
// Generate inputs.
var TYPES = {'input_value': 'appendValueInput',
'input_statement': 'appendStatementInput',
'input_dummy': 'appendDummyInput'};
var contentsBlock = rootBlock.getInputTargetBlock('INPUTS');
while (contentsBlock) {
if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) {
var name = '';
// Dummy inputs don't have names. Other inputs do.
if (contentsBlock.type != 'input_dummy') {
name =
JSON.stringify(contentsBlock.getFieldValue('INPUTNAME'));
}
code.push(' this.' + TYPES[contentsBlock.type] + '(' + name + ')');
var check = FactoryUtils.getOptTypesFrom(contentsBlock, 'TYPE');
if (check) {
code.push(' .setCheck(' + check + ')');
}
var align = contentsBlock.getFieldValue('ALIGN');
if (align != 'LEFT') {
code.push(' .setAlign(Blockly.ALIGN_' + align + ')');
}
var fields = FactoryUtils.getFieldsJs_(
contentsBlock.getInputTargetBlock('FIELDS'));
for (var i = 0; i < fields.length; i++) {
code.push(' .appendField(' + fields[i] + ')');
}
// Add semicolon to last line to finish the statement.
code[code.length - 1] += ';';
}
contentsBlock = contentsBlock.nextConnection &&
contentsBlock.nextConnection.targetBlock();
}
// Generate inline/external switch.
if (rootBlock.getFieldValue('INLINE') == 'EXT') {
code.push(' this.setInputsInline(false);');
} else if (rootBlock.getFieldValue('INLINE') == 'INT') {
code.push(' this.setInputsInline(true);');
}
// Generate output, or next/previous connections.
switch (rootBlock.getFieldValue('CONNECTIONS')) {
case 'LEFT':
code.push(FactoryUtils.connectionLineJs_('setOutput', 'OUTPUTTYPE', workspace));
break;
case 'BOTH':
code.push(
FactoryUtils.connectionLineJs_('setPreviousStatement', 'TOPTYPE', workspace));
code.push(
FactoryUtils.connectionLineJs_('setNextStatement', 'BOTTOMTYPE', workspace));
break;
case 'TOP':
code.push(
FactoryUtils.connectionLineJs_('setPreviousStatement', 'TOPTYPE', workspace));
break;
case 'BOTTOM':
code.push(
FactoryUtils.connectionLineJs_('setNextStatement', 'BOTTOMTYPE', workspace));
break;
}
// Generate colour.
var colourBlock = rootBlock.getInputTargetBlock('COLOUR');
if (colourBlock && !colourBlock.disabled) {
var hue = parseInt(colourBlock.getFieldValue('HUE'), 10);
if (!isNaN(hue)) {
code.push(' this.setColour(' + hue + ');');
}
}
var tooltip = FactoryUtils.getTooltipFromRootBlock_(rootBlock);
var helpUrl = FactoryUtils.getHelpUrlFromRootBlock_(rootBlock);
code.push(' this.setTooltip(' + JSON.stringify(tooltip) + ');');
code.push(' this.setHelpUrl(' + JSON.stringify(helpUrl) + ');');
code.push(' }');
code.push('};');
return code.join('\n');
};
/**
* Create JS code required to create a top, bottom, or value connection.
* @param {string} functionName JavaScript function name.
* @param {string} typeName Name of type input.
* @param {!Blockly.Workspace} workspace Where the root block lives.
* @return {string} Line of JavaScript code to create connection.
* @private
*/
FactoryUtils.connectionLineJs_ = function(functionName, typeName, workspace) {
var type = FactoryUtils.getOptTypesFrom(
FactoryUtils.getRootBlock(workspace), typeName);
if (type) {
type = ', ' + type;
} else {
type = '';
}
return ' this.' + functionName + '(true' + type + ');';
};
/**
* Returns field strings and any config.
* @param {!Blockly.Block} block Input block.
* @return {!Array.<string>} Field strings.
* @private
*/
FactoryUtils.getFieldsJs_ = function(block) {
var fields = [];
while (block) {
if (!block.disabled && !block.getInheritedDisabled()) {
switch (block.type) {
case 'field_static':
// Result: 'hello'
fields.push(JSON.stringify(block.getFieldValue('TEXT')));
break;
case 'field_input':
// Result: new Blockly.FieldTextInput('Hello'), 'GREET'
fields.push('new Blockly.FieldTextInput(' +
JSON.stringify(block.getFieldValue('TEXT')) + '), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_number':
// Result: new Blockly.FieldNumber(10, 0, 100, 1), 'NUMBER'
var args = [
Number(block.getFieldValue('VALUE')),
Number(block.getFieldValue('MIN')),
Number(block.getFieldValue('MAX')),
Number(block.getFieldValue('PRECISION'))
];
// Remove any trailing arguments that aren't needed.
if (args[3] == 0) {
args.pop();
if (args[2] == Infinity) {
args.pop();
if (args[1] == -Infinity) {
args.pop();
}
}
}
fields.push('new Blockly.FieldNumber(' + args.join(', ') + '), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_angle':
// Result: new Blockly.FieldAngle(90), 'ANGLE'
fields.push('new Blockly.FieldAngle(' +
parseFloat(block.getFieldValue('ANGLE')) + '), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_checkbox':
// Result: new Blockly.FieldCheckbox('TRUE'), 'CHECK'
fields.push('new Blockly.FieldCheckbox(' +
JSON.stringify(block.getFieldValue('CHECKED')) +
'), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_colour':
// Result: new Blockly.FieldColour('#ff0000'), 'COLOUR'
fields.push('new Blockly.FieldColour(' +
JSON.stringify(block.getFieldValue('COLOUR')) +
'), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_date':
// Result: new Blockly.FieldDate('2015-02-04'), 'DATE'
fields.push('new Blockly.FieldDate(' +
JSON.stringify(block.getFieldValue('DATE')) + '), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_variable':
// Result: new Blockly.FieldVariable('item'), 'VAR'
var varname
= JSON.stringify(block.getFieldValue('TEXT') || null);
fields.push('new Blockly.FieldVariable(' + varname + '), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
break;
case 'field_dropdown':
// Result:
// new Blockly.FieldDropdown([['yes', '1'], ['no', '0']]), 'TOGGLE'
var options = [];
for (var i = 0; i < block.optionList_.length; i++) {
options[i] = JSON.stringify([block.getUserData(i),
block.getFieldValue('CPU' + i)]);
}
if (options.length) {
fields.push('new Blockly.FieldDropdown([' +
options.join(', ') + ']), ' +
JSON.stringify(block.getFieldValue('FIELDNAME')));
}
break;
case 'field_image':
// Result: new Blockly.FieldImage('http://...', 80, 60, '*')
var src = JSON.stringify(block.getFieldValue('SRC'));
var width = Number(block.getFieldValue('WIDTH'));
var height = Number(block.getFieldValue('HEIGHT'));
var alt = JSON.stringify(block.getFieldValue('ALT'));
fields.push('new Blockly.FieldImage(' +
src + ', ' + width + ', ' + height + ', ' + alt + ')');
break;
}
}
block = block.nextConnection && block.nextConnection.targetBlock();
}
return fields;
};
/**
* Returns field strings and any config.
* @param {!Blockly.Block} block Input block.
* @return {!Array.<string|!Object>} Array of static text and field configs.
* @private
*/
FactoryUtils.getFieldsJson_ = function(block) {
var fields = [];
while (block) {
if (!block.disabled && !block.getInheritedDisabled()) {
switch (block.type) {
case 'field_static':
// Result: 'hello'
fields.push(block.getFieldValue('TEXT'));
break;
case 'field_input':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
text: block.getFieldValue('TEXT')
});
break;
case 'field_number':
var obj = {
type: block.type,
name: block.getFieldValue('FIELDNAME'),
value: parseFloat(block.getFieldValue('VALUE'))
};
var min = parseFloat(block.getFieldValue('MIN'));
if (min > -Infinity) {
obj.min = min;
}
var max = parseFloat(block.getFieldValue('MAX'));
if (max < Infinity) {
obj.max = max;
}
var precision = parseFloat(block.getFieldValue('PRECISION'));
if (precision) {
obj.precision = precision;
}
fields.push(obj);
break;
case 'field_angle':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
angle: Number(block.getFieldValue('ANGLE'))
});
break;
case 'field_checkbox':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
checked: block.getFieldValue('CHECKED') == 'TRUE'
});
break;
case 'field_colour':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
colour: block.getFieldValue('COLOUR')
});
break;
case 'field_date':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
date: block.getFieldValue('DATE')
});
break;
case 'field_variable':
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
variable: block.getFieldValue('TEXT') || null
});
break;
case 'field_dropdown':
var options = [];
for (var i = 0; i < block.optionList_.length; i++) {
options[i] = [block.getUserData(i),
block.getFieldValue('CPU' + i)];
}
if (options.length) {
fields.push({
type: block.type,
name: block.getFieldValue('FIELDNAME'),
options: options
});
}
break;
case 'field_image':
fields.push({
type: block.type,
src: block.getFieldValue('SRC'),
width: Number(block.getFieldValue('WIDTH')),
height: Number(block.getFieldValue('HEIGHT')),
alt: block.getFieldValue('ALT')
});
break;
}
}
block = block.nextConnection && block.nextConnection.targetBlock();
}
return fields;
};
/**
* Fetch the type(s) defined in the given input.
* Format as a string for appending to the generated code.
* @param {!Blockly.Block} block Block with input.
* @param {string} name Name of the input.
* @return {?string} String defining the types.
*/
FactoryUtils.getOptTypesFrom = function(block, name) {
var types = FactoryUtils.getTypesFrom_(block, name);
if (types.length == 0) {
return undefined;
} else if (types.indexOf('null') != -1) {
return 'null';
} else if (types.length == 1) {
return types[0];
} else {
return '[' + types.join(', ') + ']';
}
};
/**
* Fetch the type(s) defined in the given input.
* @param {!Blockly.Block} block Block with input.
* @param {string} name Name of the input.
* @return {!Array.<string>} List of types.
* @private
*/
FactoryUtils.getTypesFrom_ = function(block, name) {
var typeBlock = block.getInputTargetBlock(name);
var types;
if (!typeBlock || typeBlock.disabled) {
types = [];
} else if (typeBlock.type == 'type_other') {
types = [JSON.stringify(typeBlock.getFieldValue('TYPE'))];
} else if (typeBlock.type == 'type_group') {
types = [];
for (var n = 0; n < typeBlock.typeCount_; n++) {
types = types.concat(FactoryUtils.getTypesFrom_(typeBlock, 'TYPE' + n));
}
// Remove duplicates.
var hash = Object.create(null);
for (var n = types.length - 1; n >= 0; n--) {
if (hash[types[n]]) {
types.splice(n, 1);
}
hash[types[n]] = true;
}
} else {
types = [JSON.stringify(typeBlock.valueType)];
}
return types;
};
/**
* Return the uneditable container block that everything else attaches to in
* given workspace.
* @param {!Blockly.Workspace} workspace Where the root block lives.
* @return {Blockly.Block} Root block.
*/
FactoryUtils.getRootBlock = function(workspace) {
var blocks = workspace.getTopBlocks(false);
for (var i = 0, block; block = blocks[i]; i++) {
if (block.type == 'factory_base') {
return block;
}
}
return null;
};
// TODO(quachtina96): Move hide, show, makeInvisible, and makeVisible to a new
// AppView namespace.
/**
* Hides element so that it's invisible and doesn't take up space.
* @param {string} elementID ID of element to hide.
*/
FactoryUtils.hide = function(elementID) {
document.getElementById(elementID).style.display = 'none';
};
/**
* Un-hides an element.
* @param {string} elementID ID of element to hide.
*/
FactoryUtils.show = function(elementID) {
document.getElementById(elementID).style.display = 'block';
};
/**
* Hides element so that it's invisible but still takes up space.
* @param {string} elementID ID of element to hide.
*/
FactoryUtils.makeInvisible = function(elementID) {
document.getElementById(elementID).visibility = 'hidden';
};
/**
* Makes element visible.
* @param {string} elementID ID of element to hide.
*/
FactoryUtils.makeVisible = function(elementID) {
document.getElementById(elementID).visibility = 'visible';
};
/**
* Create a file with the given attributes and download it.
* @param {string} contents The contents of the file.
* @param {string} filename The name of the file to save to.
* @param {string} fileType The type of the file to save.
*/
FactoryUtils.createAndDownloadFile = function(contents, filename, fileType) {
var data = new Blob([contents], {type: 'text/' + fileType});
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
var a = document.createElement('a');
a.href = window.URL.createObjectURL(data);
a.download = filename;
a.textContent = 'Download file!';
a.dispatchEvent(clickEvent);
};
/**
* Get Blockly Block by rendering pre-defined block in workspace.
* @param {!Element} blockType Type of block that has already been defined.
* @param {!Blockly.Workspace} workspace Workspace on which to render
* the block.
* @return {!Blockly.Block} The Blockly.Block of desired type.
*/
FactoryUtils.getDefinedBlock = function(blockType, workspace) {
workspace.clear();
return workspace.newBlock(blockType);
};
/**
* Parses a block definition get the type of the block it defines.
* @param {string} blockDef A single block definition.
* @return {string} Type of block defined by the given definition.
*/
FactoryUtils.getBlockTypeFromJsDefinition = function(blockDef) {
var indexOfStartBracket = blockDef.indexOf('[\'');
var indexOfEndBracket = blockDef.indexOf('\']');
if (indexOfStartBracket != -1 && indexOfEndBracket != -1) {
return blockDef.substring(indexOfStartBracket + 2, indexOfEndBracket);
} else {
throw new Error ('Could not parse block type out of JavaScript block ' +
'definition. Brackets normally enclosing block type not found.');
}
};
/**
* Generates a category containing blocks of the specified block types.
* @param {!Array.<!Blockly.Block>} blocks Blocks to include in the category.
* @param {string} categoryName Name to use for the generated category.
* @return {!Element} Category XML containing the given block types.
*/
FactoryUtils.generateCategoryXml = function(blocks, categoryName) {
// Create category DOM element.
var categoryElement = goog.dom.createDom('category');
categoryElement.setAttribute('name', categoryName);
// For each block, add block element to category.
for (var i = 0, block; block = blocks[i]; i++) {
// Get preview block XML.
var blockXml = Blockly.Xml.blockToDom(block);
blockXml.removeAttribute('id');
// Add block to category and category to XML.
categoryElement.appendChild(blockXml);
}
return categoryElement;
};
/**
* Parses a string containing JavaScript block definition(s) to create an array
* in which each element is a single block definition.
* @param {string} blockDefsString JavaScript block definition(s).
* @return {!Array.<string>} Array of block definitions.
*/
FactoryUtils.parseJsBlockDefinitions = function(blockDefsString) {
var blockDefArray = [];
var defStart = blockDefsString.indexOf('Blockly.Blocks');
while (blockDefsString.indexOf('Blockly.Blocks', defStart) != -1) {
var nextStart = blockDefsString.indexOf('Blockly.Blocks', defStart + 1);
if (nextStart == -1) {
// This is the last block definition.
nextStart = blockDefsString.length;
}
var blockDef = blockDefsString.substring(defStart, nextStart);
blockDefArray.push(blockDef);
defStart = nextStart;
}
return blockDefArray;
};
/**
* Parses a string containing JSON block definition(s) to create an array
* in which each element is a single block definition. Expected input is
* one or more block definitions in the form of concatenated, stringified
* JSON objects.
* @param {string} blockDefsString String containing JSON block
* definition(s).
* @return {!Array.<string>} Array of block definitions.
*/
FactoryUtils.parseJsonBlockDefinitions = function(blockDefsString) {
var blockDefArray = [];
var unbalancedBracketCount = 0;
var defStart = 0;
// Iterate through the blockDefs string. Keep track of whether brackets
// are balanced.
for (var i = 0; i < blockDefsString.length; i++) {
var currentChar = blockDefsString[i];
if (currentChar == '{') {
unbalancedBracketCount++;
}
else if (currentChar == '}') {
unbalancedBracketCount--;
if (unbalancedBracketCount == 0 && i > 0) {
// The brackets are balanced. We've got a complete block defintion.
var blockDef = blockDefsString.substring(defStart, i + 1);
blockDefArray.push(blockDef);
defStart = i + 1;
}
}
}
return blockDefArray;
};
/**
* Define blocks from imported block definitions.
* @param {string} blockDefsString Block definition(s).
* @param {string} format Block definition format ('JSON' or 'JavaScript').
* @return {!Array.<!Element>} Array of block types defined.
*/
FactoryUtils.defineAndGetBlockTypes = function(blockDefsString, format) {
var blockTypes = [];
// Define blocks and get block types.
if (format == 'JSON') {
var blockDefArray = FactoryUtils.parseJsonBlockDefinitions(blockDefsString);
// Populate array of blocktypes and define each block.
for (var i = 0, blockDef; blockDef = blockDefArray[i]; i++) {
var json = JSON.parse(blockDef);
blockTypes.push(json.type);
// Define the block.
Blockly.Blocks[json.type] = {
init: function() {
this.jsonInit(json);
}
};
}
} else if (format == 'JavaScript') {
var blockDefArray = FactoryUtils.parseJsBlockDefinitions(blockDefsString);
// Populate array of block types.
for (var i = 0, blockDef; blockDef = blockDefArray[i]; i++) {
var blockType = FactoryUtils.getBlockTypeFromJsDefinition(blockDef);
blockTypes.push(blockType);
}
// Define all blocks.
eval(blockDefsString);
}
return blockTypes;
};
/**
* Inject code into a pre tag, with syntax highlighting.
* Safe from HTML/script injection.
* @param {string} code Lines of code.
* @param {string} id ID of <pre> element to inject into.
*/
FactoryUtils.injectCode = function(code, id) {
var pre = document.getElementById(id);
pre.textContent = code;
code = pre.textContent;
code = PR.prettyPrintOne(code, 'js');
pre.innerHTML = code;
};
/**
* Returns whether or not two blocks are the same based on their XML. Expects
* XML with a single child node that is a factory_base block, the XML found on
* Block Factory's main workspace.
* @param {!Element} blockXml1 An XML element with a single child node that
* is a factory_base block.
* @param {!Element} blockXml2 An XML element with a single child node that
* is a factory_base block.
* @return {boolean} Whether or not two blocks are the same based on their XML.
*/
FactoryUtils.sameBlockXml = function(blockXml1, blockXml2) {
// Each XML element should contain a single child element with a 'block' tag
if (blockXml1.tagName.toLowerCase() != 'xml' ||
blockXml2.tagName.toLowerCase() != 'xml') {
throw new Error('Expected two XML elements, recieved elements with tag ' +
'names: ' + blockXml1.tagName + ' and ' + blockXml2.tagName + '.');
}
// Compare the block elements directly. The XML tags may include other meta
// information we want to igrore.
var blockElement1 = blockXml1.getElementsByTagName('block')[0];
var blockElement2 = blockXml2.getElementsByTagName('block')[0];
if (!(blockElement1 && blockElement2)) {
throw new Error('Could not get find block element in XML.');
}
var blockXmlText1 = Blockly.Xml.domToText(blockElement1);
var blockXmlText2 = Blockly.Xml.domToText(blockElement2);
// Strip white space.
blockXmlText1 = blockXmlText1.replace(/\s+/g, '');
blockXmlText2 = blockXmlText2.replace(/\s+/g, '');
// Return whether or not changes have been saved.
return blockXmlText1 == blockXmlText2;
};
/*
* Checks if a block has a variable field. Blocks with variable fields cannot
* be shadow blocks.
* @param {Blockly.Block} block The block to check if a variable field exists.
* @return {boolean} True if the block has a variable field, false otherwise.
*/
FactoryUtils.hasVariableField = function(block) {
if (!block) {
return false;
}
return block.getVars().length > 0;
};
/**
* Checks if a block is a procedures block. If procedures block names are
* ever updated or expanded, this function should be updated as well (no
* other known markers for procedure blocks beyond name).
* @param {Blockly.Block} block The block to check.
* @return {boolean} True if the block is a procedure block, false otherwise.
*/
FactoryUtils.isProcedureBlock = function(block) {
return block &&
(block.type == 'procedures_defnoreturn' ||
block.type == 'procedures_defreturn' ||
block.type == 'procedures_callnoreturn' ||
block.type == 'procedures_callreturn' ||
block.type == 'procedures_ifreturn');
};
/**
* Returns whether or not a modified block's changes has been saved to the
* Block Library.
* TODO(quachtina96): move into the Block Factory Controller once made.
* @param {!BlockLibraryController} blockLibraryController Block Library
* Controller storing custom blocks.
* @return {boolean} True if all changes made to the block have been saved to
* the given Block Library.
*/
FactoryUtils.savedBlockChanges = function(blockLibraryController) {
if (BlockFactory.isStarterBlock()) {
return true;
}
var blockType = blockLibraryController.getCurrentBlockType();
var currentXml = Blockly.Xml.workspaceToDom(BlockFactory.mainWorkspace);
if (blockLibraryController.has(blockType)) {
// Block is saved in block library.
var savedXml = blockLibraryController.getBlockXml(blockType);
return FactoryUtils.sameBlockXml(savedXml, currentXml);
}
return false;
};
/**
* Given the root block of the factory, return the tooltip specified by the user
* or the empty string if no tooltip is found.
* @param {!Blockly.Block} rootBlock Factory_base block.
* @return {string} The tooltip for the generated block, or the empty string.
*/
FactoryUtils.getTooltipFromRootBlock_ = function(rootBlock) {
var tooltipBlock = rootBlock.getInputTargetBlock('TOOLTIP');
if (tooltipBlock && !tooltipBlock.disabled) {
return tooltipBlock.getFieldValue('TEXT');
}
return '';
};
/**
* Given the root block of the factory, return the help url specified by the
* user or the empty string if no tooltip is found.
* @param {!Blockly.Block} rootBlock Factory_base block.
* @return {string} The help url for the generated block, or the empty string.
*/
FactoryUtils.getHelpUrlFromRootBlock_ = function(rootBlock) {
var helpUrlBlock = rootBlock.getInputTargetBlock('HELPURL');
if (helpUrlBlock && !helpUrlBlock.disabled) {
return helpUrlBlock.getFieldValue('TEXT');
}
return '';
};