scratch-blocks/core/block.js

1557 lines
47 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 The class representing one block.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Block');
goog.require('Blockly.Blocks');
goog.require('Blockly.Colours');
goog.require('Blockly.Comment');
goog.require('Blockly.Connection');
goog.require('Blockly.Input');
goog.require('Blockly.Mutator');
goog.require('Blockly.Warning');
goog.require('Blockly.Workspace');
goog.require('Blockly.Xml');
goog.require('goog.array');
goog.require('goog.asserts');
2014-12-23 11:22:02 -08:00
goog.require('goog.math.Coordinate');
goog.require('goog.string');
/**
* Class for one block.
* Not normally called directly, workspace.newBlock() is preferred.
* @param {!Blockly.Workspace} workspace The block's workspace.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
2015-12-09 10:02:42 +01:00
* create a new id.
* @constructor
*/
2015-12-09 10:02:42 +01:00
Blockly.Block = function(workspace, prototypeName, opt_id) {
var flyoutWorkspace = workspace && workspace.getFlyout && workspace.getFlyout() ?
workspace.getFlyout().getWorkspace() : null;
2015-09-22 13:27:32 -05:00
/** @type {string} */
this.id = (opt_id && !workspace.getBlockById(opt_id) &&
(!flyoutWorkspace || !flyoutWorkspace.getBlockById(opt_id))) ?
2016-01-15 15:36:06 -08:00
opt_id : Blockly.genUid();
2016-04-05 18:43:39 -07:00
workspace.blockDB_[this.id] = this;
2015-07-13 15:03:22 -07:00
/** @type {Blockly.Connection} */
this.outputConnection = null;
2015-07-13 15:03:22 -07:00
/** @type {Blockly.Connection} */
this.nextConnection = null;
2015-07-13 15:03:22 -07:00
/** @type {Blockly.Connection} */
this.previousConnection = null;
2015-07-13 15:03:22 -07:00
/** @type {!Array.<!Blockly.Input>} */
this.inputList = [];
2015-07-13 15:03:22 -07:00
/** @type {boolean|undefined} */
2016-01-27 14:12:37 -05:00
this.inputsInline = true;
/** @type {boolean} */
this.disabled = false;
2015-07-13 15:03:22 -07:00
/** @type {string|!Function} */
this.tooltip = '';
/** @type {boolean} */
this.contextMenu = true;
2016-05-04 15:05:45 -07:00
/**
* @type {Blockly.Block}
* @private
*/
this.parentBlock_ = null;
2016-05-04 15:05:45 -07:00
/**
* @type {!Array.<!Blockly.Block>}
* @private
*/
this.childBlocks_ = [];
2016-05-04 15:05:45 -07:00
/**
* @type {boolean}
2016-05-04 15:05:45 -07:00
* @private
*/
this.deletable_ = true;
2016-05-04 15:05:45 -07:00
/**
* @type {boolean}
* @private
*/
this.movable_ = true;
2016-05-04 15:05:45 -07:00
/**
* @type {boolean}
* @private
*/
this.editable_ = true;
2016-05-04 15:05:45 -07:00
/**
* @type {boolean}
* @private
*/
2015-10-06 18:09:27 -07:00
this.isShadow_ = false;
2016-05-04 15:05:45 -07:00
/**
* @type {boolean}
* @private
*/
this.collapsed_ = false;
/**
* @type {boolean}
* @private
*/
this.checkboxInFlyout_ = false;
2015-07-13 15:03:22 -07:00
/** @type {string|Blockly.Comment} */
2014-12-23 11:22:02 -08:00
this.comment = null;
/**
* @type {?number}
* @private
*/
this.outputShape_ = null;
/**
* @type {?string}
* @private
*/
this.category_ = null;
2016-05-04 15:05:45 -07:00
/**
* @type {!goog.math.Coordinate}
* @private
*/
2014-12-23 11:22:02 -08:00
this.xy_ = new goog.math.Coordinate(0, 0);
2015-07-13 15:03:22 -07:00
/** @type {!Blockly.Workspace} */
this.workspace = workspace;
/** @type {boolean} */
this.isInFlyout = workspace.isFlyout;
/** @type {boolean} */
this.isInMutator = workspace.isMutator;
/** @type {boolean} */
2015-04-28 13:51:25 -07:00
this.RTL = workspace.RTL;
2016-02-23 14:46:04 -08:00
/** @type {boolean} */
2016-04-06 14:42:12 -07:00
this.isInsertionMarker_ = false;
2016-02-23 14:46:04 -08:00
// Copy the type-specific functions and data from the prototype.
if (prototypeName) {
2015-07-13 15:03:22 -07:00
/** @type {string} */
this.type = prototypeName;
var prototype = Blockly.Blocks[prototypeName];
goog.asserts.assertObject(prototype,
'Error: "%s" is an unknown language block.', prototypeName);
goog.mixin(this, prototype);
}
workspace.addTopBlock(this);
// Call an initialization function, if it exists.
if (goog.isFunction(this.init)) {
this.init();
}
// Record initial inline state.
2015-07-13 15:03:22 -07:00
/** @type {boolean|undefined} */
this.inputsInlineDefault = this.inputsInline;
2016-02-26 00:22:31 -08:00
if (Blockly.Events.isEnabled()) {
Blockly.Events.fire(new Blockly.Events.Create(this));
}
// Bind an onchange function, if it exists.
if (goog.isFunction(this.onchange)) {
this.onchangeWrapper_ = this.onchange.bind(this);
this.workspace.addChangeListener(this.onchangeWrapper_);
}
};
/**
* Optional text data that round-trips beween blocks and XML.
* Has no effect. May be used by 3rd parties for meta information.
* @type {?string}
*/
Blockly.Block.prototype.data = null;
2015-12-13 19:13:05 +01:00
/**
* Colour of the block in '#RRGGBB' format.
* @type {string}
* @private
*/
2016-07-14 12:16:23 -03:00
Blockly.Block.prototype.colour_ = '#FF0000';
2015-12-13 19:13:05 +01:00
/**
* Secondary colour of the block in '#RRGGBB' format.
* @type {string}
* @private
*/
2016-07-14 12:16:23 -03:00
Blockly.Block.prototype.colourSecondary_ = '#FF0000';
/**
* Tertiary colour of the block in '#RRGGBB' format.
* @type {string}
* @private
*/
2016-07-14 12:16:23 -03:00
Blockly.Block.prototype.colourTertiary_ = '#FF0000';
/**
* Dispose of this block.
* @param {boolean} healStack If true, then try to heal any gap by connecting
* the next statement with the previous statement. Otherwise, dispose of
* all children of this block.
*/
2016-02-01 16:13:05 -08:00
Blockly.Block.prototype.dispose = function(healStack) {
if (!this.workspace) {
// Already deleted.
return;
}
// Terminate onchange event calls.
if (this.onchangeWrapper_) {
2016-03-18 15:19:26 -07:00
this.workspace.removeChangeListener(this.onchangeWrapper_);
}
2016-02-01 16:13:05 -08:00
this.unplug(healStack);
2016-02-26 00:22:31 -08:00
if (Blockly.Events.isEnabled()) {
Blockly.Events.fire(new Blockly.Events.Delete(this));
}
Blockly.Events.disable();
try {
// This block is now at the top of the workspace.
// Remove this block from the workspace's list of top-most blocks.
if (this.workspace) {
this.workspace.removeTopBlock(this);
// Remove from block database.
delete this.workspace.blockDB_[this.id];
this.workspace = null;
}
// Just deleting this block from the DOM would result in a memory leak as
// well as corruption of the connection database. Therefore we must
// methodically step through the blocks and carefully disassemble them.
if (Blockly.selected == this) {
Blockly.selected = null;
}
2014-09-08 14:26:52 -07:00
// First, dispose of all my children.
for (var i = this.childBlocks_.length - 1; i >= 0; i--) {
this.childBlocks_[i].dispose(false);
}
// Then dispose of myself.
// Dispose of all inputs and their fields.
for (var i = 0, input; input = this.inputList[i]; i++) {
input.dispose();
}
this.inputList.length = 0;
// Dispose of any remaining connections (next/previous/output).
var connections = this.getConnections_(true);
for (var i = 0; i < connections.length; i++) {
var connection = connections[i];
if (connection.isConnected()) {
connection.disconnect();
}
connections[i].dispose();
}
} finally {
Blockly.Events.enable();
}
};
/**
* Unplug this block from its superior block. If this block is a statement,
* optionally reconnect the block underneath with the block on top.
* @param {boolean} opt_healStack Disconnect child statement and reconnect
* stack. Defaults to false.
*/
Blockly.Block.prototype.unplug = function(opt_healStack) {
if (this.outputConnection) {
2016-03-30 15:09:42 -07:00
if (this.outputConnection.isConnected()) {
// Disconnect from any superior block.
this.outputConnection.disconnect();
}
} else if (this.previousConnection) {
var previousTarget = null;
2016-03-30 15:09:42 -07:00
if (this.previousConnection.isConnected()) {
// Remember the connection that any next statements need to connect to.
previousTarget = this.previousConnection.targetConnection;
// Detach this block from the parent's tree.
this.previousConnection.disconnect();
}
2014-09-08 14:26:52 -07:00
var nextBlock = this.getNextBlock();
if (opt_healStack && nextBlock) {
// Disconnect the next statement.
var nextTarget = this.nextConnection.targetConnection;
nextTarget.disconnect();
if (previousTarget && previousTarget.checkType_(nextTarget)) {
// Attach the next statement to the previous statement.
previousTarget.connect(nextTarget);
}
}
}
};
/**
* Returns all connections originating from this block.
* @return {!Array.<!Blockly.Connection>} Array of connections.
* @private
*/
Blockly.Block.prototype.getConnections_ = function() {
var myConnections = [];
if (this.outputConnection) {
myConnections.push(this.outputConnection);
}
if (this.previousConnection) {
myConnections.push(this.previousConnection);
}
if (this.nextConnection) {
myConnections.push(this.nextConnection);
}
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.connection) {
myConnections.push(input.connection);
}
}
return myConnections;
};
/**
* Walks down a stack of blocks and finds the last next connection on the stack.
* @return {Blockly.Connection} The last next connection on the stack, or null.
* @private
*/
Blockly.Block.prototype.lastConnectionInStack = function() {
var nextConnection = this.nextConnection;
while (nextConnection) {
var nextBlock = nextConnection.targetBlock();
if (!nextBlock) {
// Found a next connection with nothing on the other side.
return nextConnection;
}
nextConnection = nextBlock.nextConnection;
}
// Ran out of next connections.
return null;
};
/**
* Bump unconnected blocks out of alignment. Two blocks which aren't actually
* connected should not coincidentally line up on screen.
* @private
*/
Blockly.Block.prototype.bumpNeighbours_ = function() {
2015-03-08 17:39:30 -07:00
if (!this.workspace) {
return; // Deleted block.
}
if (Blockly.dragMode_ != Blockly.DRAG_NONE) {
2015-03-08 17:39:30 -07:00
return; // Don't bump blocks during a drag.
}
var rootBlock = this.getRootBlock();
if (rootBlock.isInFlyout) {
2015-03-08 17:39:30 -07:00
return; // Don't move blocks around in a flyout.
}
// Loop though every connection on this block.
var myConnections = this.getConnections_(false);
2015-01-01 14:30:37 -08:00
for (var i = 0, connection; connection = myConnections[i]; i++) {
// Spider down from this block bumping all sub-blocks.
2016-03-30 15:09:42 -07:00
if (connection.isConnected() && connection.isSuperior()) {
connection.targetBlock().bumpNeighbours_();
}
var neighbours = connection.neighbours_(Blockly.SNAP_RADIUS);
2015-01-01 14:30:37 -08:00
for (var j = 0, otherConnection; otherConnection = neighbours[j]; j++) {
// If both connections are connected, that's probably fine. But if
// either one of them is unconnected, then there could be confusion.
2016-03-30 15:09:42 -07:00
if (!connection.isConnected() || !otherConnection.isConnected()) {
// Only bump blocks if they are from different tree structures.
if (otherConnection.getSourceBlock().getRootBlock() != rootBlock) {
// Always bump the inferior block.
if (connection.isSuperior()) {
otherConnection.bumpAwayFrom_(connection);
} else {
connection.bumpAwayFrom_(otherConnection);
}
}
}
}
}
};
/**
* Return the parent block or null if this block is at the top level.
* @return {Blockly.Block} The block that holds the current block.
*/
Blockly.Block.prototype.getParent = function() {
// Look at the DOM to see if we are nested in another block.
return this.parentBlock_;
};
/**
* Return the input that connects to the specified block.
2016-02-16 13:04:47 -08:00
* @param {!Blockly.Block} block A block connected to an input on this block.
* @return {Blockly.Input} The input that connects to the specified block.
*/
Blockly.Block.prototype.getInputWithBlock = function(block) {
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.connection && input.connection.targetBlock() == block) {
2016-03-18 15:19:26 -07:00
return input;
}
}
return null;
};
/**
* Return the input that contains the specified connection
* @param {!Blockly.Connection} conn A connection on this block.
* @return {Blockly.Input} The input that contains the specified connection.
*/
Blockly.Block.prototype.getInputWithConnection = function(conn) {
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.connection == conn) {
return input;
}
}
return null;
};
/**
* Return the parent block that surrounds the current block, or null if this
* block has no surrounding block. A parent block might just be the previous
* statement, whereas the surrounding block is an if statement, while loop, etc.
* @return {Blockly.Block} The block that surrounds the current block.
*/
Blockly.Block.prototype.getSurroundParent = function() {
var block = this;
2016-01-15 15:36:06 -08:00
do {
var prevBlock = block;
block = block.getParent();
if (!block) {
// Ran off the top.
return null;
}
} while (block.getNextBlock() == prevBlock);
// This block is an enclosing parent, not just a statement in a stack.
return block;
};
2014-09-08 14:26:52 -07:00
/**
* Return the next statement block directly connected to this block.
* @return {Blockly.Block} The next statement block or null.
*/
Blockly.Block.prototype.getNextBlock = function() {
return this.nextConnection && this.nextConnection.targetBlock();
};
2016-03-14 17:10:15 -07:00
/**
* Return the connection on the first statement input on this block, or null if
* there are none.
* @return {Blockly.Connection} The first statement connection or null.
*/
Blockly.Block.prototype.getFirstStatementConnection = function() {
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.connection && input.connection.type == Blockly.NEXT_STATEMENT) {
return input.connection;
}
}
return null;
};
/**
* Return the top-most block in this block's tree.
* This will return itself if this block is at the top level.
* @return {!Blockly.Block} The root block.
*/
Blockly.Block.prototype.getRootBlock = function() {
var rootBlock;
var block = this;
do {
rootBlock = block;
block = rootBlock.parentBlock_;
} while (block);
return rootBlock;
};
/**
* Find all the blocks that are directly nested inside this one.
* Includes value and block inputs, as well as any following statement.
* Excludes any connection on an output tab or any preceding statement.
* @return {!Array.<!Blockly.Block>} Array of blocks.
*/
Blockly.Block.prototype.getChildren = function() {
return this.childBlocks_;
};
/**
* Set parent of this block to be a new block or null.
* @param {Blockly.Block} newParent New parent block.
*/
Blockly.Block.prototype.setParent = function(newParent) {
if (newParent == this.parentBlock_) {
return;
2016-02-02 00:28:49 -08:00
}
if (this.parentBlock_) {
// Remove this block from the old parent's child list.
var children = this.parentBlock_.childBlocks_;
for (var child, x = 0; child = children[x]; x++) {
if (child == this) {
children.splice(x, 1);
break;
}
}
// Disconnect from superior blocks.
2016-03-30 15:09:42 -07:00
if (this.previousConnection && this.previousConnection.isConnected()) {
throw 'Still connected to previous block.';
}
2016-03-30 15:09:42 -07:00
if (this.outputConnection && this.outputConnection.isConnected()) {
throw 'Still connected to parent block.';
}
this.parentBlock_ = null;
// This block hasn't actually moved on-screen, so there's no need to update
// its connection locations.
} else {
// Remove this block from the workspace's list of top-most blocks.
2016-02-02 00:28:49 -08:00
this.workspace.removeTopBlock(this);
}
this.parentBlock_ = newParent;
if (newParent) {
// Add this block to the new parent's child list.
newParent.childBlocks_.push(this);
} else {
this.workspace.addTopBlock(this);
}
};
/**
* Find all the blocks that are directly or indirectly nested inside this one.
* Includes this block in the list.
* Includes value and block inputs, as well as any following statements.
* Excludes any connection on an output tab or any preceding statements.
* @param {boolean=} opt_ignoreShadows If set, don't include shadow blocks.
* @return {!Array.<!Blockly.Block>} Flattened array of blocks.
*/
Blockly.Block.prototype.getDescendants = function(opt_ignoreShadows) {
var blocks = [this];
for (var child, x = 0; child = this.childBlocks_[x]; x++) {
if (!opt_ignoreShadows || !child.isShadow_) {
blocks.push.apply(blocks, child.getDescendants(opt_ignoreShadows));
}
}
return blocks;
};
/**
* Get whether this block is deletable or not.
* @return {boolean} True if deletable.
*/
Blockly.Block.prototype.isDeletable = function() {
return this.deletable_ && !this.isShadow_ &&
2015-04-28 13:51:25 -07:00
!(this.workspace && this.workspace.options.readOnly);
};
/**
* Set whether this block is deletable or not.
* @param {boolean} deletable True if deletable.
*/
Blockly.Block.prototype.setDeletable = function(deletable) {
this.deletable_ = deletable;
};
/**
* Get whether this block is movable or not.
* @return {boolean} True if movable.
*/
Blockly.Block.prototype.isMovable = function() {
2015-10-06 18:09:27 -07:00
return this.movable_ && !this.isShadow_ &&
!(this.workspace && this.workspace.options.readOnly);
};
/**
* Set whether this block is movable or not.
* @param {boolean} movable True if movable.
*/
Blockly.Block.prototype.setMovable = function(movable) {
this.movable_ = movable;
};
2015-10-06 18:09:27 -07:00
/**
* Get whether this block is a shadow block or not.
* @return {boolean} True if a shadow.
*/
Blockly.Block.prototype.isShadow = function() {
return this.isShadow_;
};
/**
* Set whether this block is a shadow block or not.
* @param {boolean} shadow True if a shadow.
*/
Blockly.Block.prototype.setShadow = function(shadow) {
this.isShadow_ = shadow;
};
2016-02-23 14:46:04 -08:00
/**
2016-04-06 14:42:12 -07:00
* Get whether this block is an insertion marker block or not.
* @return {boolean} True if an insertion marker.
2016-02-23 14:46:04 -08:00
*/
2016-04-06 14:42:12 -07:00
Blockly.Block.prototype.isInsertionMarker = function() {
return this.isInsertionMarker_;
2016-02-23 14:46:04 -08:00
};
/**
2016-04-06 14:42:12 -07:00
* Set whether this block is an insertion marker block or not.
* @param {boolean} insertionMarker True if an insertion marker.
2016-02-23 14:46:04 -08:00
*/
2016-04-06 14:42:12 -07:00
Blockly.Block.prototype.setInsertionMarker = function(insertionMarker) {
if (this.isInsertionMarker_ == insertionMarker) {
2016-02-23 14:46:04 -08:00
return; // No change.
}
2016-04-06 14:42:12 -07:00
this.isInsertionMarker_ = insertionMarker;
if (this.isInsertionMarker_) {
this.setColour(Blockly.Colours.insertionMarker);
this.setOpacity(Blockly.Colours.insertionMarkerOpacity);
2016-02-23 14:46:04 -08:00
}
};
/**
* Get whether this block is editable or not.
* @return {boolean} True if editable.
*/
Blockly.Block.prototype.isEditable = function() {
2015-04-28 13:51:25 -07:00
return this.editable_ && !(this.workspace && this.workspace.options.readOnly);
};
/**
* Set whether this block is editable or not.
* @param {boolean} editable True if editable.
*/
Blockly.Block.prototype.setEditable = function(editable) {
this.editable_ = editable;
2015-01-01 14:30:37 -08:00
for (var i = 0, input; input = this.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
2013-12-20 16:25:26 -08:00
field.updateEditable();
}
}
};
2015-01-26 04:56:58 -08:00
/**
* Set whether the connections are hidden (not tracked in a database) or not.
* Recursively walk down all child blocks (except collapsed blocks).
2015-01-26 04:56:58 -08:00
* @param {boolean} hidden True if connections are hidden.
*/
Blockly.Block.prototype.setConnectionsHidden = function(hidden) {
if (!hidden && this.isCollapsed()) {
if (this.outputConnection) {
this.outputConnection.setHidden(hidden);
}
if (this.previousConnection) {
this.previousConnection.setHidden(hidden);
}
if (this.nextConnection) {
this.nextConnection.setHidden(hidden);
var child = this.nextConnection.targetBlock();
if (child) {
child.setConnectionsHidden(hidden);
}
}
} else {
var myConnections = this.getConnections_(true);
for (var i = 0, connection; connection = myConnections[i]; i++) {
connection.setHidden(hidden);
if (connection.isSuperior()) {
var child = connection.targetBlock();
if (child) {
child.setConnectionsHidden(hidden);
}
}
}
2015-01-26 04:56:58 -08:00
}
};
2016-03-04 14:39:24 -08:00
/**
* Find the connection on this block that corresponds to the given connection
* on the other block.
2016-04-06 14:42:12 -07:00
* Used to match connections between a block and its insertion marker.
2016-03-04 14:39:24 -08:00
* @param {!Blockly.Block} otherBlock The other block to match against.
* @param {!Blockly.Connection} conn The other connection to match.
* @return {Blockly.Connection} the matching connection on this block, or null.
*/
Blockly.Block.prototype.getMatchingConnection = function(otherBlock, conn) {
var connections = this.getConnections_(true);
var otherConnections = otherBlock.getConnections_(true);
if (connections.length != otherConnections.length) {
throw "Connection lists did not match in length.";
}
for (var i = 0; i < otherConnections.length; i++) {
if (otherConnections[i] == conn) {
return connections[i];
}
}
return null;
};
/**
* Set the URL of this block's help page.
* @param {string|Function} url URL string for block help, or function that
* returns a URL. Null for no help.
*/
Blockly.Block.prototype.setHelpUrl = function(url) {
this.helpUrl = url;
};
/**
* Change the tooltip text for a block.
* @param {string|!Function} newTip Text for tooltip or a parent element to
* link to for its tooltip. May be a function that returns a string.
*/
Blockly.Block.prototype.setTooltip = function(newTip) {
this.tooltip = newTip;
};
/**
* Get the colour of a block.
2015-12-13 19:13:05 +01:00
* @return {string} #RRGGBB string.
*/
Blockly.Block.prototype.getColour = function() {
2015-12-13 19:13:05 +01:00
return this.colour_;
};
/**
* Get the secondary colour of a block.
* @return {string} #RRGGBB string.
*/
Blockly.Block.prototype.getColourSecondary = function() {
return this.colourSecondary_;
};
/**
* Get the tertiary colour of a block.
* @return {string} #RRGGBB string.
*/
Blockly.Block.prototype.getColourTertiary = function() {
return this.colourTertiary_;
};
/**
* Create an #RRGGBB string colour from a colour HSV hue value or #RRGGBB string.
* @param {number|string} colour HSV hue value, or #RRGGBB string.
* @return {string} #RRGGBB string.
* @private
*/
Blockly.Block.prototype.makeColour_ = function(colour) {
2015-12-18 19:45:39 -08:00
var hue = parseFloat(colour);
if (!isNaN(hue)) {
return Blockly.hueToRgb(hue);
2015-12-13 19:13:05 +01:00
} else if (goog.isString(colour) && colour.match(/^#[0-9a-fA-F]{6}$/)) {
return colour;
2015-12-13 19:13:05 +01:00
} else {
throw 'Invalid colour: ' + colour;
}
2016-05-24 14:17:43 -07:00
};
/**
* Change the colour of a block, and optional secondary/teriarty colours.
* @param {number|string} colour HSV hue value, or #RRGGBB string.
* @param {number|string} colourSecondary HSV hue value, or #RRGGBB string.
* @param {number|string} colourTertiary HSV hue value, or #RRGGBB string.
*/
Blockly.Block.prototype.setColour = function(colour, colourSecondary, colourTertiary) {
this.colour_ = this.makeColour_(colour);
if (colourSecondary !== undefined) {
this.colourSecondary_ = this.makeColour_(colourSecondary);
} else {
2016-03-04 14:39:24 -08:00
this.colourSecondary_ = goog.color.darken(goog.color.hexToRgb(this.colour_),
0.1);
}
if (colourTertiary !== undefined) {
this.colourTertiary_ = this.makeColour_(colourTertiary);
} else {
2016-03-04 14:39:24 -08:00
this.colourTertiary_ = goog.color.darken(goog.color.hexToRgb(this.colour_),
0.2);
}
if (this.rendered) {
2014-12-23 11:22:02 -08:00
this.updateColour();
}
};
/**
2013-12-20 16:25:26 -08:00
* Returns the named field from a block.
* @param {string} name The name of the field.
* @return {Blockly.Field} Named field, or null if field does not exist.
*/
2015-07-02 16:14:10 -07:00
Blockly.Block.prototype.getField = function(name) {
2015-01-01 14:30:37 -08:00
for (var i = 0, input; input = this.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
2013-12-20 16:25:26 -08:00
if (field.name === name) {
return field;
}
}
}
return null;
};
/**
* Return all variables referenced by this block.
* @return {!Array.<string>} List of variable names.
*/
Blockly.Block.prototype.getVars = function() {
var vars = [];
for (var i = 0, input; input = this.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
if (field instanceof Blockly.FieldVariable) {
vars.push(field.getValue());
}
}
}
return vars;
};
/**
* Notification that a variable is renaming.
* If the name matches one of this block's variables, rename it.
* @param {string} oldName Previous name of variable.
* @param {string} newName Renamed variable.
*/
Blockly.Block.prototype.renameVar = function(oldName, newName) {
for (var i = 0, input; input = this.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
if (field instanceof Blockly.FieldVariable &&
Blockly.Names.equals(oldName, field.getValue())) {
field.setValue(newName);
}
}
}
};
/**
2013-12-20 16:25:26 -08:00
* Returns the language-neutral value from the field of a block.
* @param {string} name The name of the field.
* @return {?string} Value from the field or null if field does not exist.
*/
2013-12-20 16:25:26 -08:00
Blockly.Block.prototype.getFieldValue = function(name) {
2015-07-02 16:14:10 -07:00
var field = this.getField(name);
2013-12-20 16:25:26 -08:00
if (field) {
return field.getValue();
}
return null;
};
2013-12-20 16:25:26 -08:00
/**
* Change the field value for a block (e.g. 'CHOOSE' or 'REMOVE').
* @param {string} newValue Value to be the new field.
* @param {string} name The name of the field.
*/
Blockly.Block.prototype.setFieldValue = function(newValue, name) {
2015-07-02 16:14:10 -07:00
var field = this.getField(name);
2013-12-20 16:25:26 -08:00
goog.asserts.assertObject(field, 'Field "%s" not found.', name);
field.setValue(newValue);
};
/**
* Set whether this block can chain onto the bottom of another block.
* @param {boolean} newBoolean True if there can be a previous statement.
2015-07-13 15:03:22 -07:00
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
Blockly.Block.prototype.setPreviousStatement = function(newBoolean, opt_check) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.previousConnection) {
goog.asserts.assert(!this.outputConnection,
'Remove output connection prior to adding previous connection.');
2016-05-10 15:39:37 -07:00
this.previousConnection =
this.makeConnection_(Blockly.PREVIOUS_STATEMENT);
}
this.previousConnection.setCheck(opt_check);
} else {
if (this.previousConnection) {
goog.asserts.assert(!this.previousConnection.isConnected(),
'Must disconnect previous statement before removing connection.');
this.previousConnection.dispose();
this.previousConnection = null;
}
}
};
/**
* Set whether another block can chain onto the bottom of this block.
* @param {boolean} newBoolean True if there can be a next statement.
2015-07-13 15:03:22 -07:00
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
Blockly.Block.prototype.setNextStatement = function(newBoolean, opt_check) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.nextConnection) {
2016-05-10 15:39:37 -07:00
this.nextConnection = this.makeConnection_(Blockly.NEXT_STATEMENT);
}
this.nextConnection.setCheck(opt_check);
} else {
if (this.nextConnection) {
goog.asserts.assert(!this.nextConnection.isConnected(),
'Must disconnect next statement before removing connection.');
this.nextConnection.dispose();
this.nextConnection = null;
}
}
};
/**
* Set whether this block returns a value.
* @param {boolean} newBoolean True if there is an output.
2015-07-13 15:03:22 -07:00
* @param {string|Array.<string>|null|undefined} opt_check Returned type or list
* of returned types. Null or undefined if any type could be returned
* (e.g. variable get).
*/
Blockly.Block.prototype.setOutput = function(newBoolean, opt_check) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.outputConnection) {
goog.asserts.assert(!this.previousConnection,
'Remove previous connection prior to adding output connection.');
2016-05-10 15:39:37 -07:00
this.outputConnection = this.makeConnection_(Blockly.OUTPUT_VALUE);
}
this.outputConnection.setCheck(opt_check);
} else {
if (this.outputConnection) {
goog.asserts.assert(!this.outputConnection.isConnected(),
'Must disconnect output value before removing connection.');
this.outputConnection.dispose();
this.outputConnection = null;
}
}
};
/**
* Set whether value inputs are arranged horizontally or vertically.
* @param {boolean} newBoolean True if inputs are horizontal.
*/
Blockly.Block.prototype.setInputsInline = function(newBoolean) {
if (this.inputsInline != newBoolean) {
Blockly.Events.fire(new Blockly.Events.Change(
this, 'inline', null, this.inputsInline, newBoolean));
this.inputsInline = newBoolean;
}
};
/**
* Get whether value inputs are arranged horizontally or vertically.
* @return {boolean} True if inputs are horizontal.
*/
Blockly.Block.prototype.getInputsInline = function() {
if (this.inputsInline != undefined) {
// Set explicitly.
return this.inputsInline;
}
// Not defined explicitly. Figure out what would look best.
for (var i = 1; i < this.inputList.length; i++) {
if (this.inputList[i - 1].type == Blockly.DUMMY_INPUT &&
this.inputList[i].type == Blockly.DUMMY_INPUT) {
// Two dummy inputs in a row. Don't inline them.
return false;
}
}
for (var i = 1; i < this.inputList.length; i++) {
if (this.inputList[i - 1].type == Blockly.INPUT_VALUE &&
this.inputList[i].type == Blockly.DUMMY_INPUT) {
// Dummy input after a value input. Inline them.
return true;
}
}
return false;
};
/**
* Set whether the block is disabled or not.
* @param {boolean} disabled True if disabled.
*/
Blockly.Block.prototype.setDisabled = function(disabled) {
if (this.disabled != disabled) {
Blockly.Events.fire(new Blockly.Events.Change(
this, 'disabled', null, this.disabled, disabled));
this.disabled = disabled;
}
};
/**
* Get whether the block is disabled or not due to parents.
* The block's own disabled property is not considered.
* @return {boolean} True if disabled.
*/
Blockly.Block.prototype.getInheritedDisabled = function() {
var block = this;
while (true) {
block = block.getSurroundParent();
if (!block) {
// Ran off the top.
return false;
} else if (block.disabled) {
return true;
}
}
};
/**
* Get whether the block is collapsed or not.
* @return {boolean} True if collapsed.
*/
Blockly.Block.prototype.isCollapsed = function() {
return this.collapsed_;
};
/**
* Set whether the block is collapsed or not.
* @param {boolean} collapsed True if collapsed.
*/
Blockly.Block.prototype.setCollapsed = function(collapsed) {
2016-01-15 15:36:06 -08:00
if (this.collapsed_ != collapsed) {
Blockly.Events.fire(new Blockly.Events.Change(
this, 'collapsed', null, this.collapsed_, collapsed));
2016-01-15 15:36:06 -08:00
this.collapsed_ = collapsed;
}
};
/**
* Create a human-readable text representation of this block and any children.
2015-07-13 15:03:22 -07:00
* @param {number=} opt_maxLength Truncate the string to this length.
* @param {string=} opt_emptyToken The placeholder string used to denote an
* empty field. If not specified, '?' is used.
* @return {string} Text of block.
*/
Blockly.Block.prototype.toString = function(opt_maxLength, opt_emptyToken) {
var text = [];
var emptyFieldPlaceholder = opt_emptyToken || '?';
if (this.collapsed_) {
2015-03-02 12:45:20 -05:00
text.push(this.getInput('_TEMP_COLLAPSED_INPUT').fieldRow[0].text_);
} else {
for (var i = 0, input; input = this.inputList[i]; i++) {
for (var j = 0, field; field = input.fieldRow[j]; j++) {
text.push(field.getText());
}
if (input.connection) {
var child = input.connection.targetBlock();
if (child) {
text.push(child.toString(undefined, opt_emptyToken));
2015-03-02 12:45:20 -05:00
} else {
text.push(emptyFieldPlaceholder);
2015-03-02 12:45:20 -05:00
}
}
}
}
text = goog.string.trim(text.join(' ')) || '???';
if (opt_maxLength) {
// TODO: Improve truncation so that text from this block is given priority.
// E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not "1+2+3+4+5...".
// E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...".
text = goog.string.truncate(text, opt_maxLength);
}
return text;
};
/**
* Shortcut for appending a value input row.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
Blockly.Block.prototype.appendValueInput = function(name) {
return this.appendInput_(Blockly.INPUT_VALUE, name);
};
/**
* Shortcut for appending a statement input row.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
Blockly.Block.prototype.appendStatementInput = function(name) {
return this.appendInput_(Blockly.NEXT_STATEMENT, name);
};
/**
* Shortcut for appending a dummy input row.
2015-07-13 15:03:22 -07:00
* @param {string=} opt_name Language-neutral identifier which may used to find
* this input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
Blockly.Block.prototype.appendDummyInput = function(opt_name) {
return this.appendInput_(Blockly.DUMMY_INPUT, opt_name || '');
};
/**
* Initialize this block using a cross-platform, internationalization-friendly
* JSON description.
* @param {!Object} json Structured data describing the block.
*/
Blockly.Block.prototype.jsonInit = function(json) {
// Validate inputs.
goog.asserts.assert(json['output'] == undefined ||
json['previousStatement'] == undefined,
'Must not have both an output and a previousStatement.');
// Set basic properties of block.
if (json['colour'] !== undefined) {
this.setColour(json['colour'], json['colourSecondary'], json['colourTertiary']);
}
// Interpolate the message blocks.
var i = 0;
2015-07-01 22:49:44 -07:00
while (json['message' + i] !== undefined) {
this.interpolate_(json['message' + i], json['args' + i] || [],
json['lastDummyAlign' + i]);
i++;
}
if (json['inputsInline'] !== undefined) {
this.setInputsInline(json['inputsInline']);
}
// Set output and previous/next connections.
if (json['output'] !== undefined) {
this.setOutput(true, json['output']);
}
if (json['previousStatement'] !== undefined) {
this.setPreviousStatement(true, json['previousStatement']);
}
if (json['nextStatement'] !== undefined) {
this.setNextStatement(true, json['nextStatement']);
}
if (json['tooltip'] !== undefined) {
this.setTooltip(json['tooltip']);
}
if (json['helpUrl'] !== undefined) {
this.setHelpUrl(json['helpUrl']);
}
if (json['outputShape'] !== undefined) {
this.setOutputShape(json['outputShape']);
}
if (json['checkboxInFlyout'] !== undefined) {
this.setCheckboxInFlyout(json['checkboxInFlyout']);
}
if (json['category'] !== undefined) {
this.setCategory(json['category']);
}
};
/**
* Interpolate a message description onto the block.
2015-07-01 22:49:44 -07:00
* @param {string} message Text contains interpolation tokens (%1, %2, ...)
* that match with fields or inputs defined in the args array.
* @param {!Array} args Array of arguments to be interpolated.
* @param {string=} lastDummyAlign If a dummy input is added at the end,
* how should it be aligned?
* @private
*/
Blockly.Block.prototype.interpolate_ = function(message, args, lastDummyAlign) {
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
var tokens = Blockly.utils.tokenizeInterpolation(message);
2015-07-10 16:08:27 -07:00
// Interpolate the arguments. Build a list of elements.
var indexDup = [];
var indexCount = 0;
var elements = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
2015-07-10 16:08:27 -07:00
if (typeof token == 'number') {
goog.asserts.assert(token > 0 && token <= args.length,
'Message index "%s" out of range.', token);
2015-07-10 16:08:27 -07:00
goog.asserts.assert(!indexDup[token],
'Message index "%s" duplicated.', token);
2015-07-10 16:08:27 -07:00
indexDup[token] = true;
indexCount++;
2015-07-10 16:08:27 -07:00
elements.push(args[token - 1]);
} else {
2015-07-10 16:08:27 -07:00
token = token.trim();
if (token) {
elements.push(token);
}
}
}
goog.asserts.assert(indexCount == args.length,
'Message does not reference all %s arg(s).', args.length);
// Add last dummy input if needed.
2015-06-10 21:59:27 -07:00
if (elements.length && (typeof elements[elements.length - 1] == 'string' ||
elements[elements.length - 1]['type'].indexOf('field_') == 0)) {
2016-05-04 15:05:45 -07:00
var dummyInput = {type: 'input_dummy'};
if (lastDummyAlign) {
2016-05-04 15:05:45 -07:00
dummyInput['align'] = lastDummyAlign;
}
2016-05-04 15:05:45 -07:00
elements.push(dummyInput);
}
// Lookup of alignment constants.
var alignmentLookup = {
'LEFT': Blockly.ALIGN_LEFT,
'RIGHT': Blockly.ALIGN_RIGHT,
'CENTRE': Blockly.ALIGN_CENTRE
};
// Populate block with inputs and fields.
var fieldStack = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (typeof element == 'string') {
fieldStack.push([element, undefined]);
} else {
var field = null;
var input = null;
2015-07-01 22:49:44 -07:00
do {
var altRepeat = false;
if (typeof element == 'string') {
field = new Blockly.FieldLabel(element);
} else {
switch (element['type']) {
case 'input_value':
input = this.appendValueInput(element['name']);
break;
case 'input_statement':
input = this.appendStatementInput(element['name']);
break;
case 'input_dummy':
input = this.appendDummyInput(element['name']);
break;
case 'field_label':
field = new Blockly.FieldLabel(element['text'], element['class']);
break;
case 'field_input':
field = new Blockly.FieldTextInput(element['text']);
if (typeof element['spellcheck'] == 'boolean') {
field.setSpellcheck(element['spellcheck']);
}
break;
case 'field_angle':
field = new Blockly.FieldAngle(element['angle']);
break;
case 'field_checkbox':
field = new Blockly.FieldCheckbox(
element['checked'] ? 'TRUE' : 'FALSE');
2015-07-01 22:49:44 -07:00
break;
case 'field_colour':
field = new Blockly.FieldColour(element['colour']);
break;
case 'field_variable':
field = new Blockly.FieldVariable(element['variable']);
break;
case 'field_dropdown':
field = new Blockly.FieldDropdown(element['options']);
break;
case 'field_iconmenu':
field = new Blockly.FieldIconMenu(element['options']);
break;
case 'field_image':
field = new Blockly.FieldImage(element['src'],
element['width'], element['height'], element['alt'],
element['flip_rtl']);
break;
case 'field_number':
field = new Blockly.FieldNumber(element['value'],
element['min'], element['max'], element['precision']);
break;
case 'field_date':
if (Blockly.FieldDate) {
field = new Blockly.FieldDate(element['date']);
break;
}
// Fall through if FieldDate is not compiled in.
default:
// Unknown field.
if (element['alt']) {
element = element['alt'];
altRepeat = true;
}
}
2015-07-01 22:49:44 -07:00
}
} while (altRepeat);
if (field) {
fieldStack.push([field, element['name']]);
} else if (input) {
if (element['check']) {
input.setCheck(element['check']);
}
if (element['align']) {
input.setAlign(alignmentLookup[element['align']]);
}
for (var j = 0; j < fieldStack.length; j++) {
input.appendField(fieldStack[j][0], fieldStack[j][1]);
}
fieldStack.length = 0;
}
}
}
};
/**
* Add a value input, statement input or local variable to this block.
* @param {number} type Either Blockly.INPUT_VALUE or Blockly.NEXT_STATEMENT or
* Blockly.DUMMY_INPUT.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
* @private
*/
Blockly.Block.prototype.appendInput_ = function(type, name) {
var connection = null;
if (type == Blockly.INPUT_VALUE || type == Blockly.NEXT_STATEMENT) {
2016-05-10 15:39:37 -07:00
connection = this.makeConnection_(type);
}
var input = new Blockly.Input(type, name, this, connection);
// Append input to list.
this.inputList.push(input);
return input;
};
/**
2013-12-03 16:10:37 -08:00
* Move a named input to a different location on this block.
* @param {string} name The name of the input to move.
2013-12-03 16:10:37 -08:00
* @param {?string} refName Name of input that should be after the moved input,
* or null to be the input at the end.
*/
Blockly.Block.prototype.moveInputBefore = function(name, refName) {
2013-12-03 16:10:37 -08:00
if (name == refName) {
return;
}
// Find both inputs.
var inputIndex = -1;
var refIndex = refName ? -1 : this.inputList.length;
2015-01-01 14:30:37 -08:00
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.name == name) {
2015-01-01 14:30:37 -08:00
inputIndex = i;
if (refIndex != -1) {
break;
}
} else if (refName && input.name == refName) {
2015-01-01 14:30:37 -08:00
refIndex = i;
if (inputIndex != -1) {
break;
}
}
}
goog.asserts.assert(inputIndex != -1, 'Named input "%s" not found.', name);
2013-12-03 16:10:37 -08:00
goog.asserts.assert(refIndex != -1, 'Reference input "%s" not found.',
refName);
this.moveNumberedInputBefore(inputIndex, refIndex);
};
/**
* Move a numbered input to a different location on this block.
* @param {number} inputIndex Index of the input to move.
* @param {number} refIndex Index of input that should be after the moved input.
*/
Blockly.Block.prototype.moveNumberedInputBefore = function(
inputIndex, refIndex) {
2013-12-03 16:10:37 -08:00
// Validate arguments.
goog.asserts.assert(inputIndex != refIndex, 'Can\'t move input to itself.');
goog.asserts.assert(inputIndex < this.inputList.length,
'Input index ' + inputIndex + ' out of bounds.');
goog.asserts.assert(refIndex <= this.inputList.length,
'Reference input ' + refIndex + ' out of bounds.');
// Remove input.
2013-12-03 16:10:37 -08:00
var input = this.inputList[inputIndex];
this.inputList.splice(inputIndex, 1);
if (inputIndex < refIndex) {
refIndex--;
}
// Reinsert input.
this.inputList.splice(refIndex, 0, input);
};
/**
* Remove an input from this block.
* @param {string} name The name of the input.
2015-07-13 15:03:22 -07:00
* @param {boolean=} opt_quiet True to prevent error if input is not present.
* @throws {goog.asserts.AssertionError} if the input is not present and
* opt_quiet is not true.
*/
Blockly.Block.prototype.removeInput = function(name, opt_quiet) {
2015-01-01 14:30:37 -08:00
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.name == name) {
2016-03-30 15:09:42 -07:00
if (input.connection && input.connection.isConnected()) {
input.connection.setShadowDom(null);
var block = input.connection.targetBlock();
if (block.isShadow()) {
// Destroy any attached shadow block.
block.dispose();
} else {
// Disconnect any attached normal block.
block.unplug();
}
}
input.dispose();
2015-01-01 14:30:37 -08:00
this.inputList.splice(i, 1);
return;
}
}
if (!opt_quiet) {
goog.asserts.fail('Input "%s" not found.', name);
}
};
/**
* Fetches the named input object.
* @param {string} name The name of the input.
2016-03-18 15:19:26 -07:00
* @return {Blockly.Input} The input object, or null if input does not exist.
*/
Blockly.Block.prototype.getInput = function(name) {
2015-01-01 14:30:37 -08:00
for (var i = 0, input; input = this.inputList[i]; i++) {
if (input.name == name) {
return input;
}
}
// This input does not exist.
return null;
};
/**
* Fetches the block attached to the named input.
* @param {string} name The name of the input.
* @return {Blockly.Block} The attached value block, or null if the input is
* either disconnected or if the input does not exist.
*/
Blockly.Block.prototype.getInputTargetBlock = function(name) {
var input = this.getInput(name);
return input && input.connection && input.connection.targetBlock();
};
/**
* Returns the comment on this block (or '' if none).
* @return {string} Block's comment.
*/
Blockly.Block.prototype.getCommentText = function() {
2014-12-23 11:22:02 -08:00
return this.comment || '';
};
/**
* Set this block's comment text.
* @param {?string} text The text, or null to delete.
*/
Blockly.Block.prototype.setCommentText = function(text) {
2016-01-15 15:36:06 -08:00
if (this.comment != text) {
Blockly.Events.fire(new Blockly.Events.Change(
this, 'comment', null, this.comment, text || ''));
2016-01-15 15:36:06 -08:00
this.comment = text;
}
};
/**
* Set this block's output shape.
* e.g., null, OUTPUT_SHAPE_HEXAGONAL, OUTPUT_SHAPE_ROUND, OUTPUT_SHAPE_SQUARE.
* @param {?number} outputShape Value representing output shape
* (see constants.js).
*/
Blockly.Block.prototype.setOutputShape = function(outputShape) {
this.outputShape_ = outputShape;
};
/**
* Get this block's output shape.
* @return {?number} Value representing output shape (see constants.js).
*/
Blockly.Block.prototype.getOutputShape = function() {
return this.outputShape_;
};
/**
* Set this block's category (for styling purposes)
* @param {?string} category The block's category (see constants.js).
*/
Blockly.Block.prototype.setCategory = function(category) {
this.category_ = category;
};
/**
* Get this block's category (for styling purposes)
* @return {?string} category The block's category (see constants.js).
*/
Blockly.Block.prototype.getCategory = function() {
return this.category_;
};
/**
* Set whether this block has a checkbox next to it in the flyout.
* @param {boolean} hasCheckbox True if this block should have a checkbox.
*/
Blockly.Block.prototype.setCheckboxInFlyout = function(hasCheckbox) {
this.checkboxInFlyout_ = hasCheckbox;
};
/**
* Get whether this block has a checkbox next to it in the flyout.
* @return {boolean} True if this block should have a checkbox.
*/
Blockly.Block.prototype.hasCheckboxInFlyout = function() {
return this.checkboxInFlyout_;
};
/**
* Set this block's warning text.
* @param {?string} text The text, or null to delete.
* @abstract
*/
Blockly.Block.prototype.setWarningText = function(/*text*/) {
2014-12-23 11:22:02 -08:00
// NOP.
};
/**
2014-12-23 11:22:02 -08:00
* Give this block a mutator dialog.
* @param {Blockly.Mutator} mutator A mutator dialog instance or null to remove.
* @abstract
2014-12-23 11:22:02 -08:00
*/
Blockly.Block.prototype.setMutator = function(/*mutator*/) {
2014-12-23 11:22:02 -08:00
// NOP.
};
/**
* Return the coordinates of the top-left corner of this block relative to the
* drawing surface's origin (0,0).
* @return {!goog.math.Coordinate} Object with .x and .y properties.
*/
2014-12-23 11:22:02 -08:00
Blockly.Block.prototype.getRelativeToSurfaceXY = function() {
return this.xy_;
};
/**
* Move a block by a relative offset.
* @param {number} dx Horizontal offset.
* @param {number} dy Vertical offset.
*/
Blockly.Block.prototype.moveBy = function(dx, dy) {
2016-03-01 18:21:02 -08:00
goog.asserts.assert(!this.parentBlock_, 'Block has parent.');
2016-02-02 00:28:49 -08:00
var event = new Blockly.Events.Move(this);
2014-12-23 11:22:02 -08:00
this.xy_.translate(dx, dy);
2016-02-02 00:28:49 -08:00
event.recordNew();
Blockly.Events.fire(event);
};
2015-12-09 10:02:42 +01:00
/**
2016-05-10 15:39:37 -07:00
* Create a connection of the specified type.
* @param {number} type The type of the connection to create.
* @return {!Blockly.Connection} A new connection of the specified type.
2015-12-09 10:02:42 +01:00
* @private
*/
2016-05-10 15:39:37 -07:00
Blockly.Block.prototype.makeConnection_ = function(type) {
return new Blockly.Connection(this, type);
2015-12-09 10:02:42 +01:00
};