@blockdia/scratch-blocks 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/.nvmrc +1 -0
  2. package/LICENSE +674 -0
  3. package/README.md +57 -0
  4. package/TRADEMARK +1 -0
  5. package/blockly_compressed_horizontal.js +2268 -0
  6. package/blockly_compressed_vertical.js +2296 -0
  7. package/blockly_uncompressed_horizontal.js +1212 -0
  8. package/blockly_uncompressed_vertical.js +1212 -0
  9. package/blocks_common/colour.js +61 -0
  10. package/blocks_common/math.js +159 -0
  11. package/blocks_common/matrix.js +54 -0
  12. package/blocks_common/note.js +58 -0
  13. package/blocks_common/text.js +57 -0
  14. package/blocks_compressed.js +37 -0
  15. package/blocks_compressed_horizontal.js +68 -0
  16. package/blocks_compressed_vertical.js +216 -0
  17. package/blocks_horizontal/control.js +212 -0
  18. package/blocks_horizontal/default_toolbox.js +139 -0
  19. package/blocks_horizontal/event.js +190 -0
  20. package/blocks_horizontal/wedo.js +325 -0
  21. package/blocks_vertical/control.js +532 -0
  22. package/blocks_vertical/data.js +666 -0
  23. package/blocks_vertical/default_toolbox.js +571 -0
  24. package/blocks_vertical/event.js +329 -0
  25. package/blocks_vertical/extensions.js +294 -0
  26. package/blocks_vertical/looks.js +591 -0
  27. package/blocks_vertical/motion.js +587 -0
  28. package/blocks_vertical/operators.js +470 -0
  29. package/blocks_vertical/procedures.js +1051 -0
  30. package/blocks_vertical/sensing.js +555 -0
  31. package/blocks_vertical/sound.js +246 -0
  32. package/blocks_vertical/vertical_extensions.js +289 -0
  33. package/build/gen_blocks.js +1 -0
  34. package/build/test_expect.js +1 -0
  35. package/build/test_input.js +1 -0
  36. package/build.py +647 -0
  37. package/cleanup.sh +101 -0
  38. package/core/block.js +1837 -0
  39. package/core/block_animations.js +107 -0
  40. package/core/block_drag_surface.js +299 -0
  41. package/core/block_dragger.js +424 -0
  42. package/core/block_events.js +531 -0
  43. package/core/block_render_svg_horizontal.js +892 -0
  44. package/core/block_render_svg_vertical.js +1734 -0
  45. package/core/block_svg.js +1355 -0
  46. package/core/blockly.js +620 -0
  47. package/core/blocks.js +37 -0
  48. package/core/bubble.js +664 -0
  49. package/core/bubble_dragger.js +285 -0
  50. package/core/colours.js +177 -0
  51. package/core/comment.js +293 -0
  52. package/core/comment_events.js +539 -0
  53. package/core/connection.js +776 -0
  54. package/core/connection_db.js +300 -0
  55. package/core/constants.js +408 -0
  56. package/core/contextmenu.js +534 -0
  57. package/core/css.js +1354 -0
  58. package/core/data_category.js +490 -0
  59. package/core/dragged_connection_manager.js +260 -0
  60. package/core/dropdowndiv.js +408 -0
  61. package/core/events.js +429 -0
  62. package/core/events_abstract.js +113 -0
  63. package/core/extensions.js +450 -0
  64. package/core/field.js +810 -0
  65. package/core/field_angle.js +410 -0
  66. package/core/field_checkbox.js +133 -0
  67. package/core/field_colour.js +253 -0
  68. package/core/field_colour_slider.js +387 -0
  69. package/core/field_date.js +353 -0
  70. package/core/field_dropdown.js +447 -0
  71. package/core/field_iconmenu.js +309 -0
  72. package/core/field_image.js +200 -0
  73. package/core/field_label.js +136 -0
  74. package/core/field_label_serializable.js +125 -0
  75. package/core/field_matrix.js +566 -0
  76. package/core/field_note.js +850 -0
  77. package/core/field_number.js +366 -0
  78. package/core/field_numberdropdown.js +77 -0
  79. package/core/field_textdropdown.js +164 -0
  80. package/core/field_textinput.js +675 -0
  81. package/core/field_textinput_removable.js +105 -0
  82. package/core/field_variable.js +385 -0
  83. package/core/field_variable_getter.js +185 -0
  84. package/core/field_vertical_separator.js +161 -0
  85. package/core/flyout_base.js +935 -0
  86. package/core/flyout_button.js +324 -0
  87. package/core/flyout_dragger.js +83 -0
  88. package/core/flyout_extension_category_header.js +159 -0
  89. package/core/flyout_horizontal.js +475 -0
  90. package/core/flyout_vertical.js +770 -0
  91. package/core/generator.js +426 -0
  92. package/core/gesture.js +1010 -0
  93. package/core/grid.js +227 -0
  94. package/core/icon.js +205 -0
  95. package/core/inject.js +496 -0
  96. package/core/input.js +285 -0
  97. package/core/insertion_marker_manager.js +678 -0
  98. package/core/intersection_observer.js +102 -0
  99. package/core/msg.js +62 -0
  100. package/core/mutator.js +426 -0
  101. package/core/names.js +198 -0
  102. package/core/options.js +244 -0
  103. package/core/procedures.js +739 -0
  104. package/core/rendered_connection.js +417 -0
  105. package/core/scratch_block_comment.js +646 -0
  106. package/core/scratch_blocks_utils.js +246 -0
  107. package/core/scratch_bubble.js +699 -0
  108. package/core/scratch_events.js +131 -0
  109. package/core/scratch_msgs.js +85 -0
  110. package/core/scrollbar.js +875 -0
  111. package/core/toolbox.js +803 -0
  112. package/core/tooltip.js +337 -0
  113. package/core/touch.js +226 -0
  114. package/core/trashcan.js +343 -0
  115. package/core/ui_events.js +91 -0
  116. package/core/ui_menu_utils.js +68 -0
  117. package/core/utils.js +825 -0
  118. package/core/variable_events.js +259 -0
  119. package/core/variable_map.js +415 -0
  120. package/core/variable_model.js +116 -0
  121. package/core/variables.js +674 -0
  122. package/core/warning.js +199 -0
  123. package/core/widgetdiv.js +344 -0
  124. package/core/workspace.js +673 -0
  125. package/core/workspace_audio.js +170 -0
  126. package/core/workspace_comment.js +426 -0
  127. package/core/workspace_comment_render_svg.js +706 -0
  128. package/core/workspace_comment_svg.js +609 -0
  129. package/core/workspace_drag_surface_svg.js +195 -0
  130. package/core/workspace_dragger.js +132 -0
  131. package/core/workspace_svg.js +2382 -0
  132. package/core/xml.js +930 -0
  133. package/core/zoom_controls.js +301 -0
  134. package/dist/horizontal.js +222 -0
  135. package/dist/vertical.js +222 -0
  136. package/dist/web/horizontal.js +232 -0
  137. package/dist/web/vertical.js +232 -0
  138. package/i18n/common.py +234 -0
  139. package/i18n/create_messages.py +162 -0
  140. package/i18n/create_scratch_msgs.js +69 -0
  141. package/i18n/dedup_json.py +73 -0
  142. package/i18n/js_to_json.js +46 -0
  143. package/i18n/js_to_json.py +136 -0
  144. package/i18n/json_to_js.js +52 -0
  145. package/i18n/json_to_js.py +185 -0
  146. package/i18n/sync_tx_translations.js +111 -0
  147. package/i18n/test_scratch_msgs.js +87 -0
  148. package/i18n/tests.py +47 -0
  149. package/i18n/xliff_to_json.py +232 -0
  150. package/local_build.sh +70 -0
  151. package/media/click.mp3 +0 -0
  152. package/media/click.ogg +0 -0
  153. package/media/click.wav +0 -0
  154. package/media/comment-arrow-down.svg +10 -0
  155. package/media/comment-arrow-up.svg +10 -0
  156. package/media/delete-x.svg +10 -0
  157. package/media/delete.mp3 +0 -0
  158. package/media/delete.ogg +0 -0
  159. package/media/delete.wav +0 -0
  160. package/media/dropdown-arrow-dark.svg +1 -0
  161. package/media/dropdown-arrow.svg +1 -0
  162. package/media/extensions/microbit-block-icon.svg +130 -0
  163. package/media/extensions/music-block-icon.svg +17 -0
  164. package/media/extensions/pen-block-icon.svg +19 -0
  165. package/media/extensions/wedo2-block-icon.svg +36 -0
  166. package/media/eyedropper.svg +22 -0
  167. package/media/green-flag.svg +17 -0
  168. package/media/handclosed.cur +0 -0
  169. package/media/handdelete.cur +0 -0
  170. package/media/handopen.cur +0 -0
  171. package/media/icons/arrow.svg +12 -0
  172. package/media/icons/arrow_button.svg +1 -0
  173. package/media/icons/control_forever.svg +1 -0
  174. package/media/icons/control_repeat.svg +1 -0
  175. package/media/icons/control_stop.svg +1 -0
  176. package/media/icons/control_wait.svg +1 -0
  177. package/media/icons/event_broadcast_blue.svg +1 -0
  178. package/media/icons/event_broadcast_coral.svg +1 -0
  179. package/media/icons/event_broadcast_green.svg +1 -0
  180. package/media/icons/event_broadcast_magenta.svg +1 -0
  181. package/media/icons/event_broadcast_orange.svg +1 -0
  182. package/media/icons/event_broadcast_purple.svg +1 -0
  183. package/media/icons/event_when-broadcast-received_blue.svg +1 -0
  184. package/media/icons/event_when-broadcast-received_coral.svg +1 -0
  185. package/media/icons/event_when-broadcast-received_green.svg +1 -0
  186. package/media/icons/event_when-broadcast-received_magenta.svg +1 -0
  187. package/media/icons/event_when-broadcast-received_orange.svg +1 -0
  188. package/media/icons/event_when-broadcast-received_purple.svg +1 -0
  189. package/media/icons/event_whenflagclicked.svg +1 -0
  190. package/media/icons/remove.svg +19 -0
  191. package/media/icons/set-led_blue.svg +1 -0
  192. package/media/icons/set-led_coral.svg +1 -0
  193. package/media/icons/set-led_green.svg +1 -0
  194. package/media/icons/set-led_magenta.svg +1 -0
  195. package/media/icons/set-led_mystery.svg +1 -0
  196. package/media/icons/set-led_orange.svg +1 -0
  197. package/media/icons/set-led_purple.svg +1 -0
  198. package/media/icons/set-led_white.svg +1 -0
  199. package/media/icons/set-led_yellow.svg +1 -0
  200. package/media/icons/wedo_motor-clockwise.svg +1 -0
  201. package/media/icons/wedo_motor-counterclockwise.svg +1 -0
  202. package/media/icons/wedo_motor-speed_fast.svg +1 -0
  203. package/media/icons/wedo_motor-speed_med.svg +1 -0
  204. package/media/icons/wedo_motor-speed_slow.svg +1 -0
  205. package/media/icons/wedo_when-distance_close.svg +1 -0
  206. package/media/icons/wedo_when-tilt-backward.svg +1 -0
  207. package/media/icons/wedo_when-tilt-forward.svg +1 -0
  208. package/media/icons/wedo_when-tilt-left.svg +1 -0
  209. package/media/icons/wedo_when-tilt-right.svg +1 -0
  210. package/media/icons/wedo_when-tilt.svg +1 -0
  211. package/media/repeat.svg +18 -0
  212. package/media/rotate-left.svg +1 -0
  213. package/media/rotate-right.svg +1 -0
  214. package/media/sprites.png +0 -0
  215. package/media/status-not-ready.svg +13 -0
  216. package/media/status-ready.svg +13 -0
  217. package/media/zoom-in.svg +1 -0
  218. package/media/zoom-out.svg +1 -0
  219. package/media/zoom-reset.svg +1 -0
  220. package/msg/js/en.js +290 -0
  221. package/msg/json/en.json +285 -0
  222. package/msg/messages.js +359 -0
  223. package/msg/scratch_msgs.js +22969 -0
  224. package/package.json +60 -0
  225. package/pull_from_blockly.sh +151 -0
  226. package/renovate.json5 +15 -0
  227. package/shim/blockly_compressed_horizontal-blocks_compressed.js +1 -0
  228. package/shim/blockly_compressed_horizontal.Blockly.js +1 -0
  229. package/shim/blockly_compressed_horizontal.goog.js +1 -0
  230. package/shim/blockly_compressed_horizontal.js +1 -0
  231. package/shim/blockly_compressed_vertical-blocks_compressed.js +1 -0
  232. package/shim/blockly_compressed_vertical.Blockly.js +1 -0
  233. package/shim/blockly_compressed_vertical.goog.js +1 -0
  234. package/shim/blockly_compressed_vertical.js +1 -0
  235. package/shim/blocks_compressed_horizontal-blockly_compressed_horizontal-messages.js +1 -0
  236. package/shim/blocks_compressed_horizontal.js +1 -0
  237. package/shim/blocks_compressed_vertical-blockly_compressed_vertical-messages.js +1 -0
  238. package/shim/blocks_compressed_vertical.js +1 -0
  239. package/shim/gh-pages.js +1 -0
  240. package/shim/horizontal.js +1 -0
  241. package/shim/index.js +17 -0
  242. package/shim/vertical.js +1 -0
  243. package/universal-python.js +82 -0
package/core/utils.js ADDED
@@ -0,0 +1,825 @@
1
+ /**
2
+ * @license
3
+ * Visual Blocks Editor
4
+ *
5
+ * Copyright 2012 Google Inc.
6
+ * https://developers.google.com/blockly/
7
+ *
8
+ * Licensed under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License.
10
+ * You may obtain a copy of the License at
11
+ *
12
+ * http://www.apache.org/licenses/LICENSE-2.0
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ */
20
+
21
+ /**
22
+ * @fileoverview Utility methods.
23
+ * These methods are not specific to Blockly, and could be factored out into
24
+ * a JavaScript framework such as Closure.
25
+ * @author fraser@google.com (Neil Fraser)
26
+ */
27
+ 'use strict';
28
+
29
+ /**
30
+ * @name Blockly.utils
31
+ * @namespace
32
+ **/
33
+ goog.provide('Blockly.utils');
34
+
35
+ goog.require('Blockly.Touch');
36
+ goog.require('goog.dom');
37
+ goog.require('goog.events.BrowserFeature');
38
+ goog.require('goog.math.Coordinate');
39
+ goog.require('goog.userAgent');
40
+
41
+
42
+ /**
43
+ * To allow ADVANCED_OPTIMIZATIONS, combining variable.name and variable['name']
44
+ * is not possible. To access the exported Blockly.Msg.Something it needs to be
45
+ * accessed through the exact name that was exported. Note, that all the exports
46
+ * are happening as the last thing in the generated js files, so they won't be
47
+ * accessible before JavaScript loads!
48
+ * @return {!Object.<string, string>} The message array.
49
+ * @private
50
+ */
51
+ Blockly.utils.getMessageArray_ = function() {
52
+ return goog.global['Blockly']['Msg'];
53
+ };
54
+
55
+ /**
56
+ * Remove an attribute from a element even if it's in IE 10.
57
+ * Similar to Element.removeAttribute() but it works on SVG elements in IE 10.
58
+ * Sets the attribute to null in IE 10, which treats removeAttribute as a no-op
59
+ * if it's called on an SVG element.
60
+ * @param {!Element} element DOM element to remove attribute from.
61
+ * @param {string} attributeName Name of attribute to remove.
62
+ */
63
+ Blockly.utils.removeAttribute = function(element, attributeName) {
64
+ // goog.userAgent.isVersion is deprecated, but the replacement is
65
+ // goog.userAgent.isVersionOrHigher.
66
+ if (goog.userAgent.IE && goog.userAgent.isVersion('10.0')) {
67
+ element.setAttribute(attributeName, null);
68
+ } else {
69
+ element.removeAttribute(attributeName);
70
+ }
71
+ };
72
+
73
+ /**
74
+ * Add a CSS class to a element.
75
+ * Similar to Closure's goog.dom.classes.add, except it handles SVG elements.
76
+ * @param {!Element} element DOM element to add class to.
77
+ * @param {string} className Name of class to add.
78
+ * @return {boolean} True if class was added, false if already present.
79
+ */
80
+ Blockly.utils.addClass = function(element, className) {
81
+ var classes = element.getAttribute('class') || '';
82
+ if ((' ' + classes + ' ').indexOf(' ' + className + ' ') != -1) {
83
+ return false;
84
+ }
85
+ if (classes) {
86
+ classes += ' ';
87
+ }
88
+ element.setAttribute('class', classes + className);
89
+ return true;
90
+ };
91
+
92
+ /**
93
+ * Remove a CSS class from a element.
94
+ * Similar to Closure's goog.dom.classes.remove, except it handles SVG elements.
95
+ * @param {!Element} element DOM element to remove class from.
96
+ * @param {string} className Name of class to remove.
97
+ * @return {boolean} True if class was removed, false if never present.
98
+ */
99
+ Blockly.utils.removeClass = function(element, className) {
100
+ var classes = element.getAttribute('class');
101
+ if ((' ' + classes + ' ').indexOf(' ' + className + ' ') == -1) {
102
+ return false;
103
+ }
104
+ var classList = classes.split(/\s+/);
105
+ for (var i = 0; i < classList.length; i++) {
106
+ if (!classList[i] || classList[i] == className) {
107
+ classList.splice(i, 1);
108
+ i--;
109
+ }
110
+ }
111
+ if (classList.length) {
112
+ element.setAttribute('class', classList.join(' '));
113
+ } else {
114
+ Blockly.utils.removeAttribute(element, 'class');
115
+ }
116
+ return true;
117
+ };
118
+
119
+ /**
120
+ * Checks if an element has the specified CSS class.
121
+ * Similar to Closure's goog.dom.classes.has, except it handles SVG elements.
122
+ * @param {!Element} element DOM element to check.
123
+ * @param {string} className Name of class to check.
124
+ * @return {boolean} True if class exists, false otherwise.
125
+ * @package
126
+ */
127
+ Blockly.utils.hasClass = function(element, className) {
128
+ var classes = element.getAttribute('class');
129
+ return (' ' + classes + ' ').indexOf(' ' + className + ' ') != -1;
130
+ };
131
+
132
+ /**
133
+ * Don't do anything for this event, just halt propagation.
134
+ * @param {!Event} e An event.
135
+ */
136
+ Blockly.utils.noEvent = function(e) {
137
+ // This event has been handled. No need to bubble up to the document.
138
+ e.preventDefault();
139
+ e.stopPropagation();
140
+ };
141
+
142
+ /**
143
+ * Is this event targeting a text input widget?
144
+ * @param {!Event} e An event.
145
+ * @return {boolean} True if text input.
146
+ */
147
+ Blockly.utils.isTargetInput = function(e) {
148
+ return e.target.type == 'textarea' || e.target.type == 'text' ||
149
+ e.target.type == 'number' || e.target.type == 'email' ||
150
+ e.target.type == 'password' || e.target.type == 'search' ||
151
+ e.target.type == 'tel' || e.target.type == 'url' ||
152
+ e.target.isContentEditable;
153
+ };
154
+
155
+ /**
156
+ * Return the coordinates of the top-left corner of this element relative to
157
+ * its parent. Only for SVG elements and children (e.g. rect, g, path).
158
+ * @param {!Element} element SVG element to find the coordinates of.
159
+ * @return {!goog.math.Coordinate} Object with .x and .y properties.
160
+ */
161
+ Blockly.utils.getRelativeXY = function(element) {
162
+ var xy = new goog.math.Coordinate(0, 0);
163
+ // First, check for x and y attributes.
164
+ var x = element.getAttribute('x');
165
+ if (x) {
166
+ xy.x = parseInt(x, 10);
167
+ }
168
+ var y = element.getAttribute('y');
169
+ if (y) {
170
+ xy.y = parseInt(y, 10);
171
+ }
172
+ // Second, check for transform="translate(...)" attribute.
173
+ var transform = element.getAttribute('transform');
174
+ var r = transform && transform.match(Blockly.utils.getRelativeXY.XY_REGEX_);
175
+ if (r) {
176
+ xy.x += parseFloat(r[1]);
177
+ if (r[3]) {
178
+ xy.y += parseFloat(r[3]);
179
+ }
180
+ }
181
+
182
+ // Then check for style = transform: translate(...) or translate3d(...)
183
+ var style = element.getAttribute('style');
184
+ if (style && style.indexOf('translate') > -1) {
185
+ var styleComponents = style.match(Blockly.utils.getRelativeXY.XY_STYLE_REGEX_);
186
+ if (styleComponents) {
187
+ xy.x += parseFloat(styleComponents[1]);
188
+ if (styleComponents[3]) {
189
+ xy.y += parseFloat(styleComponents[3]);
190
+ }
191
+ }
192
+ }
193
+ return xy;
194
+ };
195
+
196
+ /**
197
+ * Return the coordinates of the top-left corner of this element relative to
198
+ * the div blockly was injected into.
199
+ * @param {!Element} element SVG element to find the coordinates of. If this is
200
+ * not a child of the div blockly was injected into, the behaviour is
201
+ * undefined.
202
+ * @return {!goog.math.Coordinate} Object with .x and .y properties.
203
+ */
204
+ Blockly.utils.getInjectionDivXY_ = function(element) {
205
+ var x = 0;
206
+ var y = 0;
207
+ while (element) {
208
+ var xy = Blockly.utils.getRelativeXY(element);
209
+ var scale = Blockly.utils.getScale_(element);
210
+ x = (x * scale) + xy.x;
211
+ y = (y * scale) + xy.y;
212
+ var classes = element.getAttribute('class') || '';
213
+ if ((' ' + classes + ' ').indexOf(' injectionDiv ') != -1) {
214
+ break;
215
+ }
216
+ element = element.parentNode;
217
+ }
218
+ return new goog.math.Coordinate(x, y);
219
+ };
220
+
221
+ /**
222
+ * Return the scale of this element.
223
+ * @param {!Element} element The element to find the coordinates of.
224
+ * @return {!number} number represending the scale applied to the element.
225
+ * @private
226
+ */
227
+ Blockly.utils.getScale_ = function(element) {
228
+ var scale = 1;
229
+ var transform = element.getAttribute('transform');
230
+ if (transform) {
231
+ var transformComponents =
232
+ transform.match(Blockly.utils.getScale_.REGEXP_);
233
+ if (transformComponents && transformComponents[0]) {
234
+ scale = parseFloat(transformComponents[0]);
235
+ }
236
+ }
237
+ return scale;
238
+ };
239
+
240
+ /**
241
+ * Static regex to pull the x,y values out of an SVG translate() directive.
242
+ * Note that Firefox and IE (9,10) return 'translate(12)' instead of
243
+ * 'translate(12, 0)'.
244
+ * Note that IE (9,10) returns 'translate(16 8)' instead of 'translate(16, 8)'.
245
+ * Note that IE has been reported to return scientific notation (0.123456e-42).
246
+ * @type {!RegExp}
247
+ * @private
248
+ */
249
+ Blockly.utils.getRelativeXY.XY_REGEX_ =
250
+ /translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/;
251
+
252
+
253
+ /**
254
+ * Static regex to pull the scale values out of a transform style property.
255
+ * Accounts for same exceptions as XY_REGEXP_.
256
+ * @type {!RegExp}
257
+ * @private
258
+ */
259
+ Blockly.utils.getScale_REGEXP_ = /scale\(\s*([-+\d.e]+)\s*\)/;
260
+
261
+ /**
262
+ * Static regex to pull the x,y values out of a translate3d() or translate3d()
263
+ * style property.
264
+ * Accounts for same exceptions as XY_REGEXP_.
265
+ * @type {!RegExp}
266
+ * @private
267
+ */
268
+ Blockly.utils.getRelativeXY.XY_STYLE_REGEX_ =
269
+ /transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/;
270
+
271
+ /**
272
+ * Helper method for creating SVG elements.
273
+ * @param {string} name Element's tag name.
274
+ * @param {!Object} attrs Dictionary of attribute names and values.
275
+ * @param {Element} parent Optional parent on which to append the element.
276
+ * @return {!SVGElement} Newly created SVG element.
277
+ */
278
+ Blockly.utils.createSvgElement = function(name, attrs, parent /*, opt_workspace */) {
279
+ var e = /** @type {!SVGElement} */
280
+ (document.createElementNS(Blockly.SVG_NS, name));
281
+ for (var key in attrs) {
282
+ e.setAttribute(key, attrs[key]);
283
+ }
284
+ // IE defines a unique attribute "runtimeStyle", it is NOT applied to
285
+ // elements created with createElementNS. However, Closure checks for IE
286
+ // and assumes the presence of the attribute and crashes.
287
+ if (document.body.runtimeStyle) { // Indicates presence of IE-only attr.
288
+ e.runtimeStyle = e.currentStyle = e.style;
289
+ }
290
+ if (parent) {
291
+ parent.appendChild(e);
292
+ }
293
+ return e;
294
+ };
295
+
296
+ /**
297
+ * Is this event a right-click?
298
+ * @param {!Event} e Mouse event.
299
+ * @return {boolean} True if right-click.
300
+ */
301
+ Blockly.utils.isRightButton = function(e) {
302
+ if (e.ctrlKey && goog.userAgent.MAC) {
303
+ // Control-clicking on Mac OS X is treated as a right-click.
304
+ // WebKit on Mac OS X fails to change button to 2 (but Gecko does).
305
+ return true;
306
+ }
307
+ return e.button == 2;
308
+ };
309
+
310
+ /**
311
+ * Return the converted coordinates of the given mouse event.
312
+ * The origin (0,0) is the top-left corner of the Blockly SVG.
313
+ * @param {!Event} e Mouse event.
314
+ * @param {!Element} svg SVG element.
315
+ * @param {SVGMatrix} matrix Inverted screen CTM to use.
316
+ * @return {!SVGPoint} Object with .x and .y properties.
317
+ */
318
+ Blockly.utils.mouseToSvg = function(e, svg, matrix) {
319
+ var svgPoint = svg.createSVGPoint();
320
+ svgPoint.x = e.clientX;
321
+ svgPoint.y = e.clientY;
322
+
323
+ if (!matrix) {
324
+ matrix = svg.getScreenCTM().inverse();
325
+ }
326
+ return svgPoint.matrixTransform(matrix);
327
+ };
328
+
329
+ /**
330
+ * Parse a string with any number of interpolation tokens (%1, %2, ...).
331
+ * It will also replace string table references (e.g., %{bky_my_msg} and
332
+ * %{BKY_MY_MSG} will both be replaced with the value in
333
+ * Blockly.Msg['MY_MSG']). Percentage sign characters '%' may be self-escaped
334
+ * (e.g., '%%').
335
+ * @param {string} message Text which might contain string table references and
336
+ * interpolation tokens.
337
+ * @return {!Array.<string|number>} Array of strings and numbers.
338
+ */
339
+ Blockly.utils.tokenizeInterpolation = function(message) {
340
+ return Blockly.utils.tokenizeInterpolation_(message, true);
341
+ };
342
+
343
+ /**
344
+ * Replaces string table references in a message, if the message is a string.
345
+ * For example, "%{bky_my_msg}" and "%{BKY_MY_MSG}" will both be replaced with
346
+ * the value in Blockly.Msg['MY_MSG'].
347
+ * @param {string|?} message Message, which may be a string that contains
348
+ * string table references.
349
+ * @return {!string} String with message references replaced.
350
+ */
351
+ Blockly.utils.replaceMessageReferences = function(message) {
352
+ if (!goog.isString(message)) {
353
+ return message;
354
+ }
355
+ var interpolatedResult = Blockly.utils.tokenizeInterpolation_(message, false);
356
+ // When parseInterpolationTokens == false, interpolatedResult should be at
357
+ // most length 1.
358
+ return interpolatedResult.length ? interpolatedResult[0] : '';
359
+ };
360
+
361
+ /**
362
+ * Validates that any %{BKY_...} references in the message refer to keys of
363
+ * the Blockly.Msg string table.
364
+ * @param {string} message Text which might contain string table references.
365
+ * @return {boolean} True if all message references have matching values.
366
+ * Otherwise, false.
367
+ */
368
+ Blockly.utils.checkMessageReferences = function(message) {
369
+ var isValid = true; // True until a bad reference is found.
370
+
371
+ var regex = /%{BKY_([a-zA-Z][a-zA-Z0-9_]*)}/g;
372
+ var match = regex.exec(message);
373
+ while (match) {
374
+ var msgKey = match[1];
375
+ if (Blockly.utils.getMessageArray_()[msgKey] == undefined) {
376
+ console.log('WARNING: No message string for %{BKY_' + msgKey + '}.');
377
+ isValid = false;
378
+ }
379
+
380
+ // Re-run on remainder of string.
381
+ message = message.substring(match.index + msgKey.length + 1);
382
+ match = regex.exec(message);
383
+ }
384
+
385
+ return isValid;
386
+ };
387
+
388
+ /**
389
+ * Internal implementation of the message reference and interpolation token
390
+ * parsing used by tokenizeInterpolation() and replaceMessageReferences().
391
+ * @param {string} message Text which might contain string table references and
392
+ * interpolation tokens.
393
+ * @param {boolean} parseInterpolationTokens Option to parse numeric
394
+ * interpolation tokens (%1, %2, ...) when true.
395
+ * @return {!Array.<string|number>} Array of strings and numbers.
396
+ * @private
397
+ */
398
+ Blockly.utils.tokenizeInterpolation_ = function(message,
399
+ parseInterpolationTokens) {
400
+ var tokens = [];
401
+ var chars = message.split('');
402
+ chars.push(''); // End marker.
403
+ // Parse the message with a finite state machine.
404
+ // 0 - Base case.
405
+ // 1 - % found.
406
+ // 2 - Digit found.
407
+ // 3 - Message ref found.
408
+ var state = 0;
409
+ var buffer = [];
410
+ var number = null;
411
+ for (var i = 0; i < chars.length; i++) {
412
+ var c = chars[i];
413
+ if (state == 0) {
414
+ if (c == '%') {
415
+ var text = buffer.join('');
416
+ if (text) {
417
+ tokens.push(text);
418
+ }
419
+ buffer.length = 0;
420
+ state = 1; // Start escape.
421
+ } else {
422
+ buffer.push(c); // Regular char.
423
+ }
424
+ } else if (state == 1) {
425
+ if (c == '%') {
426
+ buffer.push(c); // Escaped %: %%
427
+ state = 0;
428
+ } else if (parseInterpolationTokens && '0' <= c && c <= '9') {
429
+ state = 2;
430
+ number = c;
431
+ var text = buffer.join('');
432
+ if (text) {
433
+ tokens.push(text);
434
+ }
435
+ buffer.length = 0;
436
+ } else if (c == '{') {
437
+ state = 3;
438
+ } else {
439
+ buffer.push('%', c); // Not recognized. Return as literal.
440
+ state = 0;
441
+ }
442
+ } else if (state == 2) {
443
+ if ('0' <= c && c <= '9') {
444
+ number += c; // Multi-digit number.
445
+ } else {
446
+ tokens.push(parseInt(number, 10));
447
+ i--; // Parse this char again.
448
+ state = 0;
449
+ }
450
+ } else if (state == 3) { // String table reference
451
+ if (c == '') {
452
+ // Premature end before closing '}'
453
+ buffer.splice(0, 0, '%{'); // Re-insert leading delimiter
454
+ i--; // Parse this char again.
455
+ state = 0; // and parse as string literal.
456
+ } else if (c != '}') {
457
+ buffer.push(c);
458
+ } else {
459
+ var rawKey = buffer.join('');
460
+ if (/[a-zA-Z][a-zA-Z0-9_]*/.test(rawKey)) { // Strict matching
461
+ // Found a valid string key. Attempt case insensitive match.
462
+ var keyUpper = rawKey.toUpperCase();
463
+
464
+ // BKY_ is the prefix used to namespace the strings used in Blockly
465
+ // core files and the predefined blocks in ../blocks/. These strings
466
+ // are defined in ../msgs/ files.
467
+ var bklyKey = goog.string.startsWith(keyUpper, 'BKY_') ?
468
+ keyUpper.substring(4) : null;
469
+ if (bklyKey && bklyKey in Blockly.Msg) {
470
+ var rawValue = Blockly.Msg[bklyKey];
471
+ if (goog.isString(rawValue)) {
472
+ // Attempt to dereference substrings, too, appending to the end.
473
+ Array.prototype.push.apply(tokens,
474
+ Blockly.utils.tokenizeInterpolation(rawValue));
475
+ } else if (parseInterpolationTokens) {
476
+ // When parsing interpolation tokens, numbers are special
477
+ // placeholders (%1, %2, etc). Make sure all other values are
478
+ // strings.
479
+ tokens.push(String(rawValue));
480
+ } else {
481
+ tokens.push(rawValue);
482
+ }
483
+ } else {
484
+ // No entry found in the string table. Pass reference as string.
485
+ tokens.push('%{' + rawKey + '}');
486
+ }
487
+ buffer.length = 0; // Clear the array
488
+ state = 0;
489
+ } else {
490
+ tokens.push('%{' + rawKey + '}');
491
+ buffer.length = 0;
492
+ state = 0; // and parse as string literal.
493
+ }
494
+ }
495
+ }
496
+ }
497
+ var text = buffer.join('');
498
+ if (text) {
499
+ tokens.push(text);
500
+ }
501
+
502
+ // Merge adjacent text tokens into a single string.
503
+ var mergedTokens = [];
504
+ buffer.length = 0;
505
+ for (var i = 0; i < tokens.length; ++i) {
506
+ if (typeof tokens[i] == 'string') {
507
+ buffer.push(tokens[i]);
508
+ } else {
509
+ text = buffer.join('');
510
+ if (text) {
511
+ mergedTokens.push(text);
512
+ }
513
+ buffer.length = 0;
514
+ mergedTokens.push(tokens[i]);
515
+ }
516
+ }
517
+ text = buffer.join('');
518
+ if (text) {
519
+ mergedTokens.push(text);
520
+ }
521
+ buffer.length = 0;
522
+
523
+ return mergedTokens;
524
+ };
525
+
526
+ /**
527
+ * Generate a unique ID. This should be globally unique.
528
+ * 87 characters ^ 20 length > 128 bits (better than a UUID).
529
+ * @return {string} A globally unique ID string.
530
+ */
531
+ Blockly.utils.genUid = function() {
532
+ var length = 20;
533
+ var soupLength = Blockly.utils.genUid.soup_.length;
534
+ var id = [];
535
+ for (var i = 0; i < length; i++) {
536
+ id[i] = Blockly.utils.genUid.soup_.charAt(Math.random() * soupLength);
537
+ }
538
+ return id.join('');
539
+ };
540
+
541
+ /**
542
+ * Legal characters for the unique ID. Should be all on a US keyboard.
543
+ * No characters that conflict with XML or JSON. Requests to remove additional
544
+ * 'problematic' characters from this soup will be denied. That's your failure
545
+ * to properly escape in your own environment. Issues #251, #625, #682, #1304.
546
+ * @private
547
+ */
548
+ Blockly.utils.genUid.soup_ = '!#$%()*+,-./:;=?@[]^_`{|}~' +
549
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
550
+
551
+ /**
552
+ * Wrap text to the specified width.
553
+ * @param {string} text Text to wrap.
554
+ * @param {number} limit Width to wrap each line.
555
+ * @return {string} Wrapped text.
556
+ */
557
+ Blockly.utils.wrap = function(text, limit) {
558
+ var lines = text.split('\n');
559
+ for (var i = 0; i < lines.length; i++) {
560
+ lines[i] = Blockly.utils.wrapLine_(lines[i], limit);
561
+ }
562
+ return lines.join('\n');
563
+ };
564
+
565
+ /**
566
+ * Wrap single line of text to the specified width.
567
+ * @param {string} text Text to wrap.
568
+ * @param {number} limit Width to wrap each line.
569
+ * @return {string} Wrapped text.
570
+ * @private
571
+ */
572
+ Blockly.utils.wrapLine_ = function(text, limit) {
573
+ if (text.length <= limit) {
574
+ // Short text, no need to wrap.
575
+ return text;
576
+ }
577
+ // Split the text into words.
578
+ var words = text.trim().split(/\s+/);
579
+ // Set limit to be the length of the largest word.
580
+ for (var i = 0; i < words.length; i++) {
581
+ if (words[i].length > limit) {
582
+ limit = words[i].length;
583
+ }
584
+ }
585
+
586
+ var lastScore;
587
+ var score = -Infinity;
588
+ var lastText;
589
+ var lineCount = 1;
590
+ do {
591
+ lastScore = score;
592
+ lastText = text;
593
+ // Create a list of booleans representing if a space (false) or
594
+ // a break (true) appears after each word.
595
+ var wordBreaks = [];
596
+ // Seed the list with evenly spaced linebreaks.
597
+ var steps = words.length / lineCount;
598
+ var insertedBreaks = 1;
599
+ for (var i = 0; i < words.length - 1; i++) {
600
+ if (insertedBreaks < (i + 1.5) / steps) {
601
+ insertedBreaks++;
602
+ wordBreaks[i] = true;
603
+ } else {
604
+ wordBreaks[i] = false;
605
+ }
606
+ }
607
+ wordBreaks = Blockly.utils.wrapMutate_(words, wordBreaks, limit);
608
+ score = Blockly.utils.wrapScore_(words, wordBreaks, limit);
609
+ text = Blockly.utils.wrapToText_(words, wordBreaks);
610
+ lineCount++;
611
+ } while (score > lastScore);
612
+ return lastText;
613
+ };
614
+
615
+ /**
616
+ * Compute a score for how good the wrapping is.
617
+ * @param {!Array.<string>} words Array of each word.
618
+ * @param {!Array.<boolean>} wordBreaks Array of line breaks.
619
+ * @param {number} limit Width to wrap each line.
620
+ * @return {number} Larger the better.
621
+ * @private
622
+ */
623
+ Blockly.utils.wrapScore_ = function(words, wordBreaks, limit) {
624
+ // If this function becomes a performance liability, add caching.
625
+ // Compute the length of each line.
626
+ var lineLengths = [0];
627
+ var linePunctuation = [];
628
+ for (var i = 0; i < words.length; i++) {
629
+ lineLengths[lineLengths.length - 1] += words[i].length;
630
+ if (wordBreaks[i] === true) {
631
+ lineLengths.push(0);
632
+ linePunctuation.push(words[i].charAt(words[i].length - 1));
633
+ } else if (wordBreaks[i] === false) {
634
+ lineLengths[lineLengths.length - 1]++;
635
+ }
636
+ }
637
+ var maxLength = Math.max.apply(Math, lineLengths);
638
+
639
+ var score = 0;
640
+ for (var i = 0; i < lineLengths.length; i++) {
641
+ // Optimize for width.
642
+ // -2 points per char over limit (scaled to the power of 1.5).
643
+ score -= Math.pow(Math.abs(limit - lineLengths[i]), 1.5) * 2;
644
+ // Optimize for even lines.
645
+ // -1 point per char smaller than max (scaled to the power of 1.5).
646
+ score -= Math.pow(maxLength - lineLengths[i], 1.5);
647
+ // Optimize for structure.
648
+ // Add score to line endings after punctuation.
649
+ if ('.?!'.indexOf(linePunctuation[i]) != -1) {
650
+ score += limit / 3;
651
+ } else if (',;)]}'.indexOf(linePunctuation[i]) != -1) {
652
+ score += limit / 4;
653
+ }
654
+ }
655
+ // All else being equal, the last line should not be longer than the
656
+ // previous line. For example, this looks wrong:
657
+ // aaa bbb
658
+ // ccc ddd eee
659
+ if (lineLengths.length > 1 && lineLengths[lineLengths.length - 1] <=
660
+ lineLengths[lineLengths.length - 2]) {
661
+ score += 0.5;
662
+ }
663
+ return score;
664
+ };
665
+
666
+ /**
667
+ * Mutate the array of line break locations until an optimal solution is found.
668
+ * No line breaks are added or deleted, they are simply moved around.
669
+ * @param {!Array.<string>} words Array of each word.
670
+ * @param {!Array.<boolean>} wordBreaks Array of line breaks.
671
+ * @param {number} limit Width to wrap each line.
672
+ * @return {!Array.<boolean>} New array of optimal line breaks.
673
+ * @private
674
+ */
675
+ Blockly.utils.wrapMutate_ = function(words, wordBreaks, limit) {
676
+ var bestScore = Blockly.utils.wrapScore_(words, wordBreaks, limit);
677
+ var bestBreaks;
678
+ // Try shifting every line break forward or backward.
679
+ for (var i = 0; i < wordBreaks.length - 1; i++) {
680
+ if (wordBreaks[i] == wordBreaks[i + 1]) {
681
+ continue;
682
+ }
683
+ var mutatedWordBreaks = [].concat(wordBreaks);
684
+ mutatedWordBreaks[i] = !mutatedWordBreaks[i];
685
+ mutatedWordBreaks[i + 1] = !mutatedWordBreaks[i + 1];
686
+ var mutatedScore =
687
+ Blockly.utils.wrapScore_(words, mutatedWordBreaks, limit);
688
+ if (mutatedScore > bestScore) {
689
+ bestScore = mutatedScore;
690
+ bestBreaks = mutatedWordBreaks;
691
+ }
692
+ }
693
+ if (bestBreaks) {
694
+ // Found an improvement. See if it may be improved further.
695
+ return Blockly.utils.wrapMutate_(words, bestBreaks, limit);
696
+ }
697
+ // No improvements found. Done.
698
+ return wordBreaks;
699
+ };
700
+
701
+ /**
702
+ * Reassemble the array of words into text, with the specified line breaks.
703
+ * @param {!Array.<string>} words Array of each word.
704
+ * @param {!Array.<boolean>} wordBreaks Array of line breaks.
705
+ * @return {string} Plain text.
706
+ * @private
707
+ */
708
+ Blockly.utils.wrapToText_ = function(words, wordBreaks) {
709
+ var text = [];
710
+ for (var i = 0; i < words.length; i++) {
711
+ text.push(words[i]);
712
+ if (wordBreaks[i] !== undefined) {
713
+ text.push(wordBreaks[i] ? '\n' : ' ');
714
+ }
715
+ }
716
+ return text.join('');
717
+ };
718
+
719
+ /**
720
+ * Check if 3D transforms are supported by adding an element
721
+ * and attempting to set the property.
722
+ * @return {boolean} true if 3D transforms are supported.
723
+ */
724
+ Blockly.utils.is3dSupported = function() {
725
+ // TW: Every browser we care about supports 3d. Don't bother checking.
726
+ // This saves about 0.5ms on every page load.
727
+ return true;
728
+ };
729
+
730
+ /**
731
+ * Insert a node after a reference node.
732
+ * Contrast with node.insertBefore function.
733
+ * @param {!Element} newNode New element to insert.
734
+ * @param {!Element} refNode Existing element to precede new node.
735
+ * @package
736
+ */
737
+ Blockly.utils.insertAfter = function(newNode, refNode) {
738
+ var siblingNode = refNode.nextSibling;
739
+ var parentNode = refNode.parentNode;
740
+ if (!parentNode) {
741
+ throw 'Reference node has no parent.';
742
+ }
743
+ if (siblingNode) {
744
+ parentNode.insertBefore(newNode, siblingNode);
745
+ } else {
746
+ parentNode.appendChild(newNode);
747
+ }
748
+ };
749
+
750
+ /**
751
+ * Calls a function after the page has loaded, possibly immediately.
752
+ * @param {function()} fn Function to run.
753
+ * @throws Error Will throw if no global document can be found (e.g., Node.js).
754
+ */
755
+ Blockly.utils.runAfterPageLoad = function(fn) {
756
+ if (!document) {
757
+ throw new Error('Blockly.utils.runAfterPageLoad() requires browser document.');
758
+ }
759
+ if (document.readyState === 'complete') {
760
+ fn(); // Page has already loaded. Call immediately.
761
+ } else {
762
+ // Poll readyState.
763
+ var readyStateCheckInterval = setInterval(function() {
764
+ if (document.readyState === 'complete') {
765
+ clearInterval(readyStateCheckInterval);
766
+ fn();
767
+ }
768
+ }, 10);
769
+ }
770
+ };
771
+
772
+ /**
773
+ * Sets the CSS transform property on an element. This function sets the
774
+ * non-vendor-prefixed and vendor-prefixed versions for backwards compatibility
775
+ * with older browsers. See http://caniuse.com/#feat=transforms2d
776
+ * @param {!Element} node The node which the CSS transform should be applied.
777
+ * @param {string} transform The value of the CSS `transform` property.
778
+ */
779
+ Blockly.utils.setCssTransform = function(node, transform) {
780
+ node.style['transform'] = transform;
781
+ node.style['-webkit-transform'] = transform;
782
+ };
783
+
784
+ /**
785
+ * Get the position of the current viewport in window coordinates. This takes
786
+ * scroll into account.
787
+ * @return {!Object} an object containing window width, height, and scroll
788
+ * position in window coordinates.
789
+ * @package
790
+ */
791
+ Blockly.utils.getViewportBBox = function() {
792
+ // Pixels.
793
+ var windowSize = goog.dom.getViewportSize();
794
+ // Pixels, in window coordinates.
795
+ var scrollOffset = goog.style.getViewportPageOffset(document);
796
+ return {
797
+ right: windowSize.width + scrollOffset.x,
798
+ bottom: windowSize.height + scrollOffset.y,
799
+ top: scrollOffset.y,
800
+ left: scrollOffset.x
801
+ };
802
+ };
803
+
804
+ /**
805
+ * Fast prefix-checker.
806
+ * Copied from Closure's goog.string.startsWith.
807
+ * @param {string} str The string to check.
808
+ * @param {string} prefix A string to look for at the start of `str`.
809
+ * @return {boolean} True if `str` begins with `prefix`.
810
+ * @package
811
+ */
812
+ Blockly.utils.startsWith = function(str, prefix) {
813
+ return str.lastIndexOf(prefix, 0) == 0;
814
+ };
815
+
816
+ /**
817
+ * Converts degrees to radians.
818
+ * Copied from Closure's goog.math.toRadians.
819
+ * @param {number} angleDegrees Angle in degrees.
820
+ * @return {number} Angle in radians.
821
+ * @package
822
+ */
823
+ Blockly.utils.toRadians = function(angleDegrees) {
824
+ return angleDegrees * Math.PI / 180;
825
+ };