scratch-blocks/core/toolbox.js

677 lines
20 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 Toolbox from whence to create blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Toolbox');
goog.require('Blockly.Flyout');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events');
goog.require('goog.events.BrowserFeature');
2014-09-08 14:26:52 -07:00
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeStyle');
2015-01-22 15:58:10 -08:00
goog.require('goog.math.Rect');
goog.require('goog.style');
goog.require('goog.ui.tree.TreeControl');
goog.require('goog.ui.tree.TreeNode');
/**
* Class for a Toolbox.
2015-04-28 13:51:25 -07:00
* Creates the toolbox's DOM.
* @param {!Blockly.Workspace} workspace The workspace in which to create new
* blocks.
* @constructor
*/
2015-04-28 13:51:25 -07:00
Blockly.Toolbox = function(workspace) {
/**
2015-04-28 13:51:25 -07:00
* @type {!Blockly.Workspace}
* @private
*/
2015-04-28 13:51:25 -07:00
this.workspace_ = workspace;
/**
* Whether toolbox categories should be represented by icons instead of text.
* @type {boolean}
* @private
*/
this.iconic_ = false;
2016-02-17 16:19:40 -08:00
/**
* Is RTL vs LTR.
* @type {boolean}
*/
this.RTL = workspace.options.RTL;
/**
* Whether the toolbox should be laid out horizontally.
* @type {boolean}
* @private
*/
this.horizontalLayout_ = workspace.options.horizontalLayout;
2016-02-08 13:56:57 -08:00
2016-02-17 16:19:40 -08:00
/**
* Position of the toolbox and flyout relative to the workspace.
* @type {number}
*/
this.toolboxPosition = workspace.options.toolboxPosition;
2016-02-12 10:57:33 -08:00
/**
* Configuration constants for Closure's tree UI.
* @type {Object.<string,*>}
* @private
*/
2016-02-23 14:55:15 -08:00
this.config_ = {
indentWidth: 19,
cssRoot: 'blocklyTreeRoot',
cssHideRoot: 'blocklyHidden',
cssItem: '',
cssTreeRow: 'blocklyTreeRow',
cssItemLabel: 'blocklyTreeLabel',
cssTreeIcon: 'blocklyTreeIcon',
cssExpandedFolderIcon: 'blocklyTreeIconOpen',
cssFileIcon: 'blocklyTreeIconNone',
cssSelectedRow: 'blocklyTreeSelected'
};
/**
* Configuration constants for tree separator.
* @type {Object.<string,*>}
* @private
*/
2016-02-23 14:55:15 -08:00
this.treeSeparatorConfig_ = {
cssTreeRow: 'blocklyTreeSeparator'
};
if (this.horizontalLayout_) {
2016-02-23 14:55:15 -08:00
this.config_['cssTreeRow'] =
this.config_['cssTreeRow'] +
2016-04-08 15:34:08 -07:00
(workspace.RTL ?
' blocklyHorizontalTreeRtl' : ' blocklyHorizontalTree');
2016-02-23 14:55:15 -08:00
this.treeSeparatorConfig_['cssTreeRow'] =
'blocklyTreeSeparatorHorizontal ' +
2016-04-08 15:34:08 -07:00
(workspace.RTL ?
'blocklyHorizontalTreeRtl' : 'blocklyHorizontalTree');
2016-02-23 14:55:15 -08:00
this.config_['cssTreeIcon'] = '';
}
};
/**
* Width of the toolbox, which changes only in vertical layout.
* @type {number}
*/
Blockly.Toolbox.prototype.width = 0;
/**
* Height of the toolbox, which changes only in horizontal layout.
* @type {number}
*/
Blockly.Toolbox.prototype.height = 0;
/**
* The SVG group currently selected.
* @type {SVGGElement}
* @private
*/
Blockly.Toolbox.prototype.selectedOption_ = null;
/**
2015-10-12 16:14:03 -07:00
* The tree node most recently selected.
* @type {goog.ui.tree.BaseNode}
* @private
*/
Blockly.Toolbox.prototype.lastCategory_ = null;
/**
* Initializes the toolbox.
*/
2015-04-28 13:51:25 -07:00
Blockly.Toolbox.prototype.init = function() {
var workspace = this.workspace_;
var svg = this.workspace_.getParentSvg();
2015-04-28 13:51:25 -07:00
// Create an HTML container for the Toolbox menu.
this.HtmlDiv =
goog.dom.createDom(goog.dom.TagName.DIV, 'blocklyToolboxDiv');
2015-10-12 16:14:03 -07:00
this.HtmlDiv.setAttribute('dir', workspace.RTL ? 'RTL' : 'LTR');
svg.parentNode.insertBefore(this.HtmlDiv, svg);
2015-04-28 13:51:25 -07:00
// Clicking on toolbox closes popups.
2015-04-28 13:51:25 -07:00
Blockly.bindEvent_(this.HtmlDiv, 'mousedown', this,
function(e) {
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();
2015-04-28 13:51:25 -07:00
if (Blockly.isRightButton(e) || e.target == this.HtmlDiv) {
// Close flyout.
Blockly.hideChaff(false);
} else {
// Just close popups.
Blockly.hideChaff(true);
}
});
var workspaceOptions = {
disabledPatternId: workspace.options.disabledPatternId,
2015-04-28 13:51:25 -07:00
parentWorkspace: workspace,
RTL: workspace.RTL,
2016-02-12 10:57:33 -08:00
horizontalLayout: workspace.horizontalLayout,
2016-02-17 16:19:40 -08:00
toolboxPosition: workspace.options.toolboxPosition
2015-04-28 13:51:25 -07:00
};
2015-04-28 13:51:25 -07:00
/**
* @type {!Blockly.Flyout}
* @private
*/
this.flyout_ = new Blockly.Flyout(workspaceOptions);
goog.dom.insertSiblingAfter(this.flyout_.createDom(), workspace.svgGroup_);
this.flyout_.init(workspace);
2016-02-17 16:19:40 -08:00
this.flyout_.hide();
2015-04-28 13:51:25 -07:00
2016-02-23 14:55:15 -08:00
this.config_['cleardotPath'] = workspace.options.pathToMedia + '1x1.gif';
this.config_['cssCollapsedFolderIcon'] =
2015-10-12 16:14:03 -07:00
'blocklyTreeIconClosed' + (workspace.RTL ? 'Rtl' : 'Ltr');
2016-02-23 14:55:15 -08:00
var tree = new Blockly.Toolbox.TreeControl(this, this.config_);
this.tree_ = tree;
tree.setShowRootNode(false);
tree.setShowLines(false);
tree.setShowExpandIcons(false);
tree.setSelectedItem(null);
var openNode = this.populate_(workspace.options.languageTree);
tree.render(this.HtmlDiv);
if (openNode) {
tree.setSelectedItem(openNode);
}
this.addColour_();
2015-04-28 17:55:45 -07:00
this.position();
};
/**
* Dispose of this toolbox.
*/
Blockly.Toolbox.prototype.dispose = function() {
this.flyout_.dispose();
this.tree_.dispose();
goog.dom.removeNode(this.HtmlDiv);
2015-08-20 15:46:44 -07:00
this.workspace_ = null;
2015-10-12 16:14:03 -07:00
this.lastCategory_ = null;
};
/**
* Get the width of the toolbox.
* @return {number} The width of the toolbox.
*/
Blockly.Toolbox.prototype.getWidth = function() {
return this.width;
};
/**
* Get the height of the toolbox.
* @return {number} The width of the toolbox.
*/
Blockly.Toolbox.prototype.getHeight = function() {
return this.height;
};
/**
* Move the toolbox to the edge.
*/
2015-04-28 17:55:45 -07:00
Blockly.Toolbox.prototype.position = function() {
var treeDiv = this.HtmlDiv;
2015-04-28 17:55:45 -07:00
if (!treeDiv) {
// Not initialized yet.
return;
}
var svg = this.workspace_.getParentSvg();
2015-04-28 13:51:25 -07:00
var svgSize = Blockly.svgSize(svg);
if (this.horizontalLayout_) {
treeDiv.style.left = '0';
treeDiv.style.height = 'auto';
treeDiv.style.width = svgSize.width + 'px';
this.height = treeDiv.offsetHeight;
2016-02-17 16:19:40 -08:00
if (this.toolboxPosition == Blockly.TOOLBOX_AT_TOP) { // Top
treeDiv.style.top = '0';
} else { // Bottom
treeDiv.style.bottom = '0';
}
} else {
2016-02-17 16:19:40 -08:00
if (this.toolboxPosition == Blockly.TOOLBOX_AT_RIGHT) { // Right
treeDiv.style.right = '0';
} else { // Left
treeDiv.style.left = '0';
}
treeDiv.style.height = svgSize.height + 'px';
this.width = treeDiv.offsetWidth;
}
2015-04-28 17:55:45 -07:00
this.flyout_.position();
};
/**
* Fill the toolbox with categories and blocks.
* @param {!Node} newTree DOM tree of blocks.
* @return {Node} Tree node to open at startup (or null).
* @private
*/
2015-04-28 13:51:25 -07:00
Blockly.Toolbox.prototype.populate_ = function(newTree) {
this.tree_.removeChildren(); // Delete any existing content.
this.tree_.blocks = [];
this.hasColours_ = false;
var openNode =
this.syncTrees_(newTree, this.tree_, this.iconic_,
this.workspace_.options.pathToMedia);
if (this.tree_.blocks.length) {
throw 'Toolbox cannot have both blocks and categories in the root level.';
}
// Fire a resize event since the toolbox may have changed width and height.
this.workspace_.resizeContents();
return openNode;
};
/**
* Sync trees of the toolbox.
* @param {Node} treeIn DOM tree of blocks, or null.
* @param {Blockly.Toolbox.TreeControl} treeOut Blockly toolbox tree to sync.
* @param {boolean} iconic Whether the toolbox uses icons.
* @param {string} pathToMedia Media path for the toolbox.
* @return {Node} Tree node to open at startup (or null).
* @private
*/
Blockly.Toolbox.prototype.syncTrees_ = function(treeIn, treeOut, iconic,
pathToMedia) {
var openNode = null;
var lastElement = null;
for (var i = 0, childIn; childIn = treeIn.childNodes[i]; i++) {
if (!childIn.tagName) {
// Skip over text.
continue;
}
switch (childIn.tagName.toUpperCase()) {
case 'CATEGORY':
if (iconic && childIn.getAttribute('icon')) {
var childOut = this.tree_.createNode(childIn.getAttribute('name'),
pathToMedia + childIn.getAttribute('icon'));
} else {
var childOut = this.tree_.createNode(childIn.getAttribute('name'),
null);
}
childOut.blocks = [];
treeOut.add(childOut);
var custom = childIn.getAttribute('custom');
if (custom) {
// Variables and procedures are special dynamic categories.
childOut.blocks = custom;
} else {
var newOpenNode = this.syncTrees_(childIn, childOut, iconic,
pathToMedia);
if (newOpenNode) {
openNode = newOpenNode;
}
}
var colour = childIn.getAttribute('colour');
if (goog.isString(colour)) {
if (colour.match(/^#[0-9a-fA-F]{6}$/)) {
childOut.hexColour = colour;
2015-05-22 17:08:59 -07:00
} else {
childOut.hexColour = Blockly.hueToRgb(colour);
2015-05-22 17:08:59 -07:00
}
this.hasColours_ = true;
} else {
childOut.hexColour = '';
}
if (childIn.getAttribute('expanded') == 'true') {
if (childOut.blocks.length) {
// This is a category that directly contians blocks.
// After the tree is rendered, open this category and show flyout.
openNode = childOut;
2015-10-14 14:02:06 -07:00
}
childOut.setExpanded(true);
} else {
childOut.setExpanded(false);
}
lastElement = childIn;
break;
case 'SEP':
if (lastElement) {
if (lastElement.tagName.toUpperCase() == 'CATEGORY') {
// Separator between two categories.
// <sep></sep>
treeOut.add(new Blockly.Toolbox.TreeSeparator(
this.treeSeparatorConfig_));
} else {
// Change the gap between two blocks.
// <sep gap="36"></sep>
// The default gap is 24, can be set larger or smaller.
// Note that a deprecated method is to add a gap to a block.
// <block type="math_arithmetic" gap="8"></block>
var newGap = parseFloat(childIn.getAttribute('gap'));
if (!isNaN(newGap) && lastElement) {
lastElement.setAttribute('gap', newGap);
}
}
}
break;
case 'BLOCK':
case 'SHADOW':
treeOut.blocks.push(childIn);
lastElement = childIn;
break;
}
}
return openNode;
};
/**
* Recursively add colours to this toolbox.
* @param {Blockly.Toolbox.TreeNode} opt_tree Starting point of tree.
* Defaults to the root node.
* @private
*/
Blockly.Toolbox.prototype.addColour_ = function(opt_tree) {
var tree = opt_tree || this.tree_;
var children = tree.getChildren();
for (var i = 0, child; child = children[i]; i++) {
2015-10-14 14:02:06 -07:00
var element = child.getRowElement();
if (element) {
if (this.hasColours_) {
var border = '8px solid ' + (child.hexColour || '#ddd');
} else {
var border = 'none';
}
2016-02-17 16:19:40 -08:00
if (this.RTL) {
element.style.borderRight = border;
2015-10-14 14:02:06 -07:00
} else {
element.style.borderLeft = border;
}
}
this.addColour_(child);
}
};
/**
* Unhighlight any previously specified option.
*/
Blockly.Toolbox.prototype.clearSelection = function() {
this.tree_.setSelectedItem(null);
};
/**
* Return the deletion rectangle for this toolbar in viewport coordinates.\
* @return {goog.math.Rect} Rectangle in which to delete.
*/
Blockly.Toolbox.prototype.getClientRect = 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
if (!this.HtmlDiv) {
return null;
}
// BIG_NUM is offscreen padding so that blocks dragged beyond the toolbox
// area are still deleted. Must be smaller than Infinity, but larger than
// the largest screen size.
var BIG_NUM = 10000000;
var toolboxRect = this.HtmlDiv.getBoundingClientRect();
var x = toolboxRect.left;
var y = toolboxRect.top;
var width = toolboxRect.width;
var height = toolboxRect.height;
2016-02-17 16:19:40 -08:00
// Assumes that the toolbox is on the SVG edge. If this changes
// (e.g. toolboxes in mutators) then this code will need to be more complex.
if (this.toolboxPosition == Blockly.TOOLBOX_AT_LEFT) {
return new goog.math.Rect(-BIG_NUM, -BIG_NUM, BIG_NUM + x + width,
2 * BIG_NUM);
2016-02-17 16:19:40 -08:00
} else if (this.toolboxPosition == Blockly.TOOLBOX_AT_RIGHT) {
return new goog.math.Rect(x, -BIG_NUM, BIG_NUM + width, 2 * BIG_NUM);
2016-02-17 16:19:40 -08:00
} else if (this.toolboxPosition == Blockly.TOOLBOX_AT_TOP) {
2016-03-30 12:59:29 -07:00
return new goog.math.Rect(-BIG_NUM, -BIG_NUM, 2 * BIG_NUM,
BIG_NUM + y + height);
} else { // Bottom
2016-04-08 15:34:08 -07:00
return new goog.math.Rect(0, y, 2 * BIG_NUM, BIG_NUM + width);
}
};
2016-07-01 15:51:59 -07:00
/**
* Update the flyout's contents without closing it. Should be used in response
* to a change in one of the dynamic categories, such as variables or
* procedures.
*/
Blockly.Toolbox.prototype.refreshSelection = function() {
var selectedItem = this.tree_.getSelectedItem();
if (selectedItem && selectedItem.blocks) {
this.flyout_.show(selectedItem.blocks);
}
};
// Extending Closure's Tree UI.
/**
* Extention of a TreeControl object that uses a custom tree node.
* @param {Blockly.Toolbox} toolbox The parent toolbox for this tree.
* @param {Object} config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig.
* @constructor
* @extends {goog.ui.tree.TreeControl}
*/
Blockly.Toolbox.TreeControl = function(toolbox, config) {
this.toolbox_ = toolbox;
goog.ui.tree.TreeControl.call(this, goog.html.SafeHtml.EMPTY, config);
};
goog.inherits(Blockly.Toolbox.TreeControl, goog.ui.tree.TreeControl);
/**
* Adds touch handling to TreeControl.
* @override
*/
Blockly.Toolbox.TreeControl.prototype.enterDocument = function() {
Blockly.Toolbox.TreeControl.superClass_.enterDocument.call(this);
// Add touch handler.
if (goog.events.BrowserFeature.TOUCH_ENABLED) {
var el = this.getElement();
Blockly.bindEvent_(el, goog.events.EventType.TOUCHSTART, this,
this.handleTouchEvent_);
}
};
2016-06-29 23:38:32 +02:00
/**
* Handles touch events.
* @param {!goog.events.BrowserEvent} e The browser event.
* @private
*/
Blockly.Toolbox.TreeControl.prototype.handleTouchEvent_ = function(e) {
e.preventDefault();
var node = this.getNodeFromEvent_(e);
if (node && e.type === goog.events.EventType.TOUCHSTART) {
// Fire asynchronously since onMouseDown takes long enough that the browser
// would fire the default mouse event before this method returns.
setTimeout(function() {
2014-09-08 14:26:52 -07:00
node.onMouseDown(e); // Same behaviour for click and touch.
}, 1);
}
};
/**
* Creates a new tree node using a custom tree node.
2015-03-26 20:47:36 -07:00
* @param {string=} opt_html The HTML content of the node label.
* @param {string} icon The path to the icon for this category.
2014-09-08 14:26:52 -07:00
* @return {!goog.ui.tree.TreeNode} The new item.
* @override
*/
Blockly.Toolbox.TreeControl.prototype.createNode = function(opt_html, icon) {
2016-05-24 14:17:43 -07:00
var icon_html =
'<img src=\"' + icon + '\" alt=\"' + opt_html + '\" align=top>';
var safe_opt_html = opt_html ?
goog.html.SafeHtml.htmlEscape(opt_html) : goog.html.SafeHtml.EMPTY;
var label_html = icon ? icon_html + ' ' + opt_html : safe_opt_html;
return new Blockly.Toolbox.TreeNode(this.toolbox_, label_html,
this.getConfig(), this.getDomHelper());
};
/**
* Display/hide the flyout when an item is selected.
* @param {goog.ui.tree.BaseNode} node The item to select.
* @override
*/
Blockly.Toolbox.TreeControl.prototype.setSelectedItem = function(node) {
var toolbox = this.toolbox_;
if (node == this.selectedItem_ || node == toolbox.tree_) {
return;
}
if (toolbox.lastCategory_) {
2015-10-14 14:02:06 -07:00
toolbox.lastCategory_.getRowElement().style.backgroundColor = '';
}
if (node) {
var hexColour = node.hexColour || '#57e';
2015-10-14 14:02:06 -07:00
node.getRowElement().style.backgroundColor = hexColour;
2015-10-14 15:00:32 -07:00
// Add colours to child nodes which may have been collapsed and thus
// not rendered.
toolbox.addColour_(node);
}
2016-03-31 02:04:23 -07:00
var oldNode = this.getSelectedItem();
goog.ui.tree.TreeControl.prototype.setSelectedItem.call(this, node);
if (node && node.blocks && node.blocks.length) {
toolbox.flyout_.show(node.blocks);
2016-02-08 13:56:57 -08:00
// Scroll the flyout to the start if the category has changed.
2015-10-12 16:14:03 -07:00
if (toolbox.lastCategory_ != node) {
2016-02-08 13:56:57 -08:00
toolbox.flyout_.scrollToStart();
}
} else {
// Hide the flyout.
toolbox.flyout_.hide();
}
2016-03-31 02:04:23 -07:00
if (oldNode != node && oldNode != this) {
var event = new Blockly.Events.Ui(null, 'category',
oldNode && oldNode.getHtml(), node && node.getHtml());
event.workspaceId = toolbox.workspace_.id;
Blockly.Events.fire(event);
}
2015-10-14 14:02:06 -07:00
if (node) {
toolbox.lastCategory_ = node;
}
};
/**
2014-11-24 17:34:27 -08:00
* A single node in the tree, customized for Blockly's UI.
* @param {Blockly.Toolbox} toolbox The parent toolbox for this tree.
2014-09-08 14:26:52 -07:00
* @param {!goog.html.SafeHtml} html The HTML content of the node label.
* @param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig. If not specified, a default config
* will be used.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.tree.TreeNode}
*/
Blockly.Toolbox.TreeNode = function(toolbox, html, opt_config, opt_domHelper) {
goog.ui.tree.TreeNode.call(this, html, opt_config, opt_domHelper);
if (toolbox) {
this.horizontalLayout_ = toolbox.horizontalLayout_;
var resize = 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
// Even though the div hasn't changed size, the visible workspace
// surface of the workspace has, so we may need to reposition everything.
Blockly.svgResize(toolbox.workspace_);
};
// Fire a resize event since the toolbox may have changed width.
goog.events.listen(toolbox.tree_,
goog.ui.tree.BaseNode.EventType.EXPAND, resize);
goog.events.listen(toolbox.tree_,
goog.ui.tree.BaseNode.EventType.COLLAPSE, resize);
this.toolbox_ = toolbox;
}
};
goog.inherits(Blockly.Toolbox.TreeNode, goog.ui.tree.TreeNode);
/**
* Supress population of the +/- icon.
2014-09-08 14:26:52 -07:00
* @return {!goog.html.SafeHtml} The source for the icon.
* @override
*/
2015-03-26 20:47:36 -07:00
Blockly.Toolbox.TreeNode.prototype.getExpandIconSafeHtml = function() {
2014-09-08 14:26:52 -07:00
return goog.html.SafeHtml.create('span');
};
/**
* Expand or collapse the node on mouse click.
* @param {!goog.events.BrowserEvent} e The browser event.
* @override
*/
Blockly.Toolbox.TreeNode.prototype.onMouseDown = function(/*e*/) {
// Expand icon.
if (this.hasChildren() && this.isUserCollapsible_) {
this.toggle();
this.select();
} else if (this.isSelected()) {
this.getTree().setSelectedItem(null);
} else {
this.select();
}
this.updateRow();
};
/**
* Supress the inherited double-click behaviour.
* @param {!goog.events.BrowserEvent} e The browser event.
* @override
* @private
*/
Blockly.Toolbox.TreeNode.prototype.onDoubleClick_ = function(/*e*/) {
// NOP.
};
2014-11-24 17:34:27 -08:00
/**
* Remap event.keyCode in horizontalLayout so that arrow
* keys work properly and call original onKeyDown handler.
* @param {!goog.events.BrowserEvent} e The browser event.
* @return {boolean} The handled value.
* @override
* @private
*/
Blockly.Toolbox.TreeNode.prototype.onKeyDown = function(e) {
if (this.horizontalLayout_) {
var map = {};
map[goog.events.KeyCodes.RIGHT] = goog.events.KeyCodes.DOWN;
map[goog.events.KeyCodes.LEFT] = goog.events.KeyCodes.UP;
map[goog.events.KeyCodes.UP] = goog.events.KeyCodes.LEFT;
map[goog.events.KeyCodes.DOWN] = goog.events.KeyCodes.RIGHT;
2016-07-20 08:49:28 +05:00
var newKeyCode = map[e.keyCode];
e.keyCode = newKeyCode || e.keyCode;
}
return Blockly.Toolbox.TreeNode.superClass_.onKeyDown.call(this, e);
};
2014-11-24 17:34:27 -08:00
/**
* A blank separator node in the tree.
2016-05-25 12:53:42 -07:00
* @param {Object=} config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig. If not specified, a default config
* will be used.
2014-11-24 17:34:27 -08:00
* @constructor
2015-08-10 14:34:42 -05:00
* @extends {Blockly.Toolbox.TreeNode}
2014-11-24 17:34:27 -08:00
*/
Blockly.Toolbox.TreeSeparator = function(config) {
Blockly.Toolbox.TreeNode.call(this, null, '', config);
2014-11-24 17:34:27 -08:00
};
goog.inherits(Blockly.Toolbox.TreeSeparator, Blockly.Toolbox.TreeNode);