2013-10-30 14:46:03 -07:00
|
|
|
/**
|
2014-01-28 03:00:09 -08:00
|
|
|
* @license
|
2013-10-30 14:46:03 -07:00
|
|
|
* Visual Blocks Editor
|
|
|
|
*
|
|
|
|
* Copyright 2012 Google Inc.
|
2014-10-07 13:09:55 -07:00
|
|
|
* https://developers.google.com/blockly/
|
2013-10-30 14:46:03 -07:00
|
|
|
*
|
|
|
|
* 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 Utility methods.
|
2015-04-28 13:51:25 -07:00
|
|
|
* These methods are not specific to Blockly, and could be factored out into
|
|
|
|
* a JavaScript framework such as Closure.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @author fraser@google.com (Neil Fraser)
|
|
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
goog.provide('Blockly.utils');
|
|
|
|
|
2016-09-07 17:42:09 -07:00
|
|
|
goog.require('Blockly.Touch');
|
2015-09-01 12:22:50 +01:00
|
|
|
goog.require('goog.dom');
|
2015-02-06 15:27:25 -08:00
|
|
|
goog.require('goog.events.BrowserFeature');
|
2015-09-01 12:22:50 +01:00
|
|
|
goog.require('goog.math.Coordinate');
|
2015-02-23 16:04:18 -08:00
|
|
|
goog.require('goog.userAgent');
|
2015-02-06 15:27:25 -08:00
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
|
2016-04-11 14:19:56 -04:00
|
|
|
/**
|
|
|
|
* Cached value for whether 3D is supported
|
|
|
|
* @type {boolean}
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.cache3dSupported_ = null;
|
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
/**
|
|
|
|
* Add a CSS class to a element.
|
|
|
|
* Similar to Closure's goog.dom.classes.add, except it handles SVG elements.
|
|
|
|
* @param {!Element} element DOM element to add class to.
|
|
|
|
* @param {string} className Name of class to add.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.addClass_ = function(element, className) {
|
|
|
|
var classes = element.getAttribute('class') || '';
|
|
|
|
if ((' ' + classes + ' ').indexOf(' ' + className + ' ') == -1) {
|
|
|
|
if (classes) {
|
|
|
|
classes += ' ';
|
|
|
|
}
|
|
|
|
element.setAttribute('class', classes + className);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove a CSS class from a element.
|
|
|
|
* Similar to Closure's goog.dom.classes.remove, except it handles SVG elements.
|
|
|
|
* @param {!Element} element DOM element to remove class from.
|
|
|
|
* @param {string} className Name of class to remove.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.removeClass_ = function(element, className) {
|
|
|
|
var classes = element.getAttribute('class');
|
|
|
|
if ((' ' + classes + ' ').indexOf(' ' + className + ' ') != -1) {
|
|
|
|
var classList = classes.split(/\s+/);
|
|
|
|
for (var i = 0; i < classList.length; i++) {
|
|
|
|
if (!classList[i] || classList[i] == className) {
|
|
|
|
classList.splice(i, 1);
|
|
|
|
i--;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (classList.length) {
|
|
|
|
element.setAttribute('class', classList.join(' '));
|
|
|
|
} else {
|
|
|
|
element.removeAttribute('class');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-01-08 13:38:40 -08:00
|
|
|
/**
|
|
|
|
* Checks if an element has the specified CSS class.
|
|
|
|
* Similar to Closure's goog.dom.classes.has, except it handles SVG elements.
|
|
|
|
* @param {!Element} element DOM element to check.
|
|
|
|
* @param {string} className Name of class to check.
|
|
|
|
* @return {boolean} True if class exists, false otherwise.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.hasClass_ = function(element, className) {
|
|
|
|
var classes = element.getAttribute('class');
|
|
|
|
return (' ' + classes + ' ').indexOf(' ' + className + ' ') != -1;
|
|
|
|
};
|
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
/**
|
2016-09-23 13:46:57 -07:00
|
|
|
* Bind an event to a function call. When calling the function, verifies that
|
|
|
|
* it belongs to the touch stream that is currently being processsed, and splits
|
2016-09-23 13:46:11 -07:00
|
|
|
* multitouch events into multiple events as needed.
|
2014-09-08 14:26:52 -07:00
|
|
|
* @param {!Node} node Node upon which to listen.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @param {string} name Event name to listen to (e.g. 'mousedown').
|
|
|
|
* @param {Object} thisObject The value of 'this' in the function.
|
|
|
|
* @param {!Function} func Function to call when event is triggered.
|
2016-09-21 13:44:55 -07:00
|
|
|
* @param {boolean} opt_noCaptureIdentifier True if triggering on this event
|
|
|
|
* should not block execution of other event handlers on this touch or other
|
|
|
|
* simultaneous touches.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
|
|
|
|
* @private
|
|
|
|
*/
|
2016-09-23 13:46:11 -07:00
|
|
|
Blockly.bindEventWithChecks_ = function(node, name, thisObject, func,
|
2016-08-30 17:41:39 -07:00
|
|
|
opt_noCaptureIdentifier) {
|
2016-09-07 15:49:20 -07:00
|
|
|
var handled = false;
|
2016-07-21 14:07:03 -07:00
|
|
|
var wrapFunc = function(e) {
|
2016-08-31 18:04:27 -07:00
|
|
|
var captureIdentifier = !opt_noCaptureIdentifier;
|
2016-07-21 14:07:03 -07:00
|
|
|
// Handle each touch point separately. If the event was a mouse event, this
|
|
|
|
// will hand back an array with one element, which we're fine handling.
|
2016-09-07 17:42:09 -07:00
|
|
|
var events = Blockly.Touch.splitEventByTouches(e);
|
2016-08-18 14:46:28 -07:00
|
|
|
for (var i = 0, event; event = events[i]; i++) {
|
2016-09-07 17:42:09 -07:00
|
|
|
if (captureIdentifier && !Blockly.Touch.shouldHandleEvent(event)) {
|
2016-09-07 15:49:20 -07:00
|
|
|
continue;
|
2016-07-20 17:03:06 -07:00
|
|
|
}
|
2016-09-07 17:42:09 -07:00
|
|
|
Blockly.Touch.setClientFromTouch(event);
|
2016-07-21 14:07:03 -07:00
|
|
|
if (thisObject) {
|
|
|
|
func.call(thisObject, event);
|
2016-08-18 14:46:28 -07:00
|
|
|
} else {
|
2016-07-21 14:07:03 -07:00
|
|
|
func(event);
|
|
|
|
}
|
2016-09-07 15:49:20 -07:00
|
|
|
handled = true;
|
2016-07-21 14:07:03 -07:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-09-08 14:26:52 -07:00
|
|
|
node.addEventListener(name, wrapFunc, false);
|
|
|
|
var bindData = [[node, name, wrapFunc]];
|
2016-07-21 14:07:03 -07:00
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
// Add equivalent touch event.
|
2016-09-07 17:42:09 -07:00
|
|
|
if (name in Blockly.Touch.TOUCH_MAP) {
|
2016-07-21 14:07:03 -07:00
|
|
|
var touchWrapFunc = function(e) {
|
|
|
|
wrapFunc(e);
|
2015-01-27 20:28:33 -08:00
|
|
|
// Stop the browser from scrolling/zooming the page.
|
2016-09-07 15:49:20 -07:00
|
|
|
if (handled) {
|
|
|
|
e.preventDefault();
|
|
|
|
}
|
2013-10-30 14:46:03 -07:00
|
|
|
};
|
2014-09-08 14:26:52 -07:00
|
|
|
for (var i = 0, eventName;
|
2016-09-07 17:42:09 -07:00
|
|
|
eventName = Blockly.Touch.TOUCH_MAP[name][i]; i++) {
|
2016-07-21 14:07:03 -07:00
|
|
|
node.addEventListener(eventName, touchWrapFunc, false);
|
|
|
|
bindData.push([node, eventName, touchWrapFunc]);
|
2014-09-08 14:26:52 -07:00
|
|
|
}
|
2013-10-30 14:46:03 -07:00
|
|
|
}
|
|
|
|
return bindData;
|
|
|
|
};
|
|
|
|
|
2016-09-23 13:46:11 -07:00
|
|
|
|
|
|
|
/**
|
2016-09-23 13:46:57 -07:00
|
|
|
* Bind an event to a function call. Handles multitouch events by using the
|
|
|
|
* coordinates of the first changed touch, and doesn't do any safety checks for
|
2016-09-23 13:46:11 -07:00
|
|
|
* simultaneous event processing.
|
|
|
|
* @deprecated in favor of bindEventWithChecks_, but preserved for external
|
|
|
|
* users.
|
|
|
|
* @param {!Node} node Node upon which to listen.
|
|
|
|
* @param {string} name Event name to listen to (e.g. 'mousedown').
|
|
|
|
* @param {Object} thisObject The value of 'this' in the function.
|
|
|
|
* @param {!Function} func Function to call when event is triggered.
|
|
|
|
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.bindEvent_ = function(node, name, thisObject, func) {
|
|
|
|
var wrapFunc = function(e) {
|
|
|
|
if (thisObject) {
|
|
|
|
func.call(thisObject, e);
|
|
|
|
} else {
|
|
|
|
func(e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
node.addEventListener(name, wrapFunc, false);
|
|
|
|
var bindData = [[node, name, wrapFunc]];
|
|
|
|
|
|
|
|
// Add equivalent touch event.
|
|
|
|
if (name in Blockly.Touch.TOUCH_MAP) {
|
|
|
|
var touchWrapFunc = function(e) {
|
|
|
|
// Punt on multitouch events.
|
|
|
|
if (e.changedTouches.length == 1) {
|
|
|
|
// Map the touch event's properties to the event.
|
|
|
|
var touchPoint = e.changedTouches[0];
|
|
|
|
e.clientX = touchPoint.clientX;
|
|
|
|
e.clientY = touchPoint.clientY;
|
|
|
|
}
|
|
|
|
wrapFunc(e);
|
|
|
|
|
|
|
|
// Stop the browser from scrolling/zooming the page.
|
|
|
|
e.preventDefault();
|
|
|
|
};
|
|
|
|
for (var i = 0, eventName;
|
|
|
|
eventName = Blockly.Touch.TOUCH_MAP[name][i]; i++) {
|
2016-07-21 14:07:03 -07:00
|
|
|
node.addEventListener(eventName, touchWrapFunc, false);
|
|
|
|
bindData.push([node, eventName, touchWrapFunc]);
|
2014-09-08 14:26:52 -07:00
|
|
|
}
|
2013-10-30 14:46:03 -07:00
|
|
|
}
|
|
|
|
return bindData;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Unbind one or more events event from a function call.
|
|
|
|
* @param {!Array.<!Array>} bindData Opaque data from bindEvent_. This list is
|
|
|
|
* emptied during the course of calling this function.
|
|
|
|
* @return {!Function} The function call.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.unbindEvent_ = function(bindData) {
|
|
|
|
while (bindData.length) {
|
|
|
|
var bindDatum = bindData.pop();
|
2014-09-08 14:26:52 -07:00
|
|
|
var node = bindDatum[0];
|
2013-10-30 14:46:03 -07:00
|
|
|
var name = bindDatum[1];
|
|
|
|
var func = bindDatum[2];
|
2014-09-08 14:26:52 -07:00
|
|
|
node.removeEventListener(name, func, false);
|
2013-10-30 14:46:03 -07:00
|
|
|
}
|
|
|
|
return func;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Don't do anything for this event, just halt propagation.
|
|
|
|
* @param {!Event} e An event.
|
|
|
|
*/
|
|
|
|
Blockly.noEvent = function(e) {
|
|
|
|
// This event has been handled. No need to bubble up to the document.
|
|
|
|
e.preventDefault();
|
|
|
|
e.stopPropagation();
|
|
|
|
};
|
|
|
|
|
2015-04-28 13:51:25 -07:00
|
|
|
/**
|
|
|
|
* Is this event targeting a text input widget?
|
|
|
|
* @param {!Event} e An event.
|
|
|
|
* @return {boolean} True if text input.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.isTargetInput_ = function(e) {
|
|
|
|
return e.target.type == 'textarea' || e.target.type == 'text' ||
|
|
|
|
e.target.type == 'number' || e.target.type == 'email' ||
|
|
|
|
e.target.type == 'password' || e.target.type == 'search' ||
|
2015-06-22 15:42:25 -07:00
|
|
|
e.target.type == 'tel' || e.target.type == 'url' ||
|
|
|
|
e.target.isContentEditable;
|
2015-04-28 13:51:25 -07:00
|
|
|
};
|
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
/**
|
|
|
|
* Return the coordinates of the top-left corner of this element relative to
|
2015-04-28 13:51:25 -07:00
|
|
|
* its parent. Only for SVG elements and children (e.g. rect, g, path).
|
|
|
|
* @param {!Element} element SVG element to find the coordinates of.
|
2015-09-01 20:00:13 +01:00
|
|
|
* @return {!goog.math.Coordinate} Object with .x and .y properties.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.getRelativeXY_ = function(element) {
|
2015-09-01 20:00:13 +01:00
|
|
|
var xy = new goog.math.Coordinate(0, 0);
|
2013-10-30 14:46:03 -07:00
|
|
|
// First, check for x and y attributes.
|
|
|
|
var x = element.getAttribute('x');
|
|
|
|
if (x) {
|
|
|
|
xy.x = parseInt(x, 10);
|
|
|
|
}
|
|
|
|
var y = element.getAttribute('y');
|
|
|
|
if (y) {
|
|
|
|
xy.y = parseInt(y, 10);
|
|
|
|
}
|
|
|
|
// Second, check for transform="translate(...)" attribute.
|
|
|
|
var transform = element.getAttribute('transform');
|
2016-04-11 14:19:56 -04:00
|
|
|
if (transform) {
|
2016-05-24 14:17:43 -07:00
|
|
|
var transformComponents =
|
|
|
|
transform.match(Blockly.getRelativeXY_.XY_REGEXP_);
|
2016-04-11 14:19:56 -04:00
|
|
|
if (transformComponents) {
|
|
|
|
xy.x += parseFloat(transformComponents[1]);
|
|
|
|
if (transformComponents[3]) {
|
|
|
|
xy.y += parseFloat(transformComponents[3]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Third, check for style="transform: translate3d(...)".
|
|
|
|
var style = element.getAttribute('style');
|
|
|
|
if (style && style.indexOf('translate3d') > -1) {
|
|
|
|
var styleComponents = style.match(Blockly.getRelativeXY_.XY_3D_REGEXP_);
|
|
|
|
if (styleComponents) {
|
|
|
|
xy.x += parseFloat(styleComponents[1]);
|
|
|
|
if (styleComponents[3]) {
|
|
|
|
xy.y += parseFloat(styleComponents[3]);
|
|
|
|
}
|
2013-10-30 14:46:03 -07:00
|
|
|
}
|
|
|
|
}
|
2016-04-11 14:19:56 -04:00
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
return xy;
|
|
|
|
};
|
|
|
|
|
2015-08-26 14:08:03 +01:00
|
|
|
/**
|
|
|
|
* Static regex to pull the x,y values out of an SVG translate() directive.
|
|
|
|
* Note that Firefox and IE (9,10) return 'translate(12)' instead of
|
|
|
|
* 'translate(12, 0)'.
|
|
|
|
* Note that IE (9,10) returns 'translate(16 8)' instead of 'translate(16, 8)'.
|
|
|
|
* Note that IE has been reported to return scientific notation (0.123456e-42).
|
|
|
|
* @type {!RegExp}
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.getRelativeXY_.XY_REGEXP_ =
|
|
|
|
/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*\))?/;
|
|
|
|
|
2016-04-11 14:19:56 -04:00
|
|
|
/**
|
|
|
|
* Static regex to pull the x,y,z values out of a translate3d() style property.
|
|
|
|
* Accounts for same exceptions as XY_REGEXP_.
|
|
|
|
* @type {!RegExp}
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.getRelativeXY_.XY_3D_REGEXP_ =
|
|
|
|
/transform:\s*translate3d\(\s*([-+\d.e]+)px([ ,]\s*([-+\d.e]+)\s*)px([ ,]\s*([-+\d.e]+)\s*)px\)?/;
|
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
/**
|
2015-08-19 17:21:05 -07:00
|
|
|
* Return the absolute coordinates of the top-left corner of this element,
|
|
|
|
* scales that after canvas SVG element, if it's a descendant.
|
|
|
|
* The origin (0,0) is the top-left corner of the Blockly SVG.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @param {!Element} element Element to find the coordinates of.
|
2015-08-19 17:21:05 -07:00
|
|
|
* @param {!Blockly.Workspace} workspace Element must be in this workspace.
|
2015-09-01 12:22:50 +01:00
|
|
|
* @return {!goog.math.Coordinate} Object with .x and .y properties.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @private
|
|
|
|
*/
|
2015-08-19 17:21:05 -07:00
|
|
|
Blockly.getSvgXY_ = function(element, workspace) {
|
2013-10-30 14:46:03 -07:00
|
|
|
var x = 0;
|
|
|
|
var y = 0;
|
2015-09-01 20:00:13 +01:00
|
|
|
var scale = 1;
|
|
|
|
if (goog.dom.contains(workspace.getCanvas(), element) ||
|
|
|
|
goog.dom.contains(workspace.getBubbleCanvas(), element)) {
|
|
|
|
// Before the SVG canvas, scale the coordinates.
|
|
|
|
scale = workspace.scale;
|
|
|
|
}
|
2013-10-30 14:46:03 -07:00
|
|
|
do {
|
|
|
|
// Loop through this block and every parent.
|
|
|
|
var xy = Blockly.getRelativeXY_(element);
|
2015-08-19 17:21:05 -07:00
|
|
|
if (element == workspace.getCanvas() ||
|
|
|
|
element == workspace.getBubbleCanvas()) {
|
2015-09-01 20:00:13 +01:00
|
|
|
// After the SVG canvas, don't scale the coordinates.
|
|
|
|
scale = 1;
|
2015-08-19 17:21:05 -07:00
|
|
|
}
|
2015-09-01 20:00:13 +01:00
|
|
|
x += xy.x * scale;
|
|
|
|
y += xy.y * scale;
|
2013-10-30 14:46:03 -07:00
|
|
|
element = element.parentNode;
|
2016-01-07 17:01:01 -08:00
|
|
|
} while (element && element != workspace.getParentSvg());
|
2015-09-01 12:22:50 +01:00
|
|
|
return new goog.math.Coordinate(x, y);
|
2013-10-30 14:46:03 -07:00
|
|
|
};
|
|
|
|
|
2016-04-11 14:19:56 -04:00
|
|
|
/**
|
|
|
|
* Check if 3D transforms are supported by adding an element
|
|
|
|
* and attempting to set the property.
|
|
|
|
* @return {boolean} true if 3D transforms are supported
|
|
|
|
*/
|
|
|
|
Blockly.is3dSupported = function() {
|
|
|
|
if (Blockly.cache3dSupported_ !== null) {
|
|
|
|
return Blockly.cache3dSupported_;
|
|
|
|
}
|
|
|
|
// CC-BY-SA Lorenzo Polidori
|
|
|
|
// https://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
|
|
|
|
if (!window.getComputedStyle) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
var el = document.createElement('p'),
|
|
|
|
has3d,
|
|
|
|
transforms = {
|
2016-05-24 14:17:43 -07:00
|
|
|
'webkitTransform': '-webkit-transform',
|
|
|
|
'OTransform': '-o-transform',
|
|
|
|
'msTransform': '-ms-transform',
|
|
|
|
'MozTransform': '-moz-transform',
|
|
|
|
'transform': 'transform'
|
|
|
|
};
|
2016-04-11 14:19:56 -04:00
|
|
|
|
|
|
|
// Add it to the body to get the computed style.
|
|
|
|
document.body.insertBefore(el, null);
|
|
|
|
|
|
|
|
for (var t in transforms) {
|
|
|
|
if (el.style[t] !== undefined) {
|
2016-05-24 14:17:43 -07:00
|
|
|
el.style[t] = 'translate3d(1px,1px,1px)';
|
2016-04-11 14:19:56 -04:00
|
|
|
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
document.body.removeChild(el);
|
|
|
|
Blockly.cache3dSupported_ = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
|
|
|
|
return Blockly.cache3dSupported_;
|
|
|
|
};
|
|
|
|
|
2013-10-30 14:46:03 -07:00
|
|
|
/**
|
|
|
|
* Helper method for creating SVG elements.
|
|
|
|
* @param {string} name Element's tag name.
|
|
|
|
* @param {!Object} attrs Dictionary of attribute names and values.
|
2015-08-19 17:21:05 -07:00
|
|
|
* @param {Element} parent Optional parent on which to append the element.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {!SVGElement} Newly created SVG element.
|
|
|
|
*/
|
2016-08-30 15:50:59 -04:00
|
|
|
Blockly.createSvgElement = function(name, attrs, parent) {
|
2013-10-30 14:46:03 -07:00
|
|
|
var e = /** @type {!SVGElement} */ (
|
|
|
|
document.createElementNS(Blockly.SVG_NS, name));
|
|
|
|
for (var key in attrs) {
|
|
|
|
e.setAttribute(key, attrs[key]);
|
|
|
|
}
|
|
|
|
// IE defines a unique attribute "runtimeStyle", it is NOT applied to
|
|
|
|
// elements created with createElementNS. However, Closure checks for IE
|
|
|
|
// and assumes the presence of the attribute and crashes.
|
|
|
|
if (document.body.runtimeStyle) { // Indicates presence of IE-only attr.
|
|
|
|
e.runtimeStyle = e.currentStyle = e.style;
|
|
|
|
}
|
2015-08-19 17:21:05 -07:00
|
|
|
if (parent) {
|
|
|
|
parent.appendChild(e);
|
2013-10-30 14:46:03 -07:00
|
|
|
}
|
|
|
|
return e;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Is this event a right-click?
|
|
|
|
* @param {!Event} e Mouse event.
|
|
|
|
* @return {boolean} True if right-click.
|
|
|
|
*/
|
|
|
|
Blockly.isRightButton = function(e) {
|
2015-02-23 16:04:18 -08:00
|
|
|
if (e.ctrlKey && goog.userAgent.MAC) {
|
|
|
|
// Control-clicking on Mac OS X is treated as a right-click.
|
|
|
|
// WebKit on Mac OS X fails to change button to 2 (but Gecko does).
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return e.button == 2;
|
2013-10-30 14:46:03 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the converted coordinates of the given mouse event.
|
|
|
|
* The origin (0,0) is the top-left corner of the Blockly svg.
|
|
|
|
* @param {!Event} e Mouse event.
|
2015-04-28 13:51:25 -07:00
|
|
|
* @param {!Element} svg SVG element.
|
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
|
|
|
* @param {SVGMatrix} matrix Inverted screen CTM to use.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {!Object} Object with .x and .y properties.
|
|
|
|
*/
|
Merge google/develop June 22 (#441)
* Localisation updates from https://translatewiki.net.
* test page that creates random blocks and randomly drags them around the page
* Localisation updates from https://translatewiki.net.
* add missing return in fake drag
* get rid of drag_tests file:
* Generated JS helper functions should be camelCase.
Complying with Google style guide.
* Localisation updates from https://translatewiki.net.
* Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues.
* Remove claim that good.string.quote should be used.
* Change the blockly workspace resizing strategy. (#386)
* Add a new method to be called when the contents of the workspace change and
the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc)
are expected to stay in the same place.
Change a bunch of calls to svgResize to either be removed or call the new
method instead. This is a nice performance win since the offsetHeight/Width
call in svgResize can be expensive, especially when called as often as we do -
there was some layout thrashing.
This also paves the way for moving calls to recordDeleteAreas
(which is also expensive) to a more cacheable spot than on every
mouse down/touch event.
of things (namely the scrollbars)
* Fix size of graph demo when it first loads by calling svgResize.
The graph starts with fixed width and was relying on a resize event
to fire (which I believe was removed in commit
217c681b86b0f2df76c479c9efae62e6e).
* Fix the resizing of the code demo. The demo's tab min-width used to
match the toolbox's width was only being set on a resize event, but
commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked.
* Fix up some comments.
* Use specific workspaces rather than Blockly.getMainWorkspace().
* Make workspace required for resizeSvgContents and update
some calls to send real workspaces rather than ones that are
null.
Remove the private tag on terminateDrag_ because it is only
actually called from outside the BlockSvg object.
* Remove a rogue period.
* Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that
other developers don't use it, but it still can be used by other Blockly classes.
* Add a TODO to fix issue #307.
* Add @package to workspace resizeContents.
* Routine recompile
* Fix unit tests.
* Fix inheritance on rendered connection.
Closure compiler on maximum compression breaks badly due to lack of
@extends attribute.
* Add toolbox location and toolbox mode options to playground.
* Increase commonality between playgrounds.
* Properly deal with shadow statement blocks in stacks.
* Localisation updates from https://translatewiki.net.
* Use a comment block for function comments in generated JS, Python and Dart.
* Fix typo in flyout.js (#403)
* Fix typo in flyout.js (#402)
* Line wrap comments in generated code.
* Remove reference to undefined variable (#413)
REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1.
* Fix airstrike by grabbing the correct toolbox element. (#411)
Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173.
* Localisation updates from https://translatewiki.net.
* Fix issue #406 by calling resize from the keypress handler on text inputs. (#408)
* Remove shadow blocks from Accessible Blockly demo. Update README.
* Generate for loops on one line.
* Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting.
* Fix precedence on isIndex blocks.
* Add indexing setting for JavaScript Generation (#419)
Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default.
* Remove unused functions and dependencies.
* Remove the unnecessary construction of new services.
* Fix sort block in JS to satisfy tests.
* Trigger a contents resize in block's moveBy. (#422)
This fixes #420 but and it also fixes some other similar problems
with copy/paste and other users of moveBy.
* Consolidate the usages of the 'blockly-disabled' label.
* Fix error when undoing a shadow block replacement. Issue #415.
* Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks.
* Standardize naming of components.
* Prevent collisions between user functions and helper functions.
* Localisation updates from https://translatewiki.net.
* Fix #425. Attash the resize handler to the workspace so it can be removed (#429)
when workspace.dispose() is called.
* Change the TreeService to a singleton.
* Remove unneeded generated parens around function calls in indexOf blocks.
* Fix #423 by calling workspace's resize when the flyout reflows. (#430)
* Updating URLs to reflect new docs. (#418)
* Updating URLs to reflect new docs. Removing -blockly in URLs.
* Rebuilt.
* Routine recompile
* Prevent selected block from ending up underneath a bumped block.
* Fix undo on fields with validators with side effects.
* Don't fire change event on fields that haven't been named yet.
* Localisation updates from https://translatewiki.net.
* Fix tree focus issues.
* Fix remaining focus issues on block deletion.
* cache delete areas instead of recalculating them onMouseDown
* Cache screen CTM for performance improvement.
* Call svgResizeContents from block_svg's dipose so that deleting blocks (#434)
from the context menu (or anywhere really) causes the workspace to
recalculate its size.
Remove the call to svgResizeContents from onMouseUp's logic for
determining whether the block is being dropped in the trash
since it calls dispose.
One side effect of this is that when you delete multiple blocks
resize gets called for each of them and the scrollbars move during
the operation. This is most obviously seen by doing an airstrike
in the playground and then deleting all the blocks at once.
* Allow terminal blocks to replace other terminal blocks (#433)
* Allow terminal blocks to replace other terminal blocks
* Updated test to allow replacing terminal blocks
* Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus.
* Localisation updates from https://translatewiki.net.
* Remove unnecessary logging.
* Reduce unneeded parentheses in JS and Python.
* Start using field_number.
* Make it easy to disable unconnected blocks.
* Routine recompile.
* Check if matrix is null in mouseToSvg
* Remove js/ localizations pre-merge
* Fix change to block_render_svg
* Fix error in xml.js
* Playground merge
* Add simple toolboxes to playgrounds
* Fix flyout reference in events listener
* Move tokenizeIntepolation into Blockly.utils namespace.
* Use simpler message interpolation in Code demo.
* Create console stub for IE 9.
* Don't output blockId if not set (e.g., toolbox category event). (#443)
* Fix block in multi-playground
* Increase commonality between playgrounds.
# Conflicts:
# tests/multi_playground.html
# tests/playground.html
* Remove "show flyouts" button
* Recompile for merge June 22
2016-06-22 17:50:16 -04:00
|
|
|
Blockly.mouseToSvg = function(e, svg, matrix) {
|
2015-05-19 12:02:34 -07:00
|
|
|
var svgPoint = svg.createSVGPoint();
|
|
|
|
svgPoint.x = e.clientX;
|
|
|
|
svgPoint.y = e.clientY;
|
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 (!matrix) {
|
|
|
|
matrix = svg.getScreenCTM().inverse();
|
|
|
|
}
|
2015-05-19 12:02:34 -07:00
|
|
|
return svgPoint.matrixTransform(matrix);
|
2013-10-30 14:46:03 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given an array of strings, return the length of the shortest one.
|
2014-02-01 03:00:04 -08:00
|
|
|
* @param {!Array.<string>} array Array of strings.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {number} Length of shortest string.
|
|
|
|
*/
|
|
|
|
Blockly.shortestStringLength = function(array) {
|
|
|
|
if (!array.length) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
var len = array[0].length;
|
|
|
|
for (var i = 1; i < array.length; i++) {
|
|
|
|
len = Math.min(len, array[i].length);
|
|
|
|
}
|
|
|
|
return len;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given an array of strings, return the length of the common prefix.
|
|
|
|
* Words may not be split. Any space after a word is included in the length.
|
2014-02-01 03:00:04 -08:00
|
|
|
* @param {!Array.<string>} array Array of strings.
|
2015-07-13 15:03:22 -07:00
|
|
|
* @param {number=} opt_shortest Length of shortest string.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {number} Length of common prefix.
|
|
|
|
*/
|
|
|
|
Blockly.commonWordPrefix = function(array, opt_shortest) {
|
|
|
|
if (!array.length) {
|
|
|
|
return 0;
|
|
|
|
} else if (array.length == 1) {
|
|
|
|
return array[0].length;
|
|
|
|
}
|
|
|
|
var wordPrefix = 0;
|
|
|
|
var max = opt_shortest || Blockly.shortestStringLength(array);
|
|
|
|
for (var len = 0; len < max; len++) {
|
|
|
|
var letter = array[0][len];
|
|
|
|
for (var i = 1; i < array.length; i++) {
|
|
|
|
if (letter != array[i][len]) {
|
|
|
|
return wordPrefix;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (letter == ' ') {
|
|
|
|
wordPrefix = len + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (var i = 1; i < array.length; i++) {
|
|
|
|
var letter = array[i][len];
|
|
|
|
if (letter && letter != ' ') {
|
|
|
|
return wordPrefix;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return max;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given an array of strings, return the length of the common suffix.
|
|
|
|
* Words may not be split. Any space after a word is included in the length.
|
2014-02-01 03:00:04 -08:00
|
|
|
* @param {!Array.<string>} array Array of strings.
|
2015-07-13 15:03:22 -07:00
|
|
|
* @param {number=} opt_shortest Length of shortest string.
|
2013-10-30 14:46:03 -07:00
|
|
|
* @return {number} Length of common suffix.
|
|
|
|
*/
|
|
|
|
Blockly.commonWordSuffix = function(array, opt_shortest) {
|
|
|
|
if (!array.length) {
|
|
|
|
return 0;
|
|
|
|
} else if (array.length == 1) {
|
|
|
|
return array[0].length;
|
|
|
|
}
|
|
|
|
var wordPrefix = 0;
|
|
|
|
var max = opt_shortest || Blockly.shortestStringLength(array);
|
|
|
|
for (var len = 0; len < max; len++) {
|
|
|
|
var letter = array[0].substr(-len - 1, 1);
|
|
|
|
for (var i = 1; i < array.length; i++) {
|
|
|
|
if (letter != array[i].substr(-len - 1, 1)) {
|
|
|
|
return wordPrefix;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (letter == ' ') {
|
|
|
|
wordPrefix = len + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (var i = 1; i < array.length; i++) {
|
|
|
|
var letter = array[i].charAt(array[i].length - len - 1);
|
|
|
|
if (letter && letter != ' ') {
|
|
|
|
return wordPrefix;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return max;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Is the given string a number (includes negative and decimals).
|
|
|
|
* @param {string} str Input string.
|
|
|
|
* @return {boolean} True if number, false otherwise.
|
|
|
|
*/
|
|
|
|
Blockly.isNumber = function(str) {
|
|
|
|
return !!str.match(/^\s*-?\d+(\.\d+)?\s*$/);
|
|
|
|
};
|
2015-07-10 16:08:27 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Parse a string with any number of interpolation tokens (%1, %2, ...).
|
|
|
|
* '%' characters may be self-escaped (%%).
|
|
|
|
* @param {string} message Text containing interpolation tokens.
|
|
|
|
* @return {!Array.<string|number>} Array of strings and numbers.
|
|
|
|
*/
|
Merge google/develop June 22 (#441)
* Localisation updates from https://translatewiki.net.
* test page that creates random blocks and randomly drags them around the page
* Localisation updates from https://translatewiki.net.
* add missing return in fake drag
* get rid of drag_tests file:
* Generated JS helper functions should be camelCase.
Complying with Google style guide.
* Localisation updates from https://translatewiki.net.
* Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues.
* Remove claim that good.string.quote should be used.
* Change the blockly workspace resizing strategy. (#386)
* Add a new method to be called when the contents of the workspace change and
the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc)
are expected to stay in the same place.
Change a bunch of calls to svgResize to either be removed or call the new
method instead. This is a nice performance win since the offsetHeight/Width
call in svgResize can be expensive, especially when called as often as we do -
there was some layout thrashing.
This also paves the way for moving calls to recordDeleteAreas
(which is also expensive) to a more cacheable spot than on every
mouse down/touch event.
of things (namely the scrollbars)
* Fix size of graph demo when it first loads by calling svgResize.
The graph starts with fixed width and was relying on a resize event
to fire (which I believe was removed in commit
217c681b86b0f2df76c479c9efae62e6e).
* Fix the resizing of the code demo. The demo's tab min-width used to
match the toolbox's width was only being set on a resize event, but
commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked.
* Fix up some comments.
* Use specific workspaces rather than Blockly.getMainWorkspace().
* Make workspace required for resizeSvgContents and update
some calls to send real workspaces rather than ones that are
null.
Remove the private tag on terminateDrag_ because it is only
actually called from outside the BlockSvg object.
* Remove a rogue period.
* Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that
other developers don't use it, but it still can be used by other Blockly classes.
* Add a TODO to fix issue #307.
* Add @package to workspace resizeContents.
* Routine recompile
* Fix unit tests.
* Fix inheritance on rendered connection.
Closure compiler on maximum compression breaks badly due to lack of
@extends attribute.
* Add toolbox location and toolbox mode options to playground.
* Increase commonality between playgrounds.
* Properly deal with shadow statement blocks in stacks.
* Localisation updates from https://translatewiki.net.
* Use a comment block for function comments in generated JS, Python and Dart.
* Fix typo in flyout.js (#403)
* Fix typo in flyout.js (#402)
* Line wrap comments in generated code.
* Remove reference to undefined variable (#413)
REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1.
* Fix airstrike by grabbing the correct toolbox element. (#411)
Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173.
* Localisation updates from https://translatewiki.net.
* Fix issue #406 by calling resize from the keypress handler on text inputs. (#408)
* Remove shadow blocks from Accessible Blockly demo. Update README.
* Generate for loops on one line.
* Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting.
* Fix precedence on isIndex blocks.
* Add indexing setting for JavaScript Generation (#419)
Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default.
* Remove unused functions and dependencies.
* Remove the unnecessary construction of new services.
* Fix sort block in JS to satisfy tests.
* Trigger a contents resize in block's moveBy. (#422)
This fixes #420 but and it also fixes some other similar problems
with copy/paste and other users of moveBy.
* Consolidate the usages of the 'blockly-disabled' label.
* Fix error when undoing a shadow block replacement. Issue #415.
* Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks.
* Standardize naming of components.
* Prevent collisions between user functions and helper functions.
* Localisation updates from https://translatewiki.net.
* Fix #425. Attash the resize handler to the workspace so it can be removed (#429)
when workspace.dispose() is called.
* Change the TreeService to a singleton.
* Remove unneeded generated parens around function calls in indexOf blocks.
* Fix #423 by calling workspace's resize when the flyout reflows. (#430)
* Updating URLs to reflect new docs. (#418)
* Updating URLs to reflect new docs. Removing -blockly in URLs.
* Rebuilt.
* Routine recompile
* Prevent selected block from ending up underneath a bumped block.
* Fix undo on fields with validators with side effects.
* Don't fire change event on fields that haven't been named yet.
* Localisation updates from https://translatewiki.net.
* Fix tree focus issues.
* Fix remaining focus issues on block deletion.
* cache delete areas instead of recalculating them onMouseDown
* Cache screen CTM for performance improvement.
* Call svgResizeContents from block_svg's dipose so that deleting blocks (#434)
from the context menu (or anywhere really) causes the workspace to
recalculate its size.
Remove the call to svgResizeContents from onMouseUp's logic for
determining whether the block is being dropped in the trash
since it calls dispose.
One side effect of this is that when you delete multiple blocks
resize gets called for each of them and the scrollbars move during
the operation. This is most obviously seen by doing an airstrike
in the playground and then deleting all the blocks at once.
* Allow terminal blocks to replace other terminal blocks (#433)
* Allow terminal blocks to replace other terminal blocks
* Updated test to allow replacing terminal blocks
* Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus.
* Localisation updates from https://translatewiki.net.
* Remove unnecessary logging.
* Reduce unneeded parentheses in JS and Python.
* Start using field_number.
* Make it easy to disable unconnected blocks.
* Routine recompile.
* Check if matrix is null in mouseToSvg
* Remove js/ localizations pre-merge
* Fix change to block_render_svg
* Fix error in xml.js
* Playground merge
* Add simple toolboxes to playgrounds
* Fix flyout reference in events listener
* Move tokenizeIntepolation into Blockly.utils namespace.
* Use simpler message interpolation in Code demo.
* Create console stub for IE 9.
* Don't output blockId if not set (e.g., toolbox category event). (#443)
* Fix block in multi-playground
* Increase commonality between playgrounds.
# Conflicts:
# tests/multi_playground.html
# tests/playground.html
* Remove "show flyouts" button
* Recompile for merge June 22
2016-06-22 17:50:16 -04:00
|
|
|
Blockly.utils.tokenizeInterpolation = function(message) {
|
2015-07-10 16:08:27 -07:00
|
|
|
var tokens = [];
|
|
|
|
var chars = message.split('');
|
|
|
|
chars.push(''); // End marker.
|
|
|
|
// Parse the message with a finite state machine.
|
|
|
|
// 0 - Base case.
|
|
|
|
// 1 - % found.
|
|
|
|
// 2 - Digit found.
|
|
|
|
var state = 0;
|
|
|
|
var buffer = [];
|
|
|
|
var number = null;
|
|
|
|
for (var i = 0; i < chars.length; i++) {
|
|
|
|
var c = chars[i];
|
|
|
|
if (state == 0) {
|
|
|
|
if (c == '%') {
|
|
|
|
state = 1; // Start escape.
|
|
|
|
} else {
|
|
|
|
buffer.push(c); // Regular char.
|
|
|
|
}
|
|
|
|
} else if (state == 1) {
|
|
|
|
if (c == '%') {
|
|
|
|
buffer.push(c); // Escaped %: %%
|
|
|
|
state = 0;
|
|
|
|
} else if ('0' <= c && c <= '9') {
|
|
|
|
state = 2;
|
|
|
|
number = c;
|
|
|
|
var text = buffer.join('');
|
|
|
|
if (text) {
|
|
|
|
tokens.push(text);
|
|
|
|
}
|
|
|
|
buffer.length = 0;
|
|
|
|
} else {
|
|
|
|
buffer.push('%', c); // Not an escape: %a
|
|
|
|
state = 0;
|
|
|
|
}
|
|
|
|
} else if (state == 2) {
|
|
|
|
if ('0' <= c && c <= '9') {
|
|
|
|
number += c; // Multi-digit number.
|
|
|
|
} else {
|
|
|
|
tokens.push(parseInt(number, 10));
|
|
|
|
i--; // Parse this char again.
|
|
|
|
state = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var text = buffer.join('');
|
|
|
|
if (text) {
|
|
|
|
tokens.push(text);
|
|
|
|
}
|
|
|
|
return tokens;
|
|
|
|
};
|
2015-11-19 01:46:53 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a unique ID. This should be globally unique.
|
2016-02-16 22:16:36 -08:00
|
|
|
* 87 characters ^ 20 length > 128 bits (better than a UUID).
|
2016-05-04 15:05:45 -07:00
|
|
|
* @return {string} A globally unique ID string.
|
2015-11-19 01:46:53 -08:00
|
|
|
*/
|
|
|
|
Blockly.genUid = function() {
|
2015-11-24 19:16:01 -08:00
|
|
|
var length = 20;
|
|
|
|
var soupLength = Blockly.genUid.soup_.length;
|
2015-11-19 01:46:53 -08:00
|
|
|
var id = [];
|
2016-03-22 10:48:13 -07:00
|
|
|
for (var i = 0; i < length; i++) {
|
|
|
|
id[i] = Blockly.genUid.soup_.charAt(Math.random() * soupLength);
|
2015-11-19 01:46:53 -08:00
|
|
|
}
|
|
|
|
return id.join('');
|
|
|
|
};
|
2015-11-24 19:16:01 -08:00
|
|
|
|
|
|
|
/**
|
2016-10-06 18:52:25 -07:00
|
|
|
* Legal characters for the unique ID. Should be all on a US keyboard.
|
|
|
|
* No characters that conflict with XML or JSON. Requests to remove additional
|
|
|
|
* 'problematic' characters from this soup will be denied. That's your failure
|
|
|
|
* to properly escape in your own environment. Issues #251, #625, #682.
|
2015-11-24 19:16:01 -08:00
|
|
|
* @private
|
|
|
|
*/
|
2016-10-06 18:52:25 -07:00
|
|
|
Blockly.genUid.soup_ = '!#$%()*+,-./:;=?@[]^_`{|}~' +
|
2015-11-24 19:16:01 -08:00
|
|
|
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
2016-04-15 16:44:30 -04:00
|
|
|
|
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
|
|
|
/**
|
|
|
|
* Wrap text to the specified width.
|
|
|
|
* @param {string} text Text to wrap.
|
|
|
|
* @param {number} limit Width to wrap each line.
|
|
|
|
* @return {string} Wrapped text.
|
|
|
|
*/
|
|
|
|
Blockly.utils.wrap = function(text, limit) {
|
|
|
|
var lines = text.split('\n');
|
|
|
|
for (var i = 0; i < lines.length; i++) {
|
|
|
|
lines[i] = Blockly.utils.wrap_line_(lines[i], limit);
|
|
|
|
}
|
|
|
|
return lines.join('\n');
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wrap single line of text to the specified width.
|
|
|
|
* @param {string} text Text to wrap.
|
|
|
|
* @param {number} limit Width to wrap each line.
|
|
|
|
* @return {string} Wrapped text.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.utils.wrap_line_ = function(text, limit) {
|
|
|
|
if (text.length <= limit) {
|
|
|
|
// Short text, no need to wrap.
|
|
|
|
return text;
|
|
|
|
}
|
|
|
|
// Split the text into words.
|
|
|
|
var words = text.trim().split(/\s+/);
|
|
|
|
// Set limit to be the length of the largest word.
|
|
|
|
for (var i = 0; i < words.length; i++) {
|
|
|
|
if (words[i].length > limit) {
|
|
|
|
limit = words[i].length;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var lastScore;
|
|
|
|
var score = -Infinity;
|
|
|
|
var lastText;
|
|
|
|
var lineCount = 1;
|
|
|
|
do {
|
|
|
|
lastScore = score;
|
|
|
|
lastText = text;
|
|
|
|
// Create a list of booleans representing if a space (false) or
|
|
|
|
// a break (true) appears after each word.
|
|
|
|
var wordBreaks = [];
|
|
|
|
// Seed the list with evenly spaced linebreaks.
|
|
|
|
var steps = words.length / lineCount;
|
|
|
|
var insertedBreaks = 1;
|
|
|
|
for (var i = 0; i < words.length - 1; i++) {
|
|
|
|
if (insertedBreaks < (i + 1.5) / steps) {
|
|
|
|
insertedBreaks++;
|
|
|
|
wordBreaks[i] = true;
|
|
|
|
} else {
|
|
|
|
wordBreaks[i] = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wordBreaks = Blockly.utils.wrapMutate_(words, wordBreaks, limit);
|
|
|
|
score = Blockly.utils.wrapScore_(words, wordBreaks, limit);
|
|
|
|
text = Blockly.utils.wrapToText_(words, wordBreaks);
|
|
|
|
lineCount++;
|
|
|
|
} while (score > lastScore);
|
|
|
|
return lastText;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Compute a score for how good the wrapping is.
|
|
|
|
* @param {!Array.<string>} words Array of each word.
|
|
|
|
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
|
|
|
|
* @param {number} limit Width to wrap each line.
|
|
|
|
* @return {number} Larger the better.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.utils.wrapScore_ = function(words, wordBreaks, limit) {
|
|
|
|
// If this function becomes a performance liability, add caching.
|
|
|
|
// Compute the length of each line.
|
|
|
|
var lineLengths = [0];
|
|
|
|
var linePunctuation = [];
|
|
|
|
for (var i = 0; i < words.length; i++) {
|
|
|
|
lineLengths[lineLengths.length - 1] += words[i].length;
|
|
|
|
if (wordBreaks[i] === true) {
|
|
|
|
lineLengths.push(0);
|
|
|
|
linePunctuation.push(words[i].charAt(words[i].length - 1));
|
|
|
|
} else if (wordBreaks[i] === false) {
|
|
|
|
lineLengths[lineLengths.length - 1]++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var maxLength = Math.max.apply(Math, lineLengths);
|
|
|
|
|
|
|
|
var score = 0;
|
|
|
|
for (var i = 0; i < lineLengths.length; i++) {
|
|
|
|
// Optimize for width.
|
|
|
|
// -2 points per char over limit (scaled to the power of 1.5).
|
|
|
|
score -= Math.pow(Math.abs(limit - lineLengths[i]), 1.5) * 2;
|
|
|
|
// Optimize for even lines.
|
|
|
|
// -1 point per char smaller than max (scaled to the power of 1.5).
|
|
|
|
score -= Math.pow(maxLength - lineLengths[i], 1.5);
|
|
|
|
// Optimize for structure.
|
|
|
|
// Add score to line endings after punctuation.
|
|
|
|
if ('.?!'.indexOf(linePunctuation[i]) != -1) {
|
|
|
|
score += limit / 3;
|
|
|
|
} else if (',;)]}'.indexOf(linePunctuation[i]) != -1) {
|
|
|
|
score += limit / 4;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// All else being equal, the last line should not be longer than the
|
|
|
|
// previous line. For example, this looks wrong:
|
|
|
|
// aaa bbb
|
|
|
|
// ccc ddd eee
|
|
|
|
if (lineLengths.length > 1 && lineLengths[lineLengths.length - 1] <=
|
|
|
|
lineLengths[lineLengths.length - 2]) {
|
|
|
|
score += 0.5;
|
|
|
|
}
|
|
|
|
return score;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Mutate the array of line break locations until an optimal solution is found.
|
|
|
|
* No line breaks are added or deleted, they are simply moved around.
|
|
|
|
* @param {!Array.<string>} words Array of each word.
|
|
|
|
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
|
|
|
|
* @param {number} limit Width to wrap each line.
|
|
|
|
* @return {!Array.<boolean>} New array of optimal line breaks.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.utils.wrapMutate_ = function(words, wordBreaks, limit) {
|
|
|
|
var bestScore = Blockly.utils.wrapScore_(words, wordBreaks, limit);
|
|
|
|
var bestBreaks;
|
|
|
|
// Try shifting every line break forward or backward.
|
|
|
|
for (var i = 0; i < wordBreaks.length - 1; i++) {
|
|
|
|
if (wordBreaks[i] == wordBreaks[i + 1]) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
var mutatedWordBreaks = [].concat(wordBreaks);
|
|
|
|
mutatedWordBreaks[i] = !mutatedWordBreaks[i];
|
|
|
|
mutatedWordBreaks[i + 1] = !mutatedWordBreaks[i + 1];
|
|
|
|
var mutatedScore =
|
|
|
|
Blockly.utils.wrapScore_(words, mutatedWordBreaks, limit);
|
|
|
|
if (mutatedScore > bestScore) {
|
|
|
|
bestScore = mutatedScore;
|
|
|
|
bestBreaks = mutatedWordBreaks;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (bestBreaks) {
|
|
|
|
// Found an improvement. See if it may be improved further.
|
|
|
|
return Blockly.utils.wrapMutate_(words, bestBreaks, limit);
|
|
|
|
}
|
|
|
|
// No improvements found. Done.
|
|
|
|
return wordBreaks;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reassemble the array of words into text, with the specified line breaks.
|
|
|
|
* @param {!Array.<string>} words Array of each word.
|
|
|
|
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
|
|
|
|
* @return {string} Plain text.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
Blockly.utils.wrapToText_ = function(words, wordBreaks) {
|
|
|
|
var text = [];
|
|
|
|
for (var i = 0; i < words.length; i++) {
|
|
|
|
text.push(words[i]);
|
|
|
|
if (wordBreaks[i] !== undefined) {
|
|
|
|
text.push(wordBreaks[i] ? '\n' : ' ');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return text.join('');
|
|
|
|
};
|
|
|
|
|
2016-04-15 16:44:30 -04:00
|
|
|
/**
|
|
|
|
* Measure some text using a canvas in-memory.
|
|
|
|
* @param {string} fontSize E.g., '10pt'
|
|
|
|
* @param {string} fontFamily E.g., 'Arial'
|
2016-04-26 21:32:29 -04:00
|
|
|
* @param {string} fontWeight E.g., '600'
|
2016-04-15 16:44:30 -04:00
|
|
|
* @param {string} text The actual text to measure
|
|
|
|
* @return {number} Width of the text in px.
|
|
|
|
*/
|
2016-04-26 21:32:29 -04:00
|
|
|
Blockly.measureText = function(fontSize, fontFamily, fontWeight, text) {
|
2016-04-15 16:44:30 -04:00
|
|
|
var canvas = document.createElement('canvas');
|
|
|
|
var context = canvas.getContext('2d');
|
2016-04-26 21:32:29 -04:00
|
|
|
context.font = fontWeight + ' ' + fontSize + ' ' + fontFamily;
|
2016-04-15 16:44:30 -04:00
|
|
|
return context.measureText(text).width;
|
|
|
|
};
|
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
|
|
|
|
2016-07-07 18:35:41 -04:00
|
|
|
/**
|
|
|
|
* Encode a string's HTML entities.
|
|
|
|
* E.g., <a> -> <a>
|
2016-10-21 17:38:57 -07:00
|
|
|
* @param {string} rawStr Unencoded raw string to encode.
|
2016-07-07 18:35:41 -04:00
|
|
|
* @return {string} String with HTML entities encoded.
|
|
|
|
*/
|
|
|
|
Blockly.encodeEntities = function(rawStr) {
|
|
|
|
// CC-BY-SA https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
|
|
|
|
return rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
|
|
|
|
return '&#' + i.charCodeAt(0) + ';';
|
|
|
|
});
|
|
|
|
};
|