scratch-blocks/core/blockly.js

574 lines
17 KiB
JavaScript
Raw Normal View History

/**
* @license
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
2014-10-07 13:09:55 -07:00
* 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 Core JavaScript library for Blockly.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
2016-09-27 17:47:36 -04:00
/**
* The top level namespace used to access the Blockly library.
* @namespace Blockly
*/
goog.provide('Blockly');
goog.require('Blockly.BlockSvg.render');
Implement drop-down menus and icon picker field (#233) * Icon menu and drop-down stubs * Recompile 4/15 * Fix stubs to draw shadow block for drop-down * Fix rendering of shadow for icon menu * Add arrow to dropdown button * Add drop-down buttons to rest of examples * Implementation of drop-down div including positioning * Drop-downs take colours from the blocks * Fix scaled secondary position of drop-downs * Fix arrow positioning for RTL * Use SVG parentNode for sizing dropdown * Use transform for drop-down positioning * Add basic DropDownDiv hide * Add animation-in to dropdown * More subtle drop-down animation and shadow * Add icon menu example * Use options style of Blockly FieldImage for drop-down * Add default value for iconmenu * Add example hover, active states for iconmenu buttons * Update dropdown_icon example * Implement icon-menu value handling and default value * Add updating the parent block image field to dropdown * Drop-down animates out; add hooks to hide for various Blockly happenings * Add pointer cursor for drop-down icons * Improve documentation for drop-downs and minor refactor * Factor out getSrcForValue in iconmenu * Blocks take on the icon of their icon-menu * Add basic accessibility properties, similar to closure * Remove extra drop-down example; update playgrounds * Remove unnecessary colour overrides * Add onHide, colour changing, fix references in dropdowndiv * Flip arrow when the drop-down is rendered above * Hide the icon menu drop-down on second tap of button * Add preventDefault to button ontouchstart * Updates to drop-down from Carl * Add icon-menu placeholders and a crazy demo * Fix naming to normalize (drop-down, DropDown) * Add license header
2016-04-21 15:33:28 -04:00
goog.require('Blockly.DropDownDiv');
2016-01-12 16:47:18 -08:00
goog.require('Blockly.Events');
goog.require('Blockly.FieldAngle');
goog.require('Blockly.FieldCheckbox');
goog.require('Blockly.FieldColour');
// Date picker commented out since it increases footprint by 60%.
// Add it only if you need it.
//goog.require('Blockly.FieldDate');
goog.require('Blockly.FieldDropdown');
Implement drop-down menus and icon picker field (#233) * Icon menu and drop-down stubs * Recompile 4/15 * Fix stubs to draw shadow block for drop-down * Fix rendering of shadow for icon menu * Add arrow to dropdown button * Add drop-down buttons to rest of examples * Implementation of drop-down div including positioning * Drop-downs take colours from the blocks * Fix scaled secondary position of drop-downs * Fix arrow positioning for RTL * Use SVG parentNode for sizing dropdown * Use transform for drop-down positioning * Add basic DropDownDiv hide * Add animation-in to dropdown * More subtle drop-down animation and shadow * Add icon menu example * Use options style of Blockly FieldImage for drop-down * Add default value for iconmenu * Add example hover, active states for iconmenu buttons * Update dropdown_icon example * Implement icon-menu value handling and default value * Add updating the parent block image field to dropdown * Drop-down animates out; add hooks to hide for various Blockly happenings * Add pointer cursor for drop-down icons * Improve documentation for drop-downs and minor refactor * Factor out getSrcForValue in iconmenu * Blocks take on the icon of their icon-menu * Add basic accessibility properties, similar to closure * Remove extra drop-down example; update playgrounds * Remove unnecessary colour overrides * Add onHide, colour changing, fix references in dropdowndiv * Flip arrow when the drop-down is rendered above * Hide the icon menu drop-down on second tap of button * Add preventDefault to button ontouchstart * Updates to drop-down from Carl * Add icon-menu placeholders and a crazy demo * Fix naming to normalize (drop-down, DropDown) * Add license header
2016-04-21 15:33:28 -04:00
goog.require('Blockly.FieldIconMenu');
goog.require('Blockly.FieldImage');
goog.require('Blockly.FieldTextInput');
goog.require('Blockly.FieldTextDropdown');
2016-05-04 13:14:05 -07:00
goog.require('Blockly.FieldNumber');
goog.require('Blockly.FieldNumberDropdown');
goog.require('Blockly.FieldVariable');
goog.require('Blockly.Generator');
goog.require('Blockly.Msg');
goog.require('Blockly.Procedures');
goog.require('Blockly.Toolbox');
2016-09-07 17:42:09 -07:00
goog.require('Blockly.Touch');
goog.require('Blockly.WidgetDiv');
2014-12-23 11:22:02 -08:00
goog.require('Blockly.WorkspaceSvg');
2016-03-18 13:14:54 -07:00
goog.require('Blockly.constants');
goog.require('Blockly.inject');
goog.require('Blockly.utils');
goog.require('goog.color');
goog.require('goog.userAgent');
2015-09-21 18:05:34 -07:00
// Turn off debugging when compiled.
/* eslint-disable no-unused-vars */
2015-09-21 18:05:34 -07:00
var CLOSURE_DEFINES = {'goog.DEBUG': false};
/* eslint-enable no-unused-vars */
2015-09-21 18:05:34 -07:00
/**
2016-03-18 15:19:26 -07:00
* The main workspace most recently used.
* Set by Blockly.WorkspaceSvg.prototype.markFocused
* @type {Blockly.Workspace}
*/
2016-03-18 15:19:26 -07:00
Blockly.mainWorkspace = null;
/**
* Currently selected block.
* @type {Blockly.Block}
*/
Blockly.selected = null;
/**
* Currently highlighted connection (during a drag).
* @type {Blockly.Connection}
* @private
*/
Blockly.highlightedConnection_ = null;
/**
* Connection on dragged block that matches the highlighted connection.
* @type {Blockly.Connection}
* @private
*/
Blockly.localConnection_ = null;
/**
2016-05-12 13:24:08 -07:00
* All of the connections on blocks that are currently being dragged.
* @type {!Array.<!Blockly.Connection>}
* @private
*/
Blockly.draggingConnections_ = [];
/**
2016-04-06 14:42:12 -07:00
* Connection on the insertion marker block that matches
* Blockly.localConnection_ on the dragged block.
* @type {Blockly.Connection}
* @private
*/
2016-04-06 14:42:12 -07:00
Blockly.insertionMarkerConnection_ = null;
/**
* Grayed-out block that indicates to the user what will happen if they release
* a drag immediately.
* @type {Blockly.Block}
* @private
*/
Blockly.insertionMarker_ = null;
/**
* The block that will be replaced if the drag is released immediately. Should
* be visually highlighted to indicate this to the user.
* @type {Blockly.Block}
* @private
*/
Blockly.replacementMarker_ = null;
2016-03-14 17:14:00 -07:00
/**
2016-04-06 14:42:12 -07:00
* Connection that was bumped out of the way by an insertion marker, and may
* need to be put back as the drag continues.
2016-03-14 17:14:00 -07:00
* @type {Blockly.Connection}
* @private
*/
Blockly.bumpedConnection_ = null;
/**
* Contents of the local clipboard.
* @type {Element}
* @private
*/
2015-04-28 13:51:25 -07:00
Blockly.clipboardXml_ = null;
/**
* Source of the local clipboard.
* @type {Blockly.WorkspaceSvg}
2015-04-28 13:51:25 -07:00
* @private
*/
Blockly.clipboardSource_ = null;
2014-12-23 11:22:02 -08:00
/**
* Is the mouse dragging a block?
* DRAG_NONE - No drag operation.
* DRAG_STICKY - Still inside the sticky DRAG_RADIUS.
* DRAG_FREE - Freely draggable.
2014-12-23 11:22:02 -08:00
* @private
*/
Blockly.dragMode_ = Blockly.DRAG_NONE;
2014-12-23 11:22:02 -08:00
/**
* Cached value for whether 3D is supported.
* @type {!boolean}
* @private
*/
Blockly.cache3dSupported_ = null;
2016-03-18 15:19:26 -07:00
/**
* Convert a hue (HSV model) into an RGB hex triplet.
* @param {number} hue Hue on a colour wheel (0-360).
* @return {string} RGB code, e.g. '#5ba65b'.
*/
Blockly.hueToRgb = function(hue) {
return goog.color.hsvToHex(hue, Blockly.HSV_SATURATION,
Blockly.HSV_VALUE * 255);
};
/**
2015-04-28 13:51:25 -07:00
* Returns the dimensions of the specified SVG image.
* @param {!Element} svg SVG image.
* @return {!Object} Contains width and height properties.
*/
2015-04-28 13:51:25 -07:00
Blockly.svgSize = function(svg) {
return {width: svg.cachedWidth_,
height: svg.cachedHeight_};
};
/**
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
* Size the workspace when the contents change. This also updates
* scrollbars accordingly.
* @param {!Blockly.WorkspaceSvg} workspace The workspace to resize.
*/
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
Blockly.resizeSvgContents = function(workspace) {
workspace.resizeContents();
};
/**
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
* Size the SVG image to completely fill its container. Call this when the view
* actually changes sizes (e.g. on a window resize/device orientation change).
* See Blockly.resizeSvgContents to resize the workspace when the contents
* change (e.g. when a block is added or removed).
2014-09-08 14:26:52 -07:00
* Record the height/width of the SVG image.
2015-04-28 13:51:25 -07:00
* @param {!Blockly.WorkspaceSvg} workspace Any workspace in the SVG.
*/
2015-04-28 13:51:25 -07:00
Blockly.svgResize = function(workspace) {
var mainWorkspace = workspace;
while (mainWorkspace.options.parentWorkspace) {
mainWorkspace = mainWorkspace.options.parentWorkspace;
}
var svg = mainWorkspace.getParentSvg();
var div = svg.parentNode;
2015-04-28 13:51:25 -07:00
if (!div) {
2016-05-09 09:13:37 -07:00
// Workspace deleted, or something.
2015-04-28 13:51:25 -07:00
return;
}
var width = div.offsetWidth;
var height = div.offsetHeight;
if (svg.cachedWidth_ != width) {
svg.setAttribute('width', width + 'px');
svg.cachedWidth_ = width;
}
if (svg.cachedHeight_ != height) {
svg.setAttribute('height', height + 'px');
svg.cachedHeight_ = height;
}
2015-04-28 17:55:45 -07:00
mainWorkspace.resize();
};
/**
* Handle a key-down on SVG drawing surface.
* @param {!Event} e Key down event.
* @private
*/
Blockly.onKeyDown_ = function(e) {
if (Blockly.mainWorkspace.options.readOnly || Blockly.utils.isTargetInput(e)) {
// No key actions on readonly workspaces.
// When focused on an HTML text input widget, don't trap any keys.
return;
}
if (e.keyCode == 27) {
Implement drop-down menus and icon picker field (#233) * Icon menu and drop-down stubs * Recompile 4/15 * Fix stubs to draw shadow block for drop-down * Fix rendering of shadow for icon menu * Add arrow to dropdown button * Add drop-down buttons to rest of examples * Implementation of drop-down div including positioning * Drop-downs take colours from the blocks * Fix scaled secondary position of drop-downs * Fix arrow positioning for RTL * Use SVG parentNode for sizing dropdown * Use transform for drop-down positioning * Add basic DropDownDiv hide * Add animation-in to dropdown * More subtle drop-down animation and shadow * Add icon menu example * Use options style of Blockly FieldImage for drop-down * Add default value for iconmenu * Add example hover, active states for iconmenu buttons * Update dropdown_icon example * Implement icon-menu value handling and default value * Add updating the parent block image field to dropdown * Drop-down animates out; add hooks to hide for various Blockly happenings * Add pointer cursor for drop-down icons * Improve documentation for drop-downs and minor refactor * Factor out getSrcForValue in iconmenu * Blocks take on the icon of their icon-menu * Add basic accessibility properties, similar to closure * Remove extra drop-down example; update playgrounds * Remove unnecessary colour overrides * Add onHide, colour changing, fix references in dropdowndiv * Flip arrow when the drop-down is rendered above * Hide the icon menu drop-down on second tap of button * Add preventDefault to button ontouchstart * Updates to drop-down from Carl * Add icon-menu placeholders and a crazy demo * Fix naming to normalize (drop-down, DropDown) * Add license header
2016-04-21 15:33:28 -04:00
// Pressing esc closes the context menu and any drop-down
Blockly.hideChaff();
Implement drop-down menus and icon picker field (#233) * Icon menu and drop-down stubs * Recompile 4/15 * Fix stubs to draw shadow block for drop-down * Fix rendering of shadow for icon menu * Add arrow to dropdown button * Add drop-down buttons to rest of examples * Implementation of drop-down div including positioning * Drop-downs take colours from the blocks * Fix scaled secondary position of drop-downs * Fix arrow positioning for RTL * Use SVG parentNode for sizing dropdown * Use transform for drop-down positioning * Add basic DropDownDiv hide * Add animation-in to dropdown * More subtle drop-down animation and shadow * Add icon menu example * Use options style of Blockly FieldImage for drop-down * Add default value for iconmenu * Add example hover, active states for iconmenu buttons * Update dropdown_icon example * Implement icon-menu value handling and default value * Add updating the parent block image field to dropdown * Drop-down animates out; add hooks to hide for various Blockly happenings * Add pointer cursor for drop-down icons * Improve documentation for drop-downs and minor refactor * Factor out getSrcForValue in iconmenu * Blocks take on the icon of their icon-menu * Add basic accessibility properties, similar to closure * Remove extra drop-down example; update playgrounds * Remove unnecessary colour overrides * Add onHide, colour changing, fix references in dropdowndiv * Flip arrow when the drop-down is rendered above * Hide the icon menu drop-down on second tap of button * Add preventDefault to button ontouchstart * Updates to drop-down from Carl * Add icon-menu placeholders and a crazy demo * Fix naming to normalize (drop-down, DropDown) * Add license header
2016-04-21 15:33:28 -04:00
Blockly.DropDownDiv.hide();
} else if (e.keyCode == 8 || e.keyCode == 46) {
// Delete or backspace.
// Stop the browser from going back to the previous page.
e.preventDefault();
} else if (e.altKey || e.ctrlKey || e.metaKey) {
2014-09-08 14:26:52 -07:00
if (Blockly.selected &&
2015-04-28 13:51:25 -07:00
Blockly.selected.isDeletable() && Blockly.selected.isMovable()) {
if (e.keyCode == 67) {
// 'c' for copy.
Blockly.hideChaff();
Blockly.copy_(Blockly.selected);
} else if (e.keyCode == 88) {
// 'x' for cut.
Blockly.copy_(Blockly.selected);
Blockly.hideChaff();
var heal = Blockly.dragMode_ != Blockly.DRAG_FREE;
Blockly.selected.dispose(heal, true);
if (Blockly.highlightedConnection_) {
Blockly.highlightedConnection_.unhighlight();
Blockly.highlightedConnection_ = null;
}
}
}
if (e.keyCode == 86) {
// 'v' for paste.
2015-04-28 13:51:25 -07:00
if (Blockly.clipboardXml_) {
Blockly.Events.setGroup(true);
2015-04-28 13:51:25 -07:00
Blockly.clipboardSource_.paste(Blockly.clipboardXml_);
Blockly.Events.setGroup(false);
}
} else if (e.keyCode == 90) {
// 'z' for undo 'Z' is for redo.
2016-03-25 19:03:18 -07:00
Blockly.hideChaff();
Blockly.mainWorkspace.undo(e.shiftKey);
}
}
};
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
Blockly.terminateDrag_ = function() {
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
Blockly.BlockSvg.terminateDrag();
Blockly.Flyout.terminateDrag_();
};
/**
* Copy a block onto the local clipboard.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
Blockly.copy_ = function(block) {
2016-01-15 15:36:06 -08:00
var xmlBlock = Blockly.Xml.blockToDom(block);
if (Blockly.dragMode_ != Blockly.DRAG_FREE) {
Blockly.Xml.deleteNext(xmlBlock);
}
// Encode start position in XML.
var xy = block.getRelativeToSurfaceXY();
2015-04-28 13:51:25 -07:00
xmlBlock.setAttribute('x', block.RTL ? -xy.x : xy.x);
xmlBlock.setAttribute('y', xy.y);
2015-04-28 13:51:25 -07:00
Blockly.clipboardXml_ = xmlBlock;
Blockly.clipboardSource_ = block.workspace;
};
/**
* Duplicate this block and its children.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
Blockly.duplicate_ = function(block) {
// Save the clipboard.
var clipboardXml = Blockly.clipboardXml_;
var clipboardSource = Blockly.clipboardSource_;
// Create a duplicate via a copy/paste operation.
Blockly.copy_(block);
block.workspace.paste(Blockly.clipboardXml_);
// Restore the clipboard.
Blockly.clipboardXml_ = clipboardXml;
Blockly.clipboardSource_ = clipboardSource;
};
/**
* Cancel the native context menu, unless the focus is on an HTML input widget.
* @param {!Event} e Mouse down event.
* @private
*/
Blockly.onContextMenu_ = function(e) {
if (!Blockly.utils.isTargetInput(e)) {
// When focused on an HTML text input widget, don't cancel the context menu.
e.preventDefault();
}
};
/**
* Close tooltips, context menus, dropdown selections, etc.
* @param {boolean=} opt_allowToolbox If true, don't close the toolbox.
*/
Blockly.hideChaff = function(opt_allowToolbox) {
2014-09-08 14:26:52 -07:00
Blockly.Tooltip.hide();
Blockly.WidgetDiv.hide();
2015-04-28 13:51:25 -07:00
if (!opt_allowToolbox) {
var workspace = Blockly.getMainWorkspace();
if (workspace.toolbox_ &&
workspace.toolbox_.flyout_ &&
workspace.toolbox_.flyout_.autoClose) {
workspace.toolbox_.clearSelection();
}
}
};
/**
2015-04-28 13:51:25 -07:00
* Returns the main workspace. Returns the last used main workspace (based on
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
* focus). Try not to use this function, particularly if there are multiple
* Blockly instances on a page.
* @return {!Blockly.Workspace} The main workspace.
*/
Blockly.getMainWorkspace = function() {
return Blockly.mainWorkspace;
};
/**
* Wrapper to window.alert() that app developers may override to
* provide alternatives to the modal browser window.
* @param {string} message The message to display to the user.
* @param {function()=} opt_callback The callback when the alert is dismissed.
*/
Blockly.alert = function(message, opt_callback) {
window.alert(message);
if (opt_callback) {
opt_callback();
}
};
/**
* Wrapper to window.confirm() that app developers may override to
* provide alternatives to the modal browser window.
* @param {string} message The message to display to the user.
* @param {!function(boolean)} callback The callback for handling user response.
*/
Blockly.confirm = function(message, callback) {
callback(window.confirm(message));
};
/**
* Wrapper to window.prompt() that app developers may override to provide
* alternatives to the modal browser window. Built-in browser prompts are
* often used for better text input experience on mobile device. We strongly
* recommend testing mobile when overriding this.
* @param {string} message The message to display to the user.
* @param {string} defaultValue The value to initialize the prompt with.
* @param {!function(string)} callback The callback for handling user response.
*/
Blockly.prompt = function(message, defaultValue, callback) {
callback(window.prompt(message, defaultValue));
};
/**
* Helper function for defining a block from JSON. The resulting function has
* the correct value of jsonDef at the point in code where jsonInit is called.
* @param {!Object} jsonDef The JSON definition of a block.
* @return {function} A function that calls jsonInit with the correct value
* of jsonDef.
* @private
*/
Blockly.jsonInitFactory_ = function(jsonDef) {
return function() {
this.jsonInit(jsonDef);
};
};
/**
* Define blocks from an array of JSON block definitions, as might be generated
* by the Blockly Developer Tools.
* @param {!Array.<!Object>} jsonArray An array of JSON block definitions.
*/
Blockly.defineBlocksWithJsonArray = function(jsonArray) {
for (var i = 0, elem; elem = jsonArray[i]; i++) {
Blockly.Blocks[elem.type] = {
init: Blockly.jsonInitFactory_(elem)
};
}
};
/**
* Bind an event to a function call. When calling the function, verifies that
* it belongs to the touch stream that is currently being processed, and splits
* multitouch events into multiple events as needed.
* @param {!Node} node Node upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {Object} thisObject The value of 'this' in the function.
* @param {!Function} func Function to call when event is triggered.
* @param {boolean} opt_noCaptureIdentifier True if triggering on this event
* should not block execution of other event handlers on this touch or other
* simultaneous touches.
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
* @private
*/
Blockly.bindEventWithChecks_ = function(node, name, thisObject, func,
opt_noCaptureIdentifier) {
var handled = false;
var wrapFunc = function(e) {
var captureIdentifier = !opt_noCaptureIdentifier;
// Handle each touch point separately. If the event was a mouse event, this
// will hand back an array with one element, which we're fine handling.
var events = Blockly.Touch.splitEventByTouches(e);
for (var i = 0, event; event = events[i]; i++) {
if (captureIdentifier && !Blockly.Touch.shouldHandleEvent(event)) {
continue;
}
Blockly.Touch.setClientFromTouch(event);
if (thisObject) {
func.call(thisObject, event);
} else {
func(event);
}
handled = true;
}
};
node.addEventListener(name, wrapFunc, false);
var bindData = [[node, name, wrapFunc]];
// Add equivalent touch event.
if (name in Blockly.Touch.TOUCH_MAP) {
var touchWrapFunc = function(e) {
wrapFunc(e);
// Stop the browser from scrolling/zooming the page.
if (handled) {
e.preventDefault();
}
};
for (var i = 0, eventName;
eventName = Blockly.Touch.TOUCH_MAP[name][i]; i++) {
node.addEventListener(eventName, touchWrapFunc, false);
bindData.push([node, eventName, touchWrapFunc]);
}
}
return bindData;
};
/**
* Bind an event to a function call. Handles multitouch events by using the
* coordinates of the first changed touch, and doesn't do any safety checks for
* simultaneous event processing.
* @deprecated in favor of bindEventWithChecks_, but preserved for external
* users.
* @param {!Node} node Node upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {Object} thisObject The value of 'this' in the function.
* @param {!Function} func Function to call when event is triggered.
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
* @private
*/
Blockly.bindEvent_ = function(node, name, thisObject, func) {
var wrapFunc = function(e) {
if (thisObject) {
func.call(thisObject, e);
} else {
func(e);
}
};
node.addEventListener(name, wrapFunc, false);
var bindData = [[node, name, wrapFunc]];
// Add equivalent touch event.
if (name in Blockly.Touch.TOUCH_MAP) {
var touchWrapFunc = function(e) {
// Punt on multitouch events.
if (e.changedTouches.length == 1) {
// Map the touch event's properties to the event.
var touchPoint = e.changedTouches[0];
e.clientX = touchPoint.clientX;
e.clientY = touchPoint.clientY;
}
wrapFunc(e);
// Stop the browser from scrolling/zooming the page.
e.preventDefault();
};
for (var i = 0, eventName;
eventName = Blockly.Touch.TOUCH_MAP[name][i]; i++) {
node.addEventListener(eventName, touchWrapFunc, false);
bindData.push([node, eventName, touchWrapFunc]);
}
}
return bindData;
};
/**
* Unbind one or more events event from a function call.
* @param {!Array.<!Array>} bindData Opaque data from bindEvent_.
* This list is emptied during the course of calling this function.
* @return {!Function} The function call.
* @private
*/
Blockly.unbindEvent_ = function(bindData) {
while (bindData.length) {
var bindDatum = bindData.pop();
var node = bindDatum[0];
var name = bindDatum[1];
var func = bindDatum[2];
node.removeEventListener(name, func, false);
}
return func;
};
/**
* Is the given string a number (includes negative and decimals).
* @param {string} str Input string.
* @return {boolean} True if number, false otherwise.
*/
Blockly.isNumber = function(str) {
return !!str.match(/^\s*-?\d+(\.\d+)?\s*$/);
};
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
// IE9 does not have a console. Create a stub to stop errors.
if (!goog.global['console']) {
goog.global['console'] = {
'log': function() {},
'warn': function() {}
};
}
// Export symbols that would otherwise be renamed by Closure compiler.
if (!goog.global['Blockly']) {
goog.global['Blockly'] = {};
2014-09-08 14:26:52 -07:00
}
goog.global['Blockly']['getMainWorkspace'] = Blockly.getMainWorkspace;