mirror of
https://github.com/scratchfoundation/scratch-blocks.git
synced 2025-06-26 20:20:23 -04:00
* JSON definitions for colour blocks (#838)
Replaces old colour block definitions with a Blockly.defineBlocksWithJsonArray(..) call. Generator unit tests continue to load and pass, signifying compatibility with prior block definitions.
Replaces extension 'math_number_tooltip' with the reusable 'parent_tooltip_when_inline' extension, also used by colour_picker. Includes tests.
* Rewrite tree.service.js.
- Remove unnecessary code and functions.
- Add documentation where needed.
- Fix a bug arising when a block on the workspace is attached to an existing link.
* Use setValue in fieldTextInput so that procedure renaming works
* Further cleanup and removal of unnecessary functions. Pull some strings out for i18n.
* Use bindEvent_ instead of bindEventWithChecks_ for longStop
* Clean up workspace.component.js. When moving a block from one place to another, move all blocks after it too, and adjust the active descs accordingly.
* Unit tests for JSON block definitions (just the start) (#850)
* Beginnings of a JSON block definition unit test set.
* Dispose of unit test workspaces and blocks in finally blocks.
* Clarify JSON error message by echoing arg notation.
* New blocks text_count, text_replace, and text_reverse (#830)
Includes generators for all languages and units tests on those generators.
* Fixing combo boxes getting out-of-sync with NVDA.
Combo boxes need to be special cased like text input. Also, Escape is
a reserved button in NVDA, so I added Enter as a way to "submit and
move up a level" in addition to escape, so these boxes can be edited
while NVDA is on.
* Temporary fix for broken text field validation.
* rebuild
* Add a block to reverse a list (#844)
* Localisation updates from https://translatewiki.net.
* Porting math.js blocks to JSON (#846)
Moving all `math.js` definitions into a single JSON array, complete with i18n syntax for all messages, dropdowns, and tooltips.
Adding Blockly.Extensions.buildTooltipForDropdown(..) to facilitate the creation and error-checking of tooltips that update based on the value of a dropdown.
Now warn on raw string in JSON 'extensions'.
* Fixing JSON support for images in dropdowns. Adding tests. (#851)
Fixes #848.
* Update README.md
Add a link to our forum.
* Correcting math_change color
* Enable custom flyout categories.
* Add some safety
* Update the set of reserved words in Python to reflect the current state of Python (2.7 and 3.6). (#861)
* Localisation updates from https://translatewiki.net.
* .getOptions_() to .getOptions() (#869)
Fixes #867.
* Blockly.Extensions.buildTooltipForDropdown(..): Deferred validation. (#870)
Defer tooltip message string check until after load, when all Blockly.Msg should be loaded.
Avoids validation in headless mode, due to lack of document.readyState.
* annotation updates
* annotation updates
* jsdoc corrections (#874)
* Remove use of Array.prototype.includes which is not implemented in IE or Edge < 14. Fixes google/blockly#876.
* Attempt to work around the IE/Edge bug where `getComputedTextLength()` throws an exception when the SVG node is not visible. This workaround forces a re-render, which in turn, forces a re-calculation of the node width once a block is inserted into the workspace SVG. This workaround is only executed on IE and Edge. See https://groups.google.com/forum/#!topic/blockly/T8IR4t4xAIY for the initial discussion of this issue.
* Change CSS transforms to work with older browsers (#879)
* Change the setting of the CSS transform properties on SVG nodes to set both the unprefixed version and the `-webkit-` prefixed version so that Blockly correctly renders in order browsers, such as Safari < 9 and iOS Safari < 9.2. For discussion of this issue, see https://groups.google.com/forum/#!topic/blockly/o3pERaRQhSg
* Correct the separation between the CSS transform property and the rest of the CSS that was in the variable misleadingly called "transform".
* Don't try to get block position in a headless workspace
* Stop bumping neighbours in headless blockly
* Place context menu correctly on touch
* Clear all active desc ids when the 'Erase Workspace' button is pressed.
* Fix a bug where splicing a block between two linked blocks disconnects the group and messes up the focus.
* Deleting a top-level block does not cause blocks after it to be deleted. Properly handle the active desc for this case.
* Localisation updates from https://translatewiki.net.
* Use the empty field placeholder for dropdowns that do not have a value selected.
* Bugfix for #892. I incorrectly converted one CSS transform setting to use the cross-browser setting function in 40a063763c74b3f712c3057565966c25d5cfdb10. (#895)
* Adding @namespace annotations for JSDoc. (#900)
* Fix typo causing TypeError (#901)
* Pinning the angular2 dependency, and including licenses. (#893)
* Add skeleton for tests on rendered workspaces
* Fix some lint errors
* Localisation updates from https://translatewiki.net.
* Correct changedState in setWarningText() (#908)
When clearing warnings on blocks with IDs, the changedState variable should be true if the text changed. This will trigger the block being reshaped and remove the space for the notification icon (this.bumpNeighbours_).
* Adds Block.prototype.mixin() and Blockly.Extensions.registerMixin(). (#907)
Adds Block.prototype.mixin() and Blockly.Extensions.registerMixin().
This adds support for a common use pattern in extensions, and adds
error checking to avoid future incompatibilities.
* Porting Logic blocks to JSON (#913)
Extensions, mixins, mutators and constants now grouped under the new namespace Blockly.Constants.Logic.
* Improving errors/warnings with Block.toDevString() and Connection.toString(). (#911)
* Add isEditable to field, and add tests
* Separate tests
* Blockly.Constants.Math and Blockly.Constants.Colour extension constants (#916)
Also, correcting quotes in logic.js.
* Correction to logic_ternary type check (#920)
* Porting Loop blocks to JSON (#919)
* Improved documentation on `Blockly.Extensions.buildTooltipForDropdown`
* Replaced incorrect uses of `@mixes` JSDoc annotation (on mixin extensions) with `@augments Blockly.Block`.
* Added Blockly.Extensions.buildTooltipWithFieldValue() extension helper.
* Workspace isDraggable
* JSONify simple list blocks
* JSONify variable blocks
* Initial text block, with a mixin to generate quote image fields. (#923)
Text block now uses the extension "text_quotes", supported by Blockly.Constants.Text.QUOTE_IMAGE_MIXIN.quoteField_(fieldName), so that each platform can use the best platform appropriate image (size, density, etc.) for the quotes.
* Add no-op stub .neighbors() for headless Connection.
* Adding tests for logic_ternary block in a new jsunit test framework.
* Correcting output of the logic_null block.
* Potential bug fix for issue #661
* extension controls_if => controls_if_mutator.
* Renamed extension function constant, and moved variables into the mixin.
* Dereference string table references when loading variable fields from JSON.
* Moving FieldImage string dereferencing back into Block.interpolate_() (part of jsonInit()). This sets a clear boundary of where dereferencing should happen.
Towards this, I've added message dereferencing for other field types here, as well. I've used a pattern of field-type specific helper functions.
* Addressing comments.
* .utils.replaceMessageReferences(..) now gracefully returns non-string arguments.
* Clarification update.
Unraveling nested ternaries in Blockly.utils.tokenizeInterpolation_()
* Code correction from previous commit. Moved style to css.js and set ROUNDING=15;
* Fixing Enter so it properly propogates to dropdown selection. (#934)
Fixing FieldSegment so it updates dropdowns when the underlying dropdown changes.
* Localisation updates from https://translatewiki.net.
* Make variable add set/get block in context menu obey block limits
* Localisation updates from https://translatewiki.net.
* Use mutator extension for controls_if block
* Fix #946. Don't check for presence of constants.js
* Fix #945 (annotations) and an eslint issue (constant condition)
* Localisation updates from https://translatewiki.net.
* Fix #950: BlockFactory typo and copypasta
* Add safety checks for mutators and non-mutator extensions
* Handle mutations with both mixins and functions
* Adding warning on duplicate JSON block definition.
* period
* Make some functions private and add tests
* Localisation updates from https://translatewiki.net.
* Update help URL per #937.
Replace URL usages of %28 and %29 with normal parenthesis characters. (They aren't replaced by JavaScript's encodeURIComponent() function, and seem to work just fine without them.)
Added missing semicolon in build.py.
* Typo in comment.
* Make it easier to read the code that creates the variable category in the tolbox
* Adding Blockly.Xml.appendDomToWorkspace() (#962)
This is a copy (with additional comments) of PR #822 (and also #961) by @qnoirhomme with unrelated files removed. See #822 for full review.
* Annotation fixes
* Fix bug #904 by explicitly grabbing focus on the workspace svg element. (#964)
* Potential fix for #888. Stops checking whether we are mid workspace drag since we do not always get mosue up events when blockly is in an iframe. (#899)
* Adding new minimap demo
* Basic code style changes. Adding a few more comments. Return early if disableScrollChange in onScrollChange listener.
* `unction` to `function` corrects #962 (#970)
* Cross browser friendly fix for #904. This calls blur and focus from … (#972)
* Cross browser friendly fix for #904. This calls blur and focus from workspace.markFocused and removes the event listener on focus events. markFocused is called from all of our mouse down handlers, which triggers the focus event leading to an infinite loop of focus. As far as I can tell, there are no uses of the focus handler that actually did anything for us.
* Localisation updates from https://translatewiki.net.
* Another attempt to fix #904 to keep the page from jumping to the focused workspace in IE 11 (#974)
* Adding horizontal scrolling. Changed scroll change callbacks from onScroll_ to setHandlePosition. onScroll_ is not challed when workspace is dragged.
* set background color to lilac if opening the playground from file:
* Registering mousemove and mouseup listener in mousedown event. Mousemove and Mouseup events are now listening over document.
* Localisation updates from https://translatewiki.net.
* Fix #967 by overriding the updateWidth method in FieldImage blocks to be a no-op. FieldImage fields should not change size after the width is set in init. The updateWidth and, therefore, getCachedWidth is now being called by BlockSvg renderFields_ (see commit d55d9cbd9f
). IIUC, updateWidth/getCachedWidth was only called from render before which is overridden in FieldImage to be a no-op already. (#979)
* Fix #969
* Localisation updates from https://translatewiki.net.
* Fix #986. Looks like the original PR just forgot this block. (#992)
* rebuild develop (#996)
* Added the variable modal and component and implemented basic renaming functionality. (#991)
* Fixing commenting from the last commit. (#1000)
* Localisation updates from https://translatewiki.net.
* RemoveAttribute doesn't work on SVG elements in IE 10. Use setAttribute to null instead.
* Adding the remove variable modal and functionality to accessible Blockly. (#1011)
* Minimap position bug fix for browsers other than chrome. Added touch support.
* Adding an add variable modal to accessible Blockly. (#1015)
* Adding the remove variable modal and functionality to accessible Blockly.
* Adding the add variable modal for accessible Blockly.
* Block browser context menu in the toolbox and flyout
* Add links to the dev registration form and contributor guidelines
* Miscellaneous comment cleanup
* Adding the common modal class. (#1017)
Centralizes accessible modal behavior.
* - Changed error message referencing 'procedure' instead of 'function' (#1019)
- Added iOS specific UI messages
- Fixed bug with js_to_json.py script where it didn't recognize ' character
* - Allows use of Blockly's messaging format for category name, colour,… (#1028)
...in toolbox XML.
- Updated code editor demo to use this message format
- Re-built blockly_compressed.js
* Making text_count use a text color (like text_length, which also returns a number). (#1027)
* Enable google/blockly with continuous build on travis ci (#1023) (#1035)
* create .travis for ci job
* initial checkin for blocky-web travis ci job
* rename file to .travis.yaml for typo
* remove after_script
* added cache
* rename .travis.yaml to .travis.yml
* Update .travis.yml
* include build script
* fix yaml file format issue
* debug install part
* debug build issue
* Update .travis.yml
* remove cache for now
* Update .travis.yml
* Update .travis.yml
* Update .travis.yml
* more debug info
* Update .travis.yml
* Update .travis.yml
* fix typo
* installing chrome browser
* remove chrome setting config
* run build.py as part of npm install
* Update .travis.yml
* update karma dependency
* use karma as test runner
* fix typo
* remove karma test for now
* Update .travis.yml
* Update package.json
* add npm test target
* add browserstack-runner depdendency
* update browser support
* fix typo for test target
* fix chrome typo
* added closure dependency
* add google-closure-library
* include blockly_uncompressed.js and core.js dependency
* uncomment out core/*.js files
* add kama job as part of install
* remove browserstack add on for now
* fix karma config typo
* add karma-closure
* add os support
* remove typo config
* include more closure files
* change os back to linux
* use closure-library from node_modules
* change log level back to INFO
* change npm test target to use open browser command instead of karma
* change travis test target to use open command instead of karma
* list current directory
* find what's in current dir
* typo command
* Update .travis.yml
* typo again
* open right index.html
* use right path for index.html
* xdg-open to open default browser on travis
* exit browser after 5s wait
* change timeout to 1 min
* exit after opening up browser
* use browser only
* use karma
* remove un-needed dependency
* clean up script section
* fix typo
* update build status on readme
* initial commit for selenium integration tests
* update selenium jar path
* fix test_runner.js typo
* add more debug info
* check java version
* add && instead of 9288
* fix java path
* add logic to check if selenium is running or not
* add some deugging info
* initial commit to get chromedriver
* add chromedriver flag
* add get_chromedriver.sh to package.json and .travel
* change browser to chrome for now
* fix path issue
* update chromdriver path
* fix path issue again
* more debugging
* add debug msg
* fix typo
* minor fix for getting chromedriver
* install latest chrome browser
* clean up pakcage.json
* use npm target for test run
* remove removing trailing comma
* fix another trailing comma
* updated travis test target
* clean up scripts
* not sure nmp run preinstall
* redirect selenium log to tmp file
* revert writing console log to file
* update test summary
* more clean up
* minor clean up before pull request
* resolved closure-library conflict
1. add closure-library to dependencies instead of devDependencies.
2. add lint back in scripts block
* fix typo (adding comma) in script section
* Renames Blockly.workspaceDragSurface to Blockly.WorkspaceDragSurface.
Fixes #880.
* Ensure useDragSurface is a boolean.
Fixed #988
* use pretest instead of preinstall in package.json (#1043)
* cherry pick for pretest fix
* put pretest target to test_setup.sh
* fix conflict
* cherry pick for get_chromedriver.sh
* add some sleep to wait download to finish
* use node.js stable
* use npm test target
* field_angle renders degree symbol consistently.
Fixes #973
* bumpNeighbours_ function moved to block_svg.
Fixed #1009
* Update RegEx in js-to-json to match windowi eol (#1050)
The current regex only works with the "\n" line endings as it expects no characters after the optional ";" at the end of the line. In windows, if it adds the "\r" it counts as a characters and is not part of the line terminator so it doesn't match.
* Fix French translation of "colour with rgb" block (#1053)
"colorier", which is currently used, is a verb and proposed "couleur" is
a noun: the block in question does not change colour of anything, it
creates new colour instead, thus noun is more applicable.
Also, noun is used in French translation of "random colour" block:
"couleur aléatoire".
* Enforcing non-empty names on value inputs and statement inputs. (#1054)
* Correcting #1054 (#1056)
single quotes. better logic.
* Created a variable model with name, id, and type.
Created a jsunit test file for variable model.
* Change how blockly handles cursors. The old way was quite slow becau… (#1057)
* Change how blockly handles cursors. The old way was quite slow because it changed the stylesheet directly. See issue #981 for more details on implementation and tradeoffs. This changes makes the following high level changes: deprecate Blockly.Css.setCursor, use built in open and closed hand cursor instead of custom .cur files, add css to draggable objects to set the open and closed hand cursors.
* Rebuild blockly_uncompressed to pick up a testing change to make travis happy. Fix a build warning from a multi-line string in the process. (#1059)
* Merge master into develop (#1063)
- pick up translation changes
- clean up trailing spaces
* use goog.string.startswith instead of string.startswith (#1065)
* New jsinterpreter demo includes wait block. Both demos have improved UI for clarity. (#1001)
Refactor of interpreter demo
* Renamed demos/interpreter/index.html as demos/interpreter/step-execution.html (including redirect), and added demos/interpreter/async-execution.html.
* Refactored code to automatically generate/parse the blocks, eliminating the need for a "Parse JavaScript" button. Code is still shown in alert upon stepping to the first statement. Print statements now write to output <textarea> instead of modal dialogs.
* VariableMap and functions added.
* Create separate file for VariableMap and its functions.
* Fix #1069 (#1073)
* VariableMap and functions added.
* Fix #1051 (#1084)
* Improve errors when validating JSON block definitions. (#1086)
goog.asserts to not run from blockly_compressed.js. User data validation should always run.
* Dragging changes, rebased on develop (#1078)
* Add block drag surface translateSurfaceBy
* Add dragged connection manager
* Add gesture.js
* Add GestureHandler
* Implemented gesture skeleton
* Most basic workspace dragging
* Add dragged connection manager
* cleanup
* doc
* more cleanup
* Add gesture handler
* Add translateSurfaceInternal
* core/block_dragger.js
* cleanup
* Pull in changes to dragged connection manager
* Pull in changes to dragged connection manager
* comments
* more annotations
* Add workspace dragger
* Add coordinate annotations
* Start on block dragging
* Limit number of concurrent gestures
* Add some TODOs
* start using dragged connection manager
* Set origin correctly for dragging blocks
* Connect or delete at the end of a block drag.
* cleanup
* handle field clicks and block + workspace right-clicks
* move code into BlockDragger class, but still reach into Gesture internals a lot
* Clean up block dragger
* Call blockDragger constructor with correct arguments
* Enable block dragging in a mutator workspace
* Add workspace dragger
* click todos
* Drag flyout with background
* more dragging from flyout
* nit
* fix dragging from flyouts
* Remove unused code and rename gestureHandler to gestureDB
* Rename gesture handler
* Added some jsdoc in gesture.js
* Update some docs
* Move some code to block_svg and clean up code
* Lots of coordinate annotations
* Fix block dragging when zoomed.
* Remove built files from branch
* More dragging work (#1026)
-- Drag bubbles while dragging blocks
-- Use bindEventWithChecks to work in touch on Android. Not tested anywhere else yet.
-- Handle dragging blocks while zoomed
-- Handle dragging blocks in mutators
-- Handle right-clicks (I hope)
-- Removed lots of unused code
* More dragging work (#1048)
- Removed gestureDB
- Removing uses of terminateDrag
- Cleaned up disposal code
* Dragging bugfixes (#1058)
- Get rid of flyout.dragMode_ and blockly.dragMode_
- Make drags from the flyout start from the top block in the group
- Block tooltips from being scheduled or shown during gestures
- Don't resize mutator bubbles mid-drag
* Fix events in new dragging (#1060)
* rebuild for testing
* unbuild
* Fix events
* rebuild
* Fix up cursors
* Use language files from develop
* Remove handled TODOS
* attempt to fix IE rerendering bug, and recalculate workspace positions on scroll
* Rebuild all the things
* Comment cleanup; annotations; delete unused variables.
* Tidy up context menu code. (#1081)
* add osx travis test run job (#1074)
* Names are correctly fetched from VariableModels!
* add more wait time for test setup (#1091)
* Work around timing issue with travis osx issue (#1092)
* add more wait time for test setup
* increase selenium wait time
* add more wait
* Fix #1077 by adding a rule to cover the toolbox labels too. (#1099)
* Assign variable UUID to field_variable dropdown.
* Change registration link to a static one (#1106)
This lets us redirect to a different form if we change it in the future.
* Edit generators to read in Variable Models.
* Add VariableMap requirement to workspace.
* Changed parameter name in workspace for clarity.
* Add type, id, and info to the generated xml.
Add xml tests for fieldToDom.
Update workspace tests to pass with new changes.
* Fix apostrophe in tooltips and helpurls (#1111)
* Click events on shadow blocks have the correct id (#1089)
* Add image_onclick option (#1080)
* Cleanup: semicolons, spacing, etc. (#1116)
* Spelling. Spelling is hard.
* Add variable info to xml generated in variables.js
* Add missing CLAs info to the contributing file (#1119)
* Add missing CLAs info to the contributing file
* Added larger changes paragraph
* Replacing latest prettifier hosted in repo with latest version at rawgit CDN. (#1120)
* Forgot update code demo (#1121)
* Move audio code to a new file (#1122)
* move audio code to a new file
* dispose
* null check
* Make flyout get variables from target workspace's variableMap.
* Require VariableModel in field_variable.js.
* Update contributing.md (#1126)
* Include variables at top of serialization.
* Move blockSvg.getHeightWidth to block_render_svg.js (#1118)
* Deserialization variables at top.
* Create grid object (#1131)
* Create grid object
* Doc
* Units! Thanks @RoboErikG
* Add our sound files in other formats
* Remove duplicate merged code
* Remove translation files
* Cleanup duplicate functions
* Add back scrollbar code
* Fix variable related issues
* Revert workspace variable creation change
* Delete language files
* Appease linter
* Remove duplication
* Add spaces to jsdoc line
933 lines
30 KiB
JavaScript
933 lines
30 KiB
JavaScript
/**
|
|
* @license
|
|
* Visual Blocks Editor
|
|
*
|
|
* Copyright 2012 Google Inc.
|
|
* https://developers.google.com/blockly/
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Utility methods.
|
|
* These methods are not specific to Blockly, and could be factored out into
|
|
* a JavaScript framework such as Closure.
|
|
* @author fraser@google.com (Neil Fraser)
|
|
*/
|
|
'use strict';
|
|
|
|
/**
|
|
* @name Blockly.utils
|
|
* @namespace
|
|
**/
|
|
goog.provide('Blockly.utils');
|
|
|
|
goog.require('Blockly.Touch');
|
|
goog.require('goog.dom');
|
|
goog.require('goog.events.BrowserFeature');
|
|
goog.require('goog.math.Coordinate');
|
|
goog.require('goog.userAgent');
|
|
|
|
/**
|
|
* Remove an attribute from a element even if it's in IE 10.
|
|
* Similar to Element.removeAttribute() but it works on SVG elements in IE 10.
|
|
* Sets the attribute to null in IE 10, which treats removeAttribute as a no-op
|
|
* if it's called on an SVG element.
|
|
* @param {!Element} element DOM element to remove attribute from.
|
|
* @param {string} attributeName Name of attribute to remove.
|
|
*/
|
|
Blockly.utils.removeAttribute = function(element, attributeName) {
|
|
// goog.userAgent.isVersion is deprecated, but the replacement is
|
|
// goog.userAgent.isVersionOrHigher.
|
|
if (goog.userAgent.IE && goog.userAgent.isVersion('10.0')) {
|
|
element.setAttribute(attributeName, null);
|
|
} else {
|
|
element.removeAttribute(attributeName);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
* @return {boolean} True if class was added, false if already present.
|
|
*/
|
|
Blockly.utils.addClass = function(element, className) {
|
|
var classes = element.getAttribute('class') || '';
|
|
if ((' ' + classes + ' ').indexOf(' ' + className + ' ') != -1) {
|
|
return false;
|
|
}
|
|
if (classes) {
|
|
classes += ' ';
|
|
}
|
|
element.setAttribute('class', classes + className);
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
* @return {boolean} True if class was removed, false if never present.
|
|
*/
|
|
Blockly.utils.removeClass = function(element, className) {
|
|
var classes = element.getAttribute('class');
|
|
if ((' ' + classes + ' ').indexOf(' ' + className + ' ') == -1) {
|
|
return false;
|
|
}
|
|
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 {
|
|
Blockly.utils.removeAttribute(element, 'class');
|
|
}
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* 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.utils.hasClass = function(element, className) {
|
|
var classes = element.getAttribute('class');
|
|
return (' ' + classes + ' ').indexOf(' ' + className + ' ') != -1;
|
|
};
|
|
|
|
/**
|
|
* Don't do anything for this event, just halt propagation.
|
|
* @param {!Event} e An event.
|
|
*/
|
|
Blockly.utils.noEvent = function(e) {
|
|
// This event has been handled. No need to bubble up to the document.
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
};
|
|
|
|
/**
|
|
* Is this event targeting a text input widget?
|
|
* @param {!Event} e An event.
|
|
* @return {boolean} True if text input.
|
|
*/
|
|
Blockly.utils.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' ||
|
|
e.target.type == 'tel' || e.target.type == 'url' ||
|
|
e.target.isContentEditable;
|
|
};
|
|
|
|
/**
|
|
* Return the coordinates of the top-left corner of this element relative to
|
|
* its parent. Only for SVG elements and children (e.g. rect, g, path).
|
|
* @param {!Element} element SVG element to find the coordinates of.
|
|
* @return {!goog.math.Coordinate} Object with .x and .y properties.
|
|
*/
|
|
Blockly.utils.getRelativeXY = function(element) {
|
|
var xy = new goog.math.Coordinate(0, 0);
|
|
// 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');
|
|
var r = transform && transform.match(Blockly.utils.getRelativeXY.XY_REGEX_);
|
|
if (r) {
|
|
xy.x += parseFloat(r[1]);
|
|
if (r[3]) {
|
|
xy.y += parseFloat(r[3]);
|
|
}
|
|
}
|
|
|
|
// Then check for style = transform: translate(...) or translate3d(...)
|
|
var style = element.getAttribute('style');
|
|
if (style && style.indexOf('translate') > -1) {
|
|
var styleComponents = style.match(Blockly.utils.getRelativeXY.XY_2D_REGEX_);
|
|
// Try transform3d if 2d transform wasn't there.
|
|
if (!styleComponents) {
|
|
styleComponents = style.match(Blockly.utils.getRelativeXY.XY_3D_REGEX_);
|
|
}
|
|
if (styleComponents) {
|
|
xy.x += parseFloat(styleComponents[1]);
|
|
if (styleComponents[3]) {
|
|
xy.y += parseFloat(styleComponents[3]);
|
|
}
|
|
}
|
|
}
|
|
return xy;
|
|
};
|
|
|
|
/**
|
|
* Return the coordinates of the top-left corner of this element relative to
|
|
* the div blockly was injected into.
|
|
* @param {!Element} element SVG element to find the coordinates of. If this is
|
|
* not a child of the div blockly was injected into, the behaviour is
|
|
* undefined.
|
|
* @return {!goog.math.Coordinate} Object with .x and .y properties.
|
|
*/
|
|
Blockly.utils.getInjectionDivXY_ = function(element) {
|
|
var x = 0;
|
|
var y = 0;
|
|
var scale = 1;
|
|
while (element) {
|
|
var xy = Blockly.utils.getRelativeXY(element);
|
|
var scale = Blockly.utils.getScale_(element);
|
|
x = (x * scale) + xy.x;
|
|
y = (y * scale) + xy.y;
|
|
var classes = element.getAttribute('class') || '';
|
|
if ((' ' + classes + ' ').indexOf(' injectionDiv ') != -1) {
|
|
break;
|
|
}
|
|
element = element.parentNode;
|
|
}
|
|
return new goog.math.Coordinate(x, y);
|
|
};
|
|
|
|
/**
|
|
* Return the scale of this element.
|
|
* @param {!Element} element The element to find the coordinates of.
|
|
* @return {!number} number represending the scale applied to the element.
|
|
* @private
|
|
*/
|
|
Blockly.utils.getScale_ = function(element) {
|
|
var scale = 1;
|
|
var transform = element.getAttribute('transform');
|
|
if (transform) {
|
|
var transformComponents =
|
|
transform.match(Blockly.utils.getScale_.REGEXP_);
|
|
if (transformComponents && transformComponents[0]) {
|
|
scale = parseFloat(transformComponents[0]);
|
|
}
|
|
}
|
|
return scale;
|
|
};
|
|
|
|
/**
|
|
* 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.utils.getRelativeXY.XY_REGEX_ =
|
|
/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*\))?/;
|
|
|
|
|
|
/**
|
|
* Static regex to pull the scale values out of a transform style property.
|
|
* Accounts for same exceptions as XY_REGEXP_.
|
|
* @type {!RegExp}
|
|
* @private
|
|
*/
|
|
Blockly.utils.getScale_REGEXP_ = /scale\(\s*([-+\d.e]+)\s*\)/;
|
|
|
|
/**
|
|
* 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.utils.getRelativeXY.XY_3D_REGEX_ =
|
|
/transform:\s*translate3d\(\s*([-+\d.e]+)px([ ,]\s*([-+\d.e]+)\s*)px([ ,]\s*([-+\d.e]+)\s*)px\)?/;
|
|
|
|
/**
|
|
* 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.utils.getRelativeXY.XY_2D_REGEX_ =
|
|
/transform:\s*translate\(\s*([-+\d.e]+)px([ ,]\s*([-+\d.e]+)\s*)px\)?/;
|
|
|
|
/**
|
|
* Helper method for creating SVG elements.
|
|
* @param {string} name Element's tag name.
|
|
* @param {!Object} attrs Dictionary of attribute names and values.
|
|
* @param {Element} parent Optional parent on which to append the element.
|
|
* @return {!SVGElement} Newly created SVG element.
|
|
*/
|
|
Blockly.utils.createSvgElement = function(name, attrs, parent /*, opt_workspace */) {
|
|
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;
|
|
}
|
|
if (parent) {
|
|
parent.appendChild(e);
|
|
}
|
|
return e;
|
|
};
|
|
|
|
/**
|
|
* Is this event a right-click?
|
|
* @param {!Event} e Mouse event.
|
|
* @return {boolean} True if right-click.
|
|
*/
|
|
Blockly.utils.isRightButton = function(e) {
|
|
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;
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
* @param {!Element} svg SVG element.
|
|
* @param {SVGMatrix} matrix Inverted screen CTM to use.
|
|
* @return {!Object} Object with .x and .y properties.
|
|
*/
|
|
Blockly.utils.mouseToSvg = function(e, svg, matrix) {
|
|
var svgPoint = svg.createSVGPoint();
|
|
svgPoint.x = e.clientX;
|
|
svgPoint.y = e.clientY;
|
|
|
|
if (!matrix) {
|
|
matrix = svg.getScreenCTM().inverse();
|
|
}
|
|
return svgPoint.matrixTransform(matrix);
|
|
};
|
|
|
|
/**
|
|
* Given an array of strings, return the length of the shortest one.
|
|
* @param {!Array.<string>} array Array of strings.
|
|
* @return {number} Length of shortest string.
|
|
*/
|
|
Blockly.utils.shortestStringLength = function(array) {
|
|
if (!array.length) {
|
|
return 0;
|
|
}
|
|
return array.reduce(function(a, b) {
|
|
return a.length < b.length ? a : b;
|
|
}).length;
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
* @param {!Array.<string>} array Array of strings.
|
|
* @param {number=} opt_shortest Length of shortest string.
|
|
* @return {number} Length of common prefix.
|
|
*/
|
|
Blockly.utils.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.utils.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.
|
|
* @param {!Array.<string>} array Array of strings.
|
|
* @param {number=} opt_shortest Length of shortest string.
|
|
* @return {number} Length of common suffix.
|
|
*/
|
|
Blockly.utils.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.utils.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;
|
|
};
|
|
|
|
/**
|
|
* Parse a string with any number of interpolation tokens (%1, %2, ...).
|
|
* It will also replace string table references (e.g., %{bky_my_msg} and
|
|
* %{BKY_MY_MSG} will both be replaced with the value in
|
|
* Blockly.Msg['MY_MSG']). Percentage sign characters '%' may be self-escaped
|
|
* (e.g., '%%').
|
|
* @param {string} message Text which might contain string table references and
|
|
* interpolation tokens.
|
|
* @return {!Array.<string|number>} Array of strings and numbers.
|
|
*/
|
|
Blockly.utils.tokenizeInterpolation = function(message) {
|
|
return Blockly.utils.tokenizeInterpolation_(message, true);
|
|
};
|
|
|
|
/**
|
|
* Replaces string table references in a message, if the message is a string.
|
|
* For example, "%{bky_my_msg}" and "%{BKY_MY_MSG}" will both be replaced with
|
|
* the value in Blockly.Msg['MY_MSG'].
|
|
* @param {string|?} message Message, which may be a string that contains
|
|
* string table references.
|
|
* @return {!string} String with message references replaced.
|
|
*/
|
|
Blockly.utils.replaceMessageReferences = function(message) {
|
|
if (!goog.isString(message)) {
|
|
return message;
|
|
}
|
|
var interpolatedResult = Blockly.utils.tokenizeInterpolation_(message, false);
|
|
// When parseInterpolationTokens == false, interpolatedResult should be at
|
|
// most length 1.
|
|
return interpolatedResult.length ? interpolatedResult[0] : "";
|
|
};
|
|
|
|
/**
|
|
* Validates that any %{BKY_...} references in the message refer to keys of
|
|
* the Blockly.Msg string table.
|
|
* @param {string} message Text which might contain string table references.
|
|
* @return {boolean} True if all message references have matching values.
|
|
* Otherwise, false.
|
|
*/
|
|
Blockly.utils.checkMessageReferences = function(message) {
|
|
var isValid = true; // True until a bad reference is found
|
|
|
|
var regex = /%{BKY_([a-zA-Z][a-zA-Z0-9_]*)}/g;
|
|
var match = regex.exec(message);
|
|
while (match != null) {
|
|
var msgKey = match[1];
|
|
if (Blockly.Msg[msgKey] == null) {
|
|
console.log('WARNING: No message string for %{BKY_' + msgKey + '}.');
|
|
isValid = false;
|
|
}
|
|
|
|
// Re-run on remainder of sting.
|
|
message = message.substring(match.index + msgKey.length + 1);
|
|
match = regex.exec(message);
|
|
}
|
|
|
|
return isValid;
|
|
};
|
|
|
|
/**
|
|
* Internal implemention of the message reference and interpolation token
|
|
* parsing used by tokenizeInterpolation() and replaceMessageReferences().
|
|
* @param {string} message Text which might contain string table references and
|
|
* interpolation tokens.
|
|
* @param {boolean} parseInterpolationTokens Option to parse numeric
|
|
* interpolation tokens (%1, %2, ...) when true.
|
|
* @return {!Array.<string|number>} Array of strings and numbers.
|
|
* @private
|
|
*/
|
|
Blockly.utils.tokenizeInterpolation_ = function(message, parseInterpolationTokens) {
|
|
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.
|
|
// 3 - Message ref 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 == '%') {
|
|
var text = buffer.join('');
|
|
if (text) {
|
|
tokens.push(text);
|
|
}
|
|
buffer.length = 0;
|
|
state = 1; // Start escape.
|
|
} else {
|
|
buffer.push(c); // Regular char.
|
|
}
|
|
} else if (state == 1) {
|
|
if (c == '%') {
|
|
buffer.push(c); // Escaped %: %%
|
|
state = 0;
|
|
} else if (parseInterpolationTokens && '0' <= c && c <= '9') {
|
|
state = 2;
|
|
number = c;
|
|
var text = buffer.join('');
|
|
if (text) {
|
|
tokens.push(text);
|
|
}
|
|
buffer.length = 0;
|
|
} else if (c == '{') {
|
|
state = 3;
|
|
} else {
|
|
buffer.push('%', c); // Not recognized. Return as literal.
|
|
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;
|
|
}
|
|
} else if (state == 3) { // String table reference
|
|
if (c == '') {
|
|
// Premature end before closing '}'
|
|
buffer.splice(0, 0, '%{'); // Re-insert leading delimiter
|
|
i--; // Parse this char again.
|
|
state = 0; // and parse as string literal.
|
|
} else if (c != '}') {
|
|
buffer.push(c);
|
|
} else {
|
|
var rawKey = buffer.join('');
|
|
if (/[a-zA-Z][a-zA-Z0-9_]*/.test(rawKey)) { // Strict matching
|
|
// Found a valid string key. Attempt case insensitive match.
|
|
var keyUpper = rawKey.toUpperCase();
|
|
|
|
// BKY_ is the prefix used to namespace the strings used in Blockly
|
|
// core files and the predefined blocks in ../blocks/. These strings
|
|
// are defined in ../msgs/ files.
|
|
var bklyKey = goog.string.startsWith(keyUpper, 'BKY_') ?
|
|
keyUpper.substring(4) : null;
|
|
if (bklyKey && bklyKey in Blockly.Msg) {
|
|
var rawValue = Blockly.Msg[bklyKey];
|
|
if (goog.isString(rawValue)) {
|
|
// Attempt to dereference substrings, too, appending to the end.
|
|
Array.prototype.push.apply(tokens,
|
|
Blockly.utils.tokenizeInterpolation(rawValue));
|
|
} else if (parseInterpolationTokens) {
|
|
// When parsing interpolation tokens, numbers are special
|
|
// placeholders (%1, %2, etc). Make sure all other values are
|
|
// strings.
|
|
tokens.push(String(rawValue));
|
|
} else {
|
|
tokens.push(rawValue);
|
|
}
|
|
} else {
|
|
// No entry found in the string table. Pass reference as string.
|
|
tokens.push('%{' + rawKey + '}');
|
|
}
|
|
buffer.length = 0; // Clear the array
|
|
state = 0;
|
|
} else {
|
|
tokens.push('%{' + rawKey + '}');
|
|
buffer.length = 0;
|
|
state = 0; // and parse as string literal.
|
|
}
|
|
}
|
|
}
|
|
}
|
|
var text = buffer.join('');
|
|
if (text) {
|
|
tokens.push(text);
|
|
}
|
|
|
|
// Merge adjacent text tokens into a single string.
|
|
var mergedTokens = [];
|
|
buffer.length = 0;
|
|
for (var i = 0; i < tokens.length; ++i) {
|
|
if (typeof tokens[i] == 'string') {
|
|
buffer.push(tokens[i]);
|
|
} else {
|
|
text = buffer.join('');
|
|
if (text) {
|
|
mergedTokens.push(text);
|
|
}
|
|
buffer.length = 0;
|
|
mergedTokens.push(tokens[i]);
|
|
}
|
|
}
|
|
text = buffer.join('');
|
|
if (text) {
|
|
mergedTokens.push(text);
|
|
}
|
|
buffer.length = 0;
|
|
|
|
return mergedTokens;
|
|
};
|
|
|
|
/**
|
|
* Generate a unique ID. This should be globally unique.
|
|
* 87 characters ^ 20 length > 128 bits (better than a UUID).
|
|
* @return {string} A globally unique ID string.
|
|
*/
|
|
Blockly.utils.genUid = function() {
|
|
var length = 20;
|
|
var soupLength = Blockly.utils.genUid.soup_.length;
|
|
var id = [];
|
|
for (var i = 0; i < length; i++) {
|
|
id[i] = Blockly.utils.genUid.soup_.charAt(Math.random() * soupLength);
|
|
}
|
|
return id.join('');
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
* @private
|
|
*/
|
|
Blockly.utils.genUid.soup_ = '!#$%()*+,-./:;=?@[]^_`{|}~' +
|
|
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
|
|
/**
|
|
* 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.wrapLine_(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.wrapLine_ = 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('');
|
|
};
|
|
|
|
/**
|
|
* Measure some text using a canvas in-memory.
|
|
* Does not exist in Blockly, but needed in scratch-blocks
|
|
* @param {string} fontSize E.g., '10pt'
|
|
* @param {string} fontFamily E.g., 'Arial'
|
|
* @param {string} fontWeight E.g., '600'
|
|
* @param {string} text The actual text to measure
|
|
* @return {number} Width of the text in px.
|
|
*/
|
|
Blockly.utils.measureText = function(fontSize, fontFamily, fontWeight, text) {
|
|
var canvas = document.createElement('canvas');
|
|
var context = canvas.getContext('2d');
|
|
context.font = fontWeight + ' ' + fontSize + ' ' + fontFamily;
|
|
return context.measureText(text).width;
|
|
};
|
|
|
|
/**
|
|
* Encode a string's HTML entities.
|
|
* E.g., <a> -> <a>
|
|
* Does not exist in Blockly, but needed in scratch-blocks
|
|
* @param {string} rawStr Unencoded raw string to encode.
|
|
* @return {string} String with HTML entities encoded.
|
|
*/
|
|
Blockly.utils.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) + ';';
|
|
});
|
|
};
|
|
|
|
/**
|
|
* 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.utils.is3dSupported = function() {
|
|
if (Blockly.utils.is3dSupported.cached_ !== undefined) {
|
|
return Blockly.utils.is3dSupported.cached_;
|
|
}
|
|
// CC-BY-SA Lorenzo Polidori
|
|
// stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
|
|
if (!goog.global.getComputedStyle) {
|
|
return false;
|
|
}
|
|
|
|
var el = document.createElement('p');
|
|
var has3d = 'none';
|
|
var transforms = {
|
|
'webkitTransform': '-webkit-transform',
|
|
'OTransform': '-o-transform',
|
|
'msTransform': '-ms-transform',
|
|
'MozTransform': '-moz-transform',
|
|
'transform': 'transform'
|
|
};
|
|
|
|
// 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) {
|
|
el.style[t] = 'translate3d(1px,1px,1px)';
|
|
var computedStyle = goog.global.getComputedStyle(el);
|
|
if (!computedStyle) {
|
|
// getComputedStyle in Firefox returns null when blockly is loaded
|
|
// inside an iframe with display: none. Returning false and not
|
|
// caching is3dSupported means we try again later. This is most likely
|
|
// when users are interacting with blocks which should mean blockly is
|
|
// visible again.
|
|
// See https://bugzilla.mozilla.org/show_bug.cgi?id=548397
|
|
document.body.removeChild(el);
|
|
return false;
|
|
}
|
|
has3d = computedStyle.getPropertyValue(transforms[t]);
|
|
}
|
|
}
|
|
document.body.removeChild(el);
|
|
Blockly.utils.is3dSupported.cached_ = has3d !== 'none';
|
|
return Blockly.utils.is3dSupported.cached_;
|
|
};
|
|
|
|
/**
|
|
* Insert a node after a reference node.
|
|
* Contrast with node.insertBefore function.
|
|
* @param {!Element} newNode New element to insert.
|
|
* @param {!Element} refNode Existing element to precede new node.
|
|
* @private
|
|
*/
|
|
Blockly.utils.insertAfter_ = function(newNode, refNode) {
|
|
var siblingNode = refNode.nextSibling;
|
|
var parentNode = refNode.parentNode;
|
|
if (!parentNode) {
|
|
throw 'Reference node has no parent.';
|
|
}
|
|
if (siblingNode) {
|
|
parentNode.insertBefore(newNode, siblingNode);
|
|
} else {
|
|
parentNode.appendChild(newNode);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Calls a function after the page has loaded, possibly immediately.
|
|
* @param {function()} fn Function to run.
|
|
* @throws Error Will throw if no global document can be found (e.g., Node.js).
|
|
*/
|
|
Blockly.utils.runAfterPageLoad = function(fn) {
|
|
if (!document) {
|
|
throw new Error('Blockly.utils.runAfterPageLoad() requires browser document.');
|
|
}
|
|
if (document.readyState === 'complete') {
|
|
fn(); // Page has already loaded. Call immediately.
|
|
} else {
|
|
// Poll readyState.
|
|
var readyStateCheckInterval = setInterval(function() {
|
|
if (document.readyState === 'complete') {
|
|
clearInterval(readyStateCheckInterval);
|
|
fn();
|
|
}
|
|
}, 10);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Sets the CSS transform property on an element. This function sets the
|
|
* non-vendor-prefixed and vendor-prefixed versions for backwards compatibility
|
|
* with older browsers. See http://caniuse.com/#feat=transforms2d
|
|
* @param {!Element} node The node which the CSS transform should be applied.
|
|
* @param {string} transform The value of the CSS `transform` property.
|
|
*/
|
|
Blockly.utils.setCssTransform = function(node, transform) {
|
|
node.style['transform'] = transform;
|
|
node.style['-webkit-transform'] = transform;
|
|
};
|