blockly 7.20211209.4 → 8.0.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 (262) hide show
  1. package/blockly.d.ts +18963 -18432
  2. package/blockly.min.js +852 -844
  3. package/blockly_compressed.js +669 -664
  4. package/blockly_compressed.js.map +1 -1
  5. package/blocks/blocks.js +47 -0
  6. package/blocks/colour.js +13 -3
  7. package/blocks/lists.js +22 -13
  8. package/blocks/logic.js +13 -3
  9. package/blocks/loops.js +24 -11
  10. package/blocks/math.js +12 -3
  11. package/blocks/procedures.js +41 -27
  12. package/blocks/text.js +22 -13
  13. package/blocks/variables.js +14 -3
  14. package/blocks/variables_dynamic.js +13 -3
  15. package/blocks_compressed.js +146 -141
  16. package/blocks_compressed.js.map +1 -1
  17. package/core/block.js +1869 -1814
  18. package/core/block_drag_surface.js +201 -200
  19. package/core/block_dragger.js +377 -373
  20. package/core/block_svg.js +1593 -1479
  21. package/core/blockly.js +8 -22
  22. package/core/blocks.js +9 -2
  23. package/core/browser_events.js +22 -5
  24. package/core/bubble.js +841 -797
  25. package/core/bubble_dragger.js +213 -206
  26. package/core/bump_objects.js +2 -2
  27. package/core/clipboard.js +9 -9
  28. package/core/comment.js +353 -332
  29. package/core/common.js +46 -17
  30. package/core/component_manager.js +181 -174
  31. package/core/config.js +87 -0
  32. package/core/connection.js +595 -584
  33. package/core/connection_checker.js +242 -244
  34. package/core/connection_db.js +235 -230
  35. package/core/contextmenu.js +9 -6
  36. package/core/contextmenu_items.js +1 -2
  37. package/core/contextmenu_registry.js +93 -89
  38. package/core/css.js +474 -474
  39. package/core/delete_area.js +45 -42
  40. package/core/drag_target.js +57 -56
  41. package/core/dropdowndiv.js +153 -163
  42. package/core/events/events.js +2 -2
  43. package/core/events/events_abstract.js +89 -77
  44. package/core/events/events_block_base.js +37 -36
  45. package/core/events/events_block_change.js +130 -124
  46. package/core/events/events_block_create.js +73 -71
  47. package/core/events/events_block_delete.js +84 -82
  48. package/core/events/events_block_drag.js +50 -49
  49. package/core/events/events_block_move.js +147 -140
  50. package/core/events/events_bubble_open.js +51 -50
  51. package/core/events/events_click.js +48 -44
  52. package/core/events/events_comment_base.js +72 -69
  53. package/core/events/events_comment_change.js +63 -61
  54. package/core/events/events_comment_create.js +44 -42
  55. package/core/events/events_comment_delete.js +42 -40
  56. package/core/events/events_comment_move.js +106 -104
  57. package/core/events/events_marker_move.js +65 -64
  58. package/core/events/events_selected.js +46 -45
  59. package/core/events/events_theme_change.js +36 -35
  60. package/core/events/events_toolbox_item_select.js +46 -45
  61. package/core/events/events_trashcan_open.js +37 -36
  62. package/core/events/events_ui.js +47 -46
  63. package/core/events/events_ui_base.js +30 -29
  64. package/core/events/events_var_base.js +37 -36
  65. package/core/events/events_var_create.js +50 -48
  66. package/core/events/events_var_delete.js +50 -48
  67. package/core/events/events_var_rename.js +51 -49
  68. package/core/events/events_viewport.js +66 -65
  69. package/core/events/utils.js +29 -14
  70. package/core/events/workspace_events.js +49 -55
  71. package/core/extensions.js +4 -3
  72. package/core/field.js +1061 -997
  73. package/core/field_angle.js +462 -442
  74. package/core/field_checkbox.js +194 -182
  75. package/core/field_colour.js +519 -505
  76. package/core/field_dropdown.js +617 -598
  77. package/core/field_image.js +229 -220
  78. package/core/field_label.js +102 -91
  79. package/core/field_label_serializable.js +42 -41
  80. package/core/field_multilineinput.js +372 -358
  81. package/core/field_number.js +272 -253
  82. package/core/field_textinput.js +499 -467
  83. package/core/field_variable.js +458 -420
  84. package/core/flyout_base.js +1005 -952
  85. package/core/flyout_button.js +277 -260
  86. package/core/flyout_horizontal.js +304 -302
  87. package/core/flyout_metrics_manager.js +64 -64
  88. package/core/flyout_vertical.js +306 -300
  89. package/core/generator.js +459 -446
  90. package/core/gesture.js +829 -813
  91. package/core/grid.js +166 -163
  92. package/core/icon.js +168 -159
  93. package/core/inject.js +7 -5
  94. package/core/input.js +257 -248
  95. package/core/insertion_marker_manager.js +655 -624
  96. package/core/internal_constants.js +0 -129
  97. package/core/keyboard_nav/ast_node.js +605 -596
  98. package/core/keyboard_nav/basic_cursor.js +166 -165
  99. package/core/keyboard_nav/cursor.js +99 -97
  100. package/core/keyboard_nav/marker.js +83 -79
  101. package/core/keyboard_nav/tab_navigate_cursor.js +18 -23
  102. package/core/marker_manager.js +153 -141
  103. package/core/menu.js +377 -372
  104. package/core/menuitem.js +223 -217
  105. package/core/metrics_manager.js +403 -390
  106. package/core/mutator.js +468 -437
  107. package/core/names.js +229 -188
  108. package/core/options.js +290 -284
  109. package/core/procedures.js +29 -17
  110. package/core/registry.js +19 -16
  111. package/core/rendered_connection.js +482 -463
  112. package/core/renderers/common/block_rendering.js +9 -3
  113. package/core/renderers/common/constants.js +1119 -1112
  114. package/core/renderers/common/debug.js +14 -0
  115. package/core/renderers/common/debugger.js +338 -316
  116. package/core/renderers/common/drawer.js +380 -370
  117. package/core/renderers/common/i_path_object.js +2 -2
  118. package/core/renderers/common/info.js +626 -618
  119. package/core/renderers/common/marker_svg.js +579 -541
  120. package/core/renderers/common/path_object.js +203 -200
  121. package/core/renderers/common/renderer.js +220 -218
  122. package/core/renderers/geras/constants.js +36 -36
  123. package/core/renderers/geras/drawer.js +155 -147
  124. package/core/renderers/geras/highlight_constants.js +244 -238
  125. package/core/renderers/geras/highlighter.js +231 -179
  126. package/core/renderers/geras/info.js +392 -369
  127. package/core/renderers/geras/measurables/inline_input.js +25 -19
  128. package/core/renderers/geras/measurables/statement_input.js +23 -17
  129. package/core/renderers/geras/path_object.js +106 -121
  130. package/core/renderers/geras/renderer.js +96 -98
  131. package/core/renderers/measurables/base.js +30 -18
  132. package/core/renderers/measurables/bottom_row.js +83 -80
  133. package/core/renderers/measurables/connection.js +22 -15
  134. package/core/renderers/measurables/external_value_input.js +35 -22
  135. package/core/renderers/measurables/field.js +35 -20
  136. package/core/renderers/measurables/hat.js +18 -13
  137. package/core/renderers/measurables/icon.js +24 -17
  138. package/core/renderers/measurables/in_row_spacer.js +15 -13
  139. package/core/renderers/measurables/inline_input.js +43 -33
  140. package/core/renderers/measurables/input_connection.js +41 -28
  141. package/core/renderers/measurables/input_row.js +50 -44
  142. package/core/renderers/measurables/jagged_edge.js +14 -12
  143. package/core/renderers/measurables/next_connection.js +16 -14
  144. package/core/renderers/measurables/output_connection.js +26 -20
  145. package/core/renderers/measurables/previous_connection.js +16 -15
  146. package/core/renderers/measurables/round_corner.js +20 -18
  147. package/core/renderers/measurables/row.js +184 -168
  148. package/core/renderers/measurables/spacer_row.js +38 -23
  149. package/core/renderers/measurables/square_corner.js +18 -16
  150. package/core/renderers/measurables/statement_input.js +23 -20
  151. package/core/renderers/measurables/top_row.js +88 -85
  152. package/core/renderers/minimalist/constants.js +8 -7
  153. package/core/renderers/minimalist/drawer.js +11 -10
  154. package/core/renderers/minimalist/info.js +18 -18
  155. package/core/renderers/minimalist/renderer.js +40 -39
  156. package/core/renderers/thrasos/info.js +258 -248
  157. package/core/renderers/thrasos/renderer.js +20 -20
  158. package/core/renderers/zelos/constants.js +898 -873
  159. package/core/renderers/zelos/drawer.js +186 -169
  160. package/core/renderers/zelos/info.js +502 -479
  161. package/core/renderers/zelos/marker_svg.js +129 -115
  162. package/core/renderers/zelos/measurables/bottom_row.js +31 -30
  163. package/core/renderers/zelos/measurables/inputs.js +22 -21
  164. package/core/renderers/zelos/measurables/row_elements.js +14 -13
  165. package/core/renderers/zelos/measurables/top_row.js +34 -33
  166. package/core/renderers/zelos/path_object.js +181 -180
  167. package/core/renderers/zelos/renderer.js +91 -92
  168. package/core/scrollbar.js +759 -713
  169. package/core/scrollbar_pair.js +250 -245
  170. package/core/serialization/blocks.js +19 -9
  171. package/core/serialization/workspaces.js +3 -2
  172. package/core/shortcut_registry.js +286 -277
  173. package/core/sprites.js +31 -0
  174. package/core/theme.js +135 -141
  175. package/core/theme_manager.js +147 -143
  176. package/core/toolbox/category.js +602 -576
  177. package/core/toolbox/collapsible_category.js +226 -227
  178. package/core/toolbox/separator.js +70 -61
  179. package/core/toolbox/toolbox.js +934 -927
  180. package/core/toolbox/toolbox_item.js +115 -99
  181. package/core/tooltip.js +108 -35
  182. package/core/touch.js +8 -3
  183. package/core/touch_gesture.js +254 -251
  184. package/core/trashcan.js +606 -595
  185. package/core/utils/coordinate.js +97 -95
  186. package/core/utils/dom.js +2 -2
  187. package/core/utils/global.js +2 -0
  188. package/core/utils/rect.js +41 -37
  189. package/core/utils/sentinel.js +25 -0
  190. package/core/utils/size.js +30 -27
  191. package/core/utils/svg.js +18 -16
  192. package/core/variable_map.js +325 -341
  193. package/core/variable_model.js +55 -54
  194. package/core/variables.js +9 -2
  195. package/core/variables_dynamic.js +3 -1
  196. package/core/warning.js +126 -120
  197. package/core/widgetdiv.js +4 -4
  198. package/core/workspace.js +685 -664
  199. package/core/workspace_audio.js +124 -118
  200. package/core/workspace_comment.js +308 -298
  201. package/core/workspace_comment_svg.js +1029 -951
  202. package/core/workspace_drag_surface_svg.js +147 -140
  203. package/core/workspace_dragger.js +70 -71
  204. package/core/workspace_svg.js +2322 -2297
  205. package/core/xml.js +30 -20
  206. package/core/zoom_controls.js +431 -439
  207. package/dart_compressed.js +40 -43
  208. package/dart_compressed.js.map +1 -1
  209. package/generators/dart/colour.js +56 -64
  210. package/generators/dart/lists.js +61 -50
  211. package/generators/dart/math.js +160 -148
  212. package/generators/dart/text.js +83 -61
  213. package/generators/javascript/colour.js +37 -34
  214. package/generators/javascript/lists.js +50 -43
  215. package/generators/javascript/math.js +123 -139
  216. package/generators/javascript/text.js +67 -81
  217. package/generators/lua/colour.js +25 -23
  218. package/generators/lua/lists.js +97 -69
  219. package/generators/lua/logic.js +1 -2
  220. package/generators/lua/math.js +182 -144
  221. package/generators/lua/text.js +116 -99
  222. package/generators/php/colour.js +38 -32
  223. package/generators/php/lists.js +109 -89
  224. package/generators/php/math.js +90 -81
  225. package/generators/php/text.js +63 -61
  226. package/generators/python/colour.js +18 -18
  227. package/generators/python/lists.js +38 -30
  228. package/generators/python/loops.js +12 -8
  229. package/generators/python/math.js +104 -106
  230. package/generators/python/text.js +34 -30
  231. package/javascript_compressed.js +37 -39
  232. package/javascript_compressed.js.map +1 -1
  233. package/lua_compressed.js +39 -42
  234. package/lua_compressed.js.map +1 -1
  235. package/msg/az.js +2 -2
  236. package/msg/be.js +4 -4
  237. package/msg/cs.js +15 -15
  238. package/msg/de.js +1 -1
  239. package/msg/diq.js +1 -1
  240. package/msg/eo.js +1 -1
  241. package/msg/es.js +1 -1
  242. package/msg/fa.js +1 -1
  243. package/msg/fr.js +4 -4
  244. package/msg/he.js +1 -1
  245. package/msg/hr.js +2 -2
  246. package/msg/hy.js +2 -2
  247. package/msg/id.js +12 -12
  248. package/msg/inh.js +14 -14
  249. package/msg/ja.js +7 -7
  250. package/msg/lv.js +29 -29
  251. package/msg/pa.js +3 -3
  252. package/msg/smn.js +436 -0
  253. package/msg/te.js +1 -1
  254. package/msg/yue.js +1 -1
  255. package/msg/zh-hans.js +3 -3
  256. package/msg/zh-hant.js +3 -3
  257. package/package.json +7 -6
  258. package/php_compressed.js +38 -42
  259. package/php_compressed.js.map +1 -1
  260. package/python_compressed.js +26 -25
  261. package/python_compressed.js.map +1 -1
  262. package/blocks/all.js +0 -23
package/core/block.js CHANGED
@@ -15,8 +15,6 @@
15
15
  */
16
16
  goog.module('Blockly.Block');
17
17
 
18
- /* eslint-disable-next-line no-unused-vars */
19
- const Abstract = goog.requireType('Blockly.Events.Abstract');
20
18
  const Extensions = goog.require('Blockly.Extensions');
21
19
  const Tooltip = goog.require('Blockly.Tooltip');
22
20
  const arrayUtils = goog.require('Blockly.utils.array');
@@ -27,8 +25,12 @@ const fieldRegistry = goog.require('Blockly.fieldRegistry');
27
25
  const idGenerator = goog.require('Blockly.utils.idGenerator');
28
26
  const object = goog.require('Blockly.utils.object');
29
27
  const parsing = goog.require('Blockly.utils.parsing');
28
+ /* eslint-disable-next-line no-unused-vars */
29
+ const {Abstract} = goog.requireType('Blockly.Events.Abstract');
30
30
  const {Align, Input} = goog.require('Blockly.Input');
31
31
  const {ASTNode} = goog.require('Blockly.ASTNode');
32
+ /* eslint-disable-next-line no-unused-vars */
33
+ const {BlockMove} = goog.requireType('Blockly.Events.BlockMove');
32
34
  const {Blocks} = goog.require('Blockly.blocks');
33
35
  /* eslint-disable-next-line no-unused-vars */
34
36
  const {Comment} = goog.requireType('Blockly.Comment');
@@ -62,2095 +64,2148 @@ goog.require('Blockly.Events.BlockMove');
62
64
  /**
63
65
  * Class for one block.
64
66
  * Not normally called directly, workspace.newBlock() is preferred.
65
- * @param {!Workspace} workspace The block's workspace.
66
- * @param {!string} prototypeName Name of the language object containing
67
- * type-specific functions for this block.
68
- * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
69
- * create a new ID.
70
- * @constructor
71
67
  * @implements {IASTNodeLocation}
72
68
  * @implements {IDeletable}
73
- * @throws When the prototypeName is not valid or not allowed.
69
+ * @unrestricted
74
70
  * @alias Blockly.Block
75
71
  */
76
- const Block = function(workspace, prototypeName, opt_id) {
77
- const {Generator} = goog.module.get('Blockly.Generator');
78
- if (Generator && typeof Generator.prototype[prototypeName] !== 'undefined') {
79
- // Occluding Generator class members is not allowed.
80
- throw Error(
81
- 'Block prototypeName "' + prototypeName +
82
- '" conflicts with Blockly.Generator members.');
83
- }
84
-
85
- /** @type {string} */
86
- this.id = (opt_id && !workspace.getBlockById(opt_id)) ? opt_id :
87
- idGenerator.genUid();
88
- workspace.setBlockById(this.id, this);
89
- /** @type {Connection} */
90
- this.outputConnection = null;
91
- /** @type {Connection} */
92
- this.nextConnection = null;
93
- /** @type {Connection} */
94
- this.previousConnection = null;
95
- /** @type {!Array<!Input>} */
96
- this.inputList = [];
97
- /** @type {boolean|undefined} */
98
- this.inputsInline = undefined;
99
- /**
100
- * @type {boolean}
101
- * @private
72
+ class Block {
73
+ /**
74
+ * @param {!Workspace} workspace The block's workspace.
75
+ * @param {!string} prototypeName Name of the language object containing
76
+ * type-specific functions for this block.
77
+ * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
78
+ * create a new ID.
79
+ * @throws When the prototypeName is not valid or not allowed.
102
80
  */
103
- this.disabled = false;
104
- /** @type {!Tooltip.TipInfo} */
105
- this.tooltip = '';
106
- /** @type {boolean} */
107
- this.contextMenu = true;
81
+ constructor(workspace, prototypeName, opt_id) {
82
+ const {Generator} = goog.module.get('Blockly.Generator');
83
+ if (Generator &&
84
+ typeof Generator.prototype[prototypeName] !== 'undefined') {
85
+ // Occluding Generator class members is not allowed.
86
+ throw Error(
87
+ 'Block prototypeName "' + prototypeName +
88
+ '" conflicts with Blockly.Generator members.');
89
+ }
90
+
91
+ /**
92
+ * Optional text data that round-trips between blocks and XML.
93
+ * Has no effect. May be used by 3rd parties for meta information.
94
+ * @type {?string}
95
+ */
96
+ this.data = null;
97
+
98
+ /**
99
+ * Has this block been disposed of?
100
+ * @type {boolean}
101
+ * @package
102
+ */
103
+ this.disposed = false;
104
+
105
+ /**
106
+ * Colour of the block as HSV hue value (0-360)
107
+ * This may be null if the block colour was not set via a hue number.
108
+ * @type {?number}
109
+ * @private
110
+ */
111
+ this.hue_ = null;
112
+
113
+ /**
114
+ * Colour of the block in '#RRGGBB' format.
115
+ * @type {string}
116
+ * @protected
117
+ */
118
+ this.colour_ = '#000000';
119
+
120
+ /**
121
+ * Name of the block style.
122
+ * @type {string}
123
+ * @protected
124
+ */
125
+ this.styleName_ = '';
126
+
127
+ /**
128
+ * An optional method called during initialization.
129
+ * @type {undefined|?function()}
130
+ */
131
+ this.init = undefined;
132
+
133
+ /**
134
+ * An optional serialization method for defining how to serialize the
135
+ * mutation state to XML. This must be coupled with defining
136
+ * `domToMutation`.
137
+ * @type {undefined|?function(...):!Element}
138
+ */
139
+ this.mutationToDom = undefined;
140
+
141
+ /**
142
+ * An optional deserialization method for defining how to deserialize the
143
+ * mutation state from XML. This must be coupled with defining
144
+ * `mutationToDom`.
145
+ * @type {undefined|?function(!Element)}
146
+ */
147
+ this.domToMutation = undefined;
148
+
149
+ /**
150
+ * An optional serialization method for defining how to serialize the
151
+ * block's extra state (eg mutation state) to something JSON compatible.
152
+ * This must be coupled with defining `loadExtraState`.
153
+ * @type {undefined|?function(): *}
154
+ */
155
+ this.saveExtraState = undefined;
156
+
157
+ /**
158
+ * An optional serialization method for defining how to deserialize the
159
+ * block's extra state (eg mutation state) from something JSON compatible.
160
+ * This must be coupled with defining `saveExtraState`.
161
+ * @type {undefined|?function(*)}
162
+ */
163
+ this.loadExtraState = undefined;
164
+
165
+
166
+ /**
167
+ * An optional property for suppressing adding STATEMENT_PREFIX and
168
+ * STATEMENT_SUFFIX to generated code.
169
+ * @type {?boolean}
170
+ */
171
+ this.suppressPrefixSuffix = false;
172
+
173
+ /**
174
+ * An optional property for declaring developer variables. Return a list of
175
+ * variable names for use by generators. Developer variables are never
176
+ * shown to the user, but are declared as global variables in the generated
177
+ * code.
178
+ * @type {undefined|?function():!Array<string>}
179
+ */
180
+ this.getDeveloperVariables = undefined;
181
+
182
+ /** @type {string} */
183
+ this.id = (opt_id && !workspace.getBlockById(opt_id)) ?
184
+ opt_id :
185
+ idGenerator.genUid();
186
+ workspace.setBlockById(this.id, this);
187
+ /** @type {Connection} */
188
+ this.outputConnection = null;
189
+ /** @type {Connection} */
190
+ this.nextConnection = null;
191
+ /** @type {Connection} */
192
+ this.previousConnection = null;
193
+ /** @type {!Array<!Input>} */
194
+ this.inputList = [];
195
+ /** @type {boolean|undefined} */
196
+ this.inputsInline = undefined;
197
+ /**
198
+ * @type {boolean}
199
+ * @private
200
+ */
201
+ this.disabled = false;
202
+ /** @type {!Tooltip.TipInfo} */
203
+ this.tooltip = '';
204
+ /** @type {boolean} */
205
+ this.contextMenu = true;
206
+
207
+ /**
208
+ * @type {Block}
209
+ * @protected
210
+ */
211
+ this.parentBlock_ = null;
212
+
213
+ /**
214
+ * @type {!Array<!Block>}
215
+ * @protected
216
+ */
217
+ this.childBlocks_ = [];
218
+
219
+ /**
220
+ * @type {boolean}
221
+ * @private
222
+ */
223
+ this.deletable_ = true;
224
+
225
+ /**
226
+ * @type {boolean}
227
+ * @private
228
+ */
229
+ this.movable_ = true;
230
+
231
+ /**
232
+ * @type {boolean}
233
+ * @private
234
+ */
235
+ this.editable_ = true;
236
+
237
+ /**
238
+ * @type {boolean}
239
+ * @private
240
+ */
241
+ this.isShadow_ = false;
242
+
243
+ /**
244
+ * @type {boolean}
245
+ * @protected
246
+ */
247
+ this.collapsed_ = false;
248
+
249
+ /**
250
+ * @type {?number}
251
+ * @protected
252
+ */
253
+ this.outputShape_ = null;
254
+
255
+ /**
256
+ * A string representing the comment attached to this block.
257
+ * @type {string|Comment}
258
+ * @deprecated August 2019. Use getCommentText instead.
259
+ */
260
+ this.comment = null;
261
+
262
+ /**
263
+ * A model of the comment attached to this block.
264
+ * @type {!Block.CommentModel}
265
+ * @package
266
+ */
267
+ this.commentModel = {text: null, pinned: false, size: new Size(160, 80)};
268
+
269
+ /**
270
+ * The block's position in workspace units. (0, 0) is at the workspace's
271
+ * origin; scale does not change this value.
272
+ * @type {!Coordinate}
273
+ * @private
274
+ */
275
+ this.xy_ = new Coordinate(0, 0);
276
+
277
+ /** @type {!Workspace} */
278
+ this.workspace = workspace;
279
+ /** @type {boolean} */
280
+ this.isInFlyout = workspace.isFlyout;
281
+ /** @type {boolean} */
282
+ this.isInMutator = workspace.isMutator;
283
+
284
+ /** @type {boolean} */
285
+ this.RTL = workspace.RTL;
286
+
287
+ /**
288
+ * True if this block is an insertion marker.
289
+ * @type {boolean}
290
+ * @protected
291
+ */
292
+ this.isInsertionMarker_ = false;
293
+
294
+ /**
295
+ * Name of the type of hat.
296
+ * @type {string|undefined}
297
+ */
298
+ this.hat = undefined;
299
+
300
+ /** @type {?boolean} */
301
+ this.rendered = null;
302
+
303
+ /**
304
+ * String for block help, or function that returns a URL. Null for no help.
305
+ * @type {string|Function}
306
+ */
307
+ this.helpUrl = null;
308
+
309
+ /**
310
+ * A bound callback function to use when the parent workspace changes.
311
+ * @type {?function(Abstract)}
312
+ * @private
313
+ */
314
+ this.onchangeWrapper_ = null;
315
+
316
+ /**
317
+ * A count of statement inputs on the block.
318
+ * @type {number}
319
+ * @package
320
+ */
321
+ this.statementInputCount = 0;
322
+
323
+ // Copy the type-specific functions and data from the prototype.
324
+ if (prototypeName) {
325
+ /** @type {string} */
326
+ this.type = prototypeName;
327
+ const prototype = Blocks[prototypeName];
328
+ if (!prototype || typeof prototype !== 'object') {
329
+ throw TypeError('Invalid block definition for type: ' + prototypeName);
330
+ }
331
+ object.mixin(this, prototype);
332
+ }
333
+
334
+ workspace.addTopBlock(this);
335
+ workspace.addTypedBlock(this);
336
+
337
+ if (new.target === Block) this.doInit_();
338
+ }
108
339
 
109
340
  /**
110
- * @type {Block}
341
+ * Calls the init() function and handles associated event firing, etc.
111
342
  * @protected
112
343
  */
113
- this.parentBlock_ = null;
344
+ doInit_() {
345
+ // All events fired should be part of the same group.
346
+ // Any events fired during init should not be undoable,
347
+ // so that block creation is atomic.
348
+ const existingGroup = eventUtils.getGroup();
349
+ if (!existingGroup) {
350
+ eventUtils.setGroup(true);
351
+ }
352
+ const initialUndoFlag = eventUtils.getRecordUndo();
353
+
354
+ try {
355
+ // Call an initialization function, if it exists.
356
+ if (typeof this.init === 'function') {
357
+ eventUtils.setRecordUndo(false);
358
+ this.init();
359
+ eventUtils.setRecordUndo(initialUndoFlag);
360
+ }
361
+
362
+ // Fire a create event.
363
+ if (eventUtils.isEnabled()) {
364
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(this));
365
+ }
366
+ } finally {
367
+ if (!existingGroup) {
368
+ eventUtils.setGroup(false);
369
+ }
370
+ // In case init threw, recordUndo flag should still be reset.
371
+ eventUtils.setRecordUndo(initialUndoFlag);
372
+ }
373
+
374
+ // Record initial inline state.
375
+ /** @type {boolean|undefined} */
376
+ this.inputsInlineDefault = this.inputsInline;
377
+
378
+ // Bind an onchange function, if it exists.
379
+ if (typeof this.onchange === 'function') {
380
+ this.setOnChange(this.onchange);
381
+ }
382
+ }
114
383
 
115
384
  /**
116
- * @type {!Array<!Block>}
117
- * @protected
385
+ * Dispose of this block.
386
+ * @param {boolean} healStack If true, then try to heal any gap by connecting
387
+ * the next statement with the previous statement. Otherwise, dispose of
388
+ * all children of this block.
389
+ * @suppress {checkTypes}
118
390
  */
119
- this.childBlocks_ = [];
391
+ dispose(healStack) {
392
+ if (!this.workspace) {
393
+ // Already deleted.
394
+ return;
395
+ }
396
+ // Terminate onchange event calls.
397
+ if (this.onchangeWrapper_) {
398
+ this.workspace.removeChangeListener(this.onchangeWrapper_);
399
+ }
400
+
401
+ this.unplug(healStack);
402
+ if (eventUtils.isEnabled()) {
403
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_DELETE))(this));
404
+ }
405
+ eventUtils.disable();
406
+
407
+ try {
408
+ // This block is now at the top of the workspace.
409
+ // Remove this block from the workspace's list of top-most blocks.
410
+ if (this.workspace) {
411
+ this.workspace.removeTopBlock(this);
412
+ this.workspace.removeTypedBlock(this);
413
+ // Remove from block database.
414
+ this.workspace.removeBlockById(this.id);
415
+ this.workspace = null;
416
+ }
417
+
418
+ // Just deleting this block from the DOM would result in a memory leak as
419
+ // well as corruption of the connection database. Therefore we must
420
+ // methodically step through the blocks and carefully disassemble them.
421
+
422
+ if (common.getSelected() === this) {
423
+ common.setSelected(null);
424
+ }
425
+
426
+ // First, dispose of all my children.
427
+ for (let i = this.childBlocks_.length - 1; i >= 0; i--) {
428
+ this.childBlocks_[i].dispose(false);
429
+ }
430
+ // Then dispose of myself.
431
+ // Dispose of all inputs and their fields.
432
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
433
+ input.dispose();
434
+ }
435
+ this.inputList.length = 0;
436
+ // Dispose of any remaining connections (next/previous/output).
437
+ const connections = this.getConnections_(true);
438
+ for (let i = 0, connection; (connection = connections[i]); i++) {
439
+ connection.dispose();
440
+ }
441
+ } finally {
442
+ eventUtils.enable();
443
+ this.disposed = true;
444
+ }
445
+ }
120
446
 
121
447
  /**
122
- * @type {boolean}
123
- * @private
448
+ * Call initModel on all fields on the block.
449
+ * May be called more than once.
450
+ * Either initModel or initSvg must be called after creating a block and
451
+ * before the first interaction with it. Interactions include UI actions
452
+ * (e.g. clicking and dragging) and firing events (e.g. create, delete, and
453
+ * change).
454
+ * @public
124
455
  */
125
- this.deletable_ = true;
456
+ initModel() {
457
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
458
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
459
+ if (field.initModel) {
460
+ field.initModel();
461
+ }
462
+ }
463
+ }
464
+ }
126
465
 
127
466
  /**
128
- * @type {boolean}
129
- * @private
467
+ * Unplug this block from its superior block. If this block is a statement,
468
+ * optionally reconnect the block underneath with the block on top.
469
+ * @param {boolean=} opt_healStack Disconnect child statement and reconnect
470
+ * stack. Defaults to false.
130
471
  */
131
- this.movable_ = true;
472
+ unplug(opt_healStack) {
473
+ if (this.outputConnection) {
474
+ this.unplugFromRow_(opt_healStack);
475
+ }
476
+ if (this.previousConnection) {
477
+ this.unplugFromStack_(opt_healStack);
478
+ }
479
+ }
132
480
 
133
481
  /**
134
- * @type {boolean}
482
+ * Unplug this block's output from an input on another block. Optionally
483
+ * reconnect the block's parent to the only child block, if possible.
484
+ * @param {boolean=} opt_healStack Disconnect right-side block and connect to
485
+ * left-side block. Defaults to false.
135
486
  * @private
136
487
  */
137
- this.editable_ = true;
488
+ unplugFromRow_(opt_healStack) {
489
+ let parentConnection = null;
490
+ if (this.outputConnection.isConnected()) {
491
+ parentConnection = this.outputConnection.targetConnection;
492
+ // Disconnect from any superior block.
493
+ this.outputConnection.disconnect();
494
+ }
495
+
496
+ // Return early in obvious cases.
497
+ if (!parentConnection || !opt_healStack) {
498
+ return;
499
+ }
500
+
501
+ const thisConnection = this.getOnlyValueConnection_();
502
+ if (!thisConnection || !thisConnection.isConnected() ||
503
+ thisConnection.targetBlock().isShadow()) {
504
+ // Too many or too few possible connections on this block, or there's
505
+ // nothing on the other side of this connection.
506
+ return;
507
+ }
508
+
509
+ const childConnection = thisConnection.targetConnection;
510
+ // Disconnect the child block.
511
+ childConnection.disconnect();
512
+ // Connect child to the parent if possible, otherwise bump away.
513
+ if (this.workspace.connectionChecker.canConnect(
514
+ childConnection, parentConnection, false)) {
515
+ parentConnection.connect(childConnection);
516
+ } else {
517
+ childConnection.onFailedConnect(parentConnection);
518
+ }
519
+ }
138
520
 
139
521
  /**
140
- * @type {boolean}
522
+ * Returns the connection on the value input that is connected to another
523
+ * block. When an insertion marker is connected to a connection with a block
524
+ * already attached, the connected block is attached to the insertion marker.
525
+ * Since only one block can be displaced and attached to the insertion marker
526
+ * this should only ever return one connection.
527
+ *
528
+ * @return {?Connection} The connection on the value input, or null.
141
529
  * @private
142
530
  */
143
- this.isShadow_ = false;
531
+ getOnlyValueConnection_() {
532
+ let connection = null;
533
+ for (let i = 0; i < this.inputList.length; i++) {
534
+ const thisConnection = this.inputList[i].connection;
535
+ if (thisConnection &&
536
+ thisConnection.type === ConnectionType.INPUT_VALUE &&
537
+ thisConnection.targetConnection) {
538
+ if (connection) {
539
+ return null; // More than one value input found.
540
+ }
541
+ connection = thisConnection;
542
+ }
543
+ }
544
+ return connection;
545
+ }
144
546
 
145
547
  /**
146
- * @type {boolean}
147
- * @protected
548
+ * Unplug this statement block from its superior block. Optionally reconnect
549
+ * the block underneath with the block on top.
550
+ * @param {boolean=} opt_healStack Disconnect child statement and reconnect
551
+ * stack. Defaults to false.
552
+ * @private
148
553
  */
149
- this.collapsed_ = false;
554
+ unplugFromStack_(opt_healStack) {
555
+ let previousTarget = null;
556
+ if (this.previousConnection.isConnected()) {
557
+ // Remember the connection that any next statements need to connect to.
558
+ previousTarget = this.previousConnection.targetConnection;
559
+ // Detach this block from the parent's tree.
560
+ this.previousConnection.disconnect();
561
+ }
562
+ const nextBlock = this.getNextBlock();
563
+ if (opt_healStack && nextBlock && !nextBlock.isShadow()) {
564
+ // Disconnect the next statement.
565
+ const nextTarget = this.nextConnection.targetConnection;
566
+ nextTarget.disconnect();
567
+ if (previousTarget &&
568
+ this.workspace.connectionChecker.canConnect(
569
+ previousTarget, nextTarget, false)) {
570
+ // Attach the next statement to the previous statement.
571
+ previousTarget.connect(nextTarget);
572
+ }
573
+ }
574
+ }
150
575
 
151
576
  /**
152
- * @type {?number}
153
- * @protected
577
+ * Returns all connections originating from this block.
578
+ * @param {boolean} _all If true, return all connections even hidden ones.
579
+ * @return {!Array<!Connection>} Array of connections.
580
+ * @package
154
581
  */
155
- this.outputShape_ = null;
582
+ getConnections_(_all) {
583
+ const myConnections = [];
584
+ if (this.outputConnection) {
585
+ myConnections.push(this.outputConnection);
586
+ }
587
+ if (this.previousConnection) {
588
+ myConnections.push(this.previousConnection);
589
+ }
590
+ if (this.nextConnection) {
591
+ myConnections.push(this.nextConnection);
592
+ }
593
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
594
+ if (input.connection) {
595
+ myConnections.push(input.connection);
596
+ }
597
+ }
598
+ return myConnections;
599
+ }
156
600
 
157
601
  /**
158
- * A string representing the comment attached to this block.
159
- * @type {string|Comment}
160
- * @deprecated August 2019. Use getCommentText instead.
602
+ * Walks down a stack of blocks and finds the last next connection on the
603
+ * stack.
604
+ * @param {boolean} ignoreShadows If true,the last connection on a non-shadow
605
+ * block will be returned. If false, this will follow shadows to find the
606
+ * last connection.
607
+ * @return {?Connection} The last next connection on the stack, or null.
608
+ * @package
161
609
  */
162
- this.comment = null;
610
+ lastConnectionInStack(ignoreShadows) {
611
+ let nextConnection = this.nextConnection;
612
+ while (nextConnection) {
613
+ const nextBlock = nextConnection.targetBlock();
614
+ if (!nextBlock || (ignoreShadows && nextBlock.isShadow())) {
615
+ return nextConnection;
616
+ }
617
+ nextConnection = nextBlock.nextConnection;
618
+ }
619
+ return null;
620
+ }
163
621
 
164
622
  /**
165
- * A model of the comment attached to this block.
166
- * @type {!Block.CommentModel}
167
- * @package
623
+ * Bump unconnected blocks out of alignment. Two blocks which aren't actually
624
+ * connected should not coincidentally line up on screen.
168
625
  */
169
- this.commentModel = {text: null, pinned: false, size: new Size(160, 80)};
626
+ bumpNeighbours() {
627
+ // noop.
628
+ }
170
629
 
171
630
  /**
172
- * The block's position in workspace units. (0, 0) is at the workspace's
173
- * origin; scale does not change this value.
174
- * @type {!Coordinate}
175
- * @private
631
+ * Return the parent block or null if this block is at the top level. The
632
+ * parent block is either the block connected to the previous connection (for
633
+ * a statement block) or the block connected to the output connection (for a
634
+ * value block).
635
+ * @return {?Block} The block (if any) that holds the current block.
176
636
  */
177
- this.xy_ = new Coordinate(0, 0);
178
-
179
- /** @type {!Workspace} */
180
- this.workspace = workspace;
181
- /** @type {boolean} */
182
- this.isInFlyout = workspace.isFlyout;
183
- /** @type {boolean} */
184
- this.isInMutator = workspace.isMutator;
637
+ getParent() {
638
+ return this.parentBlock_;
639
+ }
185
640
 
186
- /** @type {boolean} */
187
- this.RTL = workspace.RTL;
641
+ /**
642
+ * Return the input that connects to the specified block.
643
+ * @param {!Block} block A block connected to an input on this block.
644
+ * @return {?Input} The input (if any) that connects to the specified
645
+ * block.
646
+ */
647
+ getInputWithBlock(block) {
648
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
649
+ if (input.connection && input.connection.targetBlock() === block) {
650
+ return input;
651
+ }
652
+ }
653
+ return null;
654
+ }
188
655
 
189
656
  /**
190
- * True if this block is an insertion marker.
191
- * @type {boolean}
192
- * @protected
657
+ * Return the parent block that surrounds the current block, or null if this
658
+ * block has no surrounding block. A parent block might just be the previous
659
+ * statement, whereas the surrounding block is an if statement, while loop,
660
+ * etc.
661
+ * @return {?Block} The block (if any) that surrounds the current block.
193
662
  */
194
- this.isInsertionMarker_ = false;
663
+ getSurroundParent() {
664
+ let block = this;
665
+ let prevBlock;
666
+ do {
667
+ prevBlock = block;
668
+ block = block.getParent();
669
+ if (!block) {
670
+ // Ran off the top.
671
+ return null;
672
+ }
673
+ } while (block.getNextBlock() === prevBlock);
674
+ // This block is an enclosing parent, not just a statement in a stack.
675
+ return block;
676
+ }
195
677
 
196
678
  /**
197
- * Name of the type of hat.
198
- * @type {string|undefined}
679
+ * Return the next statement block directly connected to this block.
680
+ * @return {?Block} The next statement block or null.
199
681
  */
200
- this.hat = undefined;
682
+ getNextBlock() {
683
+ return this.nextConnection && this.nextConnection.targetBlock();
684
+ }
201
685
 
202
- /** @type {?boolean} */
203
- this.rendered = null;
686
+ /**
687
+ * Returns the block connected to the previous connection.
688
+ * @return {?Block} The previous statement block or null.
689
+ */
690
+ getPreviousBlock() {
691
+ return this.previousConnection && this.previousConnection.targetBlock();
692
+ }
204
693
 
205
694
  /**
206
- * A count of statement inputs on the block.
207
- * @type {number}
695
+ * Return the connection on the first statement input on this block, or null
696
+ * if there are none.
697
+ * @return {?Connection} The first statement connection or null.
208
698
  * @package
209
699
  */
210
- this.statementInputCount = 0;
211
-
212
- // Copy the type-specific functions and data from the prototype.
213
- if (prototypeName) {
214
- /** @type {string} */
215
- this.type = prototypeName;
216
- const prototype = Blocks[prototypeName];
217
- if (!prototype || typeof prototype !== 'object') {
218
- throw TypeError('Unknown block type: ' + prototypeName);
700
+ getFirstStatementConnection() {
701
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
702
+ if (input.connection &&
703
+ input.connection.type === ConnectionType.NEXT_STATEMENT) {
704
+ return input.connection;
705
+ }
219
706
  }
220
- object.mixin(this, prototype);
707
+ return null;
221
708
  }
222
709
 
223
- workspace.addTopBlock(this);
224
- workspace.addTypedBlock(this);
710
+ /**
711
+ * Return the top-most block in this block's tree.
712
+ * This will return itself if this block is at the top level.
713
+ * @return {!Block} The root block.
714
+ */
715
+ getRootBlock() {
716
+ let rootBlock;
717
+ let block = this;
718
+ do {
719
+ rootBlock = block;
720
+ block = rootBlock.parentBlock_;
721
+ } while (block);
722
+ return rootBlock;
723
+ }
225
724
 
226
- // All events fired should be part of the same group.
227
- // Any events fired during init should not be undoable,
228
- // so that block creation is atomic.
229
- const existingGroup = eventUtils.getGroup();
230
- if (!existingGroup) {
231
- eventUtils.setGroup(true);
725
+ /**
726
+ * Walk up from the given block up through the stack of blocks to find
727
+ * the top block of the sub stack. If we are nested in a statement input only
728
+ * find the top-most nested block. Do not go all the way to the root block.
729
+ * @return {!Block} The top block in a stack.
730
+ * @package
731
+ */
732
+ getTopStackBlock() {
733
+ let block = this;
734
+ let previous;
735
+ do {
736
+ previous = block.getPreviousBlock();
737
+ } while (previous && previous.getNextBlock() === block &&
738
+ (block = previous));
739
+ return block;
232
740
  }
233
- const initialUndoFlag = eventUtils.getRecordUndo();
234
741
 
235
- try {
236
- // Call an initialization function, if it exists.
237
- if (typeof this.init === 'function') {
238
- eventUtils.setRecordUndo(false);
239
- this.init();
240
- eventUtils.setRecordUndo(initialUndoFlag);
742
+ /**
743
+ * Find all the blocks that are directly nested inside this one.
744
+ * Includes value and statement inputs, as well as any following statement.
745
+ * Excludes any connection on an output tab or any preceding statement.
746
+ * Blocks are optionally sorted by position; top to bottom.
747
+ * @param {boolean} ordered Sort the list if true.
748
+ * @return {!Array<!Block>} Array of blocks.
749
+ */
750
+ getChildren(ordered) {
751
+ if (!ordered) {
752
+ return this.childBlocks_;
241
753
  }
242
-
243
- // Fire a create event.
244
- if (eventUtils.isEnabled()) {
245
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(this));
754
+ const blocks = [];
755
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
756
+ if (input.connection) {
757
+ const child = input.connection.targetBlock();
758
+ if (child) {
759
+ blocks.push(child);
760
+ }
761
+ }
246
762
  }
247
- } finally {
248
- if (!existingGroup) {
249
- eventUtils.setGroup(false);
763
+ const next = this.getNextBlock();
764
+ if (next) {
765
+ blocks.push(next);
250
766
  }
251
- // In case init threw, recordUndo flag should still be reset.
252
- eventUtils.setRecordUndo(initialUndoFlag);
253
- }
254
-
255
- // Record initial inline state.
256
- /** @type {boolean|undefined} */
257
- this.inputsInlineDefault = this.inputsInline;
258
-
259
- // Bind an onchange function, if it exists.
260
- if (typeof this.onchange === 'function') {
261
- this.setOnChange(this.onchange);
767
+ return blocks;
262
768
  }
263
- };
264
-
265
- /**
266
- * @typedef {{
267
- * text:?string,
268
- * pinned:boolean,
269
- * size:Size
270
- * }}
271
- */
272
- Block.CommentModel;
273
-
274
- /**
275
- * The language-neutral ID given to the collapsed input.
276
- * @const {string}
277
- */
278
- Block.COLLAPSED_INPUT_NAME = constants.COLLAPSED_INPUT_NAME;
279
-
280
- /**
281
- * The language-neutral ID given to the collapsed field.
282
- * @const {string}
283
- */
284
- Block.COLLAPSED_FIELD_NAME = constants.COLLAPSED_FIELD_NAME;
285
-
286
- /**
287
- * Optional text data that round-trips between blocks and XML.
288
- * Has no effect. May be used by 3rd parties for meta information.
289
- * @type {?string}
290
- */
291
- Block.prototype.data = null;
292
-
293
- /**
294
- * Has this block been disposed of?
295
- * @type {boolean}
296
- * @package
297
- */
298
- Block.prototype.disposed = false;
299
-
300
- /**
301
- * Colour of the block as HSV hue value (0-360)
302
- * This may be null if the block colour was not set via a hue number.
303
- * @type {?number}
304
- * @private
305
- */
306
- Block.prototype.hue_ = null;
307
-
308
- /**
309
- * Colour of the block in '#RRGGBB' format.
310
- * @type {string}
311
- * @protected
312
- */
313
- Block.prototype.colour_ = '#000000';
314
-
315
- /**
316
- * Name of the block style.
317
- * @type {string}
318
- * @protected
319
- */
320
- Block.prototype.styleName_ = '';
321
-
322
- /**
323
- * An optional method called during initialization.
324
- * @type {?function()}
325
- */
326
- Block.prototype.init;
327
-
328
- /**
329
- * An optional callback method to use whenever the block's parent workspace
330
- * changes. This is usually only called from the constructor, the block type
331
- * initializer function, or an extension initializer function.
332
- * @type {?function(Abstract)}
333
- */
334
- Block.prototype.onchange;
335
-
336
- /**
337
- * An optional serialization method for defining how to serialize the
338
- * mutation state to XML. This must be coupled with defining `domToMutation`.
339
- * @type {?function(...):!Element}
340
- */
341
- Block.prototype.mutationToDom;
342
-
343
- /**
344
- * An optional deserialization method for defining how to deserialize the
345
- * mutation state from XML. This must be coupled with defining `mutationToDom`.
346
- * @type {?function(!Element)}
347
- */
348
- Block.prototype.domToMutation;
349
-
350
- /**
351
- * An optional serialization method for defining how to serialize the block's
352
- * extra state (eg mutation state) to something JSON compatible. This must be
353
- * coupled with defining `loadExtraState`.
354
- * @type {?function(): *}
355
- */
356
- Block.prototype.saveExtraState;
357
-
358
- /**
359
- * An optional serialization method for defining how to deserialize the block's
360
- * extra state (eg mutation state) from something JSON compatible. This must be
361
- * coupled with defining `saveExtraState`.
362
- * @type {?function(*)}
363
- */
364
- Block.prototype.loadExtraState;
365
-
366
- /**
367
- * An optional property for suppressing adding STATEMENT_PREFIX and
368
- * STATEMENT_SUFFIX to generated code.
369
- * @type {?boolean}
370
- */
371
- Block.prototype.suppressPrefixSuffix;
372
769
 
373
- /**
374
- * An optional property for declaring developer variables. Return a list of
375
- * variable names for use by generators. Developer variables are never shown to
376
- * the user, but are declared as global variables in the generated code.
377
- * @type {?function():!Array<string>}
378
- */
379
- Block.prototype.getDeveloperVariables;
770
+ /**
771
+ * Set parent of this block to be a new block or null.
772
+ * @param {Block} newParent New parent block.
773
+ * @package
774
+ */
775
+ setParent(newParent) {
776
+ if (newParent === this.parentBlock_) {
777
+ return;
778
+ }
380
779
 
381
- /**
382
- * Dispose of this block.
383
- * @param {boolean} healStack If true, then try to heal any gap by connecting
384
- * the next statement with the previous statement. Otherwise, dispose of
385
- * all children of this block.
386
- * @suppress {checkTypes}
387
- */
388
- Block.prototype.dispose = function(healStack) {
389
- if (!this.workspace) {
390
- // Already deleted.
391
- return;
392
- }
393
- // Terminate onchange event calls.
394
- if (this.onchangeWrapper_) {
395
- this.workspace.removeChangeListener(this.onchangeWrapper_);
396
- }
780
+ // Check that block is connected to new parent if new parent is not null and
781
+ // that block is not connected to superior one if new parent is null.
782
+ const targetBlock =
783
+ (this.previousConnection && this.previousConnection.targetBlock()) ||
784
+ (this.outputConnection && this.outputConnection.targetBlock());
785
+ const isConnected = !!targetBlock;
786
+
787
+ if (isConnected && newParent && targetBlock !== newParent) {
788
+ throw Error('Block connected to superior one that is not new parent.');
789
+ } else if (!isConnected && newParent) {
790
+ throw Error('Block not connected to new parent.');
791
+ } else if (isConnected && !newParent) {
792
+ throw Error(
793
+ 'Cannot set parent to null while block is still connected to' +
794
+ ' superior block.');
795
+ }
397
796
 
398
- this.unplug(healStack);
399
- if (eventUtils.isEnabled()) {
400
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_DELETE))(this));
401
- }
402
- eventUtils.disable();
797
+ if (this.parentBlock_) {
798
+ // Remove this block from the old parent's child list.
799
+ arrayUtils.removeElem(this.parentBlock_.childBlocks_, this);
403
800
 
404
- try {
405
- // This block is now at the top of the workspace.
406
- // Remove this block from the workspace's list of top-most blocks.
407
- if (this.workspace) {
801
+ // This block hasn't actually moved on-screen, so there's no need to
802
+ // update
803
+ // its connection locations.
804
+ } else {
805
+ // New parent must be non-null so remove this block from the workspace's
806
+ // list of top-most blocks.
408
807
  this.workspace.removeTopBlock(this);
409
- this.workspace.removeTypedBlock(this);
410
- // Remove from block database.
411
- this.workspace.removeBlockById(this.id);
412
- this.workspace = null;
413
808
  }
414
809
 
415
- // Just deleting this block from the DOM would result in a memory leak as
416
- // well as corruption of the connection database. Therefore we must
417
- // methodically step through the blocks and carefully disassemble them.
418
-
419
- if (common.getSelected() === this) {
420
- common.setSelected(null);
810
+ this.parentBlock_ = newParent;
811
+ if (newParent) {
812
+ // Add this block to the new parent's child list.
813
+ newParent.childBlocks_.push(this);
814
+ } else {
815
+ this.workspace.addTopBlock(this);
421
816
  }
817
+ }
422
818
 
423
- // First, dispose of all my children.
424
- for (let i = this.childBlocks_.length - 1; i >= 0; i--) {
425
- this.childBlocks_[i].dispose(false);
426
- }
427
- // Then dispose of myself.
428
- // Dispose of all inputs and their fields.
429
- for (let i = 0, input; (input = this.inputList[i]); i++) {
430
- input.dispose();
431
- }
432
- this.inputList.length = 0;
433
- // Dispose of any remaining connections (next/previous/output).
434
- const connections = this.getConnections_(true);
435
- for (let i = 0, connection; (connection = connections[i]); i++) {
436
- connection.dispose();
819
+ /**
820
+ * Find all the blocks that are directly or indirectly nested inside this one.
821
+ * Includes this block in the list.
822
+ * Includes value and statement inputs, as well as any following statements.
823
+ * Excludes any connection on an output tab or any preceding statements.
824
+ * Blocks are optionally sorted by position; top to bottom.
825
+ * @param {boolean} ordered Sort the list if true.
826
+ * @return {!Array<!Block>} Flattened array of blocks.
827
+ */
828
+ getDescendants(ordered) {
829
+ const blocks = [this];
830
+ const childBlocks = this.getChildren(ordered);
831
+ for (let child, i = 0; (child = childBlocks[i]); i++) {
832
+ blocks.push.apply(blocks, child.getDescendants(ordered));
437
833
  }
438
- } finally {
439
- eventUtils.enable();
440
- this.disposed = true;
834
+ return blocks;
441
835
  }
442
- };
443
836
 
444
- /**
445
- * Call initModel on all fields on the block.
446
- * May be called more than once.
447
- * Either initModel or initSvg must be called after creating a block and before
448
- * the first interaction with it. Interactions include UI actions
449
- * (e.g. clicking and dragging) and firing events (e.g. create, delete, and
450
- * change).
451
- * @public
452
- */
453
- Block.prototype.initModel = function() {
454
- for (let i = 0, input; (input = this.inputList[i]); i++) {
455
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
456
- if (field.initModel) {
457
- field.initModel();
458
- }
459
- }
837
+ /**
838
+ * Get whether this block is deletable or not.
839
+ * @return {boolean} True if deletable.
840
+ */
841
+ isDeletable() {
842
+ return this.deletable_ && !this.isShadow_ &&
843
+ !(this.workspace && this.workspace.options.readOnly);
460
844
  }
461
- };
462
845
 
463
- /**
464
- * Unplug this block from its superior block. If this block is a statement,
465
- * optionally reconnect the block underneath with the block on top.
466
- * @param {boolean=} opt_healStack Disconnect child statement and reconnect
467
- * stack. Defaults to false.
468
- */
469
- Block.prototype.unplug = function(opt_healStack) {
470
- if (this.outputConnection) {
471
- this.unplugFromRow_(opt_healStack);
846
+ /**
847
+ * Set whether this block is deletable or not.
848
+ * @param {boolean} deletable True if deletable.
849
+ */
850
+ setDeletable(deletable) {
851
+ this.deletable_ = deletable;
472
852
  }
473
- if (this.previousConnection) {
474
- this.unplugFromStack_(opt_healStack);
853
+
854
+ /**
855
+ * Get whether this block is movable or not.
856
+ * @return {boolean} True if movable.
857
+ */
858
+ isMovable() {
859
+ return this.movable_ && !this.isShadow_ &&
860
+ !(this.workspace && this.workspace.options.readOnly);
475
861
  }
476
- };
477
862
 
478
- /**
479
- * Unplug this block's output from an input on another block. Optionally
480
- * reconnect the block's parent to the only child block, if possible.
481
- * @param {boolean=} opt_healStack Disconnect right-side block and connect to
482
- * left-side block. Defaults to false.
483
- * @private
484
- */
485
- Block.prototype.unplugFromRow_ = function(opt_healStack) {
486
- let parentConnection = null;
487
- if (this.outputConnection.isConnected()) {
488
- parentConnection = this.outputConnection.targetConnection;
489
- // Disconnect from any superior block.
490
- this.outputConnection.disconnect();
863
+ /**
864
+ * Set whether this block is movable or not.
865
+ * @param {boolean} movable True if movable.
866
+ */
867
+ setMovable(movable) {
868
+ this.movable_ = movable;
491
869
  }
492
870
 
493
- // Return early in obvious cases.
494
- if (!parentConnection || !opt_healStack) {
495
- return;
871
+ /**
872
+ * Get whether is block is duplicatable or not. If duplicating this block and
873
+ * descendants will put this block over the workspace's capacity this block is
874
+ * not duplicatable. If duplicating this block and descendants will put any
875
+ * type over their maxInstances this block is not duplicatable.
876
+ * @return {boolean} True if duplicatable.
877
+ */
878
+ isDuplicatable() {
879
+ if (!this.workspace.hasBlockLimits()) {
880
+ return true;
881
+ }
882
+ return this.workspace.isCapacityAvailable(
883
+ common.getBlockTypeCounts(this, true));
496
884
  }
497
885
 
498
- const thisConnection = this.getOnlyValueConnection_();
499
- if (!thisConnection || !thisConnection.isConnected() ||
500
- thisConnection.targetBlock().isShadow()) {
501
- // Too many or too few possible connections on this block, or there's
502
- // nothing on the other side of this connection.
503
- return;
886
+ /**
887
+ * Get whether this block is a shadow block or not.
888
+ * @return {boolean} True if a shadow.
889
+ */
890
+ isShadow() {
891
+ return this.isShadow_;
504
892
  }
505
893
 
506
- const childConnection = thisConnection.targetConnection;
507
- // Disconnect the child block.
508
- childConnection.disconnect();
509
- // Connect child to the parent if possible, otherwise bump away.
510
- if (this.workspace.connectionChecker.canConnect(
511
- childConnection, parentConnection, false)) {
512
- parentConnection.connect(childConnection);
513
- } else {
514
- childConnection.onFailedConnect(parentConnection);
894
+ /**
895
+ * Set whether this block is a shadow block or not.
896
+ * @param {boolean} shadow True if a shadow.
897
+ * @package
898
+ */
899
+ setShadow(shadow) {
900
+ this.isShadow_ = shadow;
515
901
  }
516
- };
517
902
 
518
- /**
519
- * Returns the connection on the value input that is connected to another block.
520
- * When an insertion marker is connected to a connection with a block already
521
- * attached, the connected block is attached to the insertion marker.
522
- * Since only one block can be displaced and attached to the insertion marker
523
- * this should only ever return one connection.
524
- *
525
- * @return {?Connection} The connection on the value input, or null.
526
- * @private
527
- */
528
- Block.prototype.getOnlyValueConnection_ = function() {
529
- let connection = null;
530
- for (let i = 0; i < this.inputList.length; i++) {
531
- const thisConnection = this.inputList[i].connection;
532
- if (thisConnection && thisConnection.type === ConnectionType.INPUT_VALUE &&
533
- thisConnection.targetConnection) {
534
- if (connection) {
535
- return null; // More than one value input found.
536
- }
537
- connection = thisConnection;
538
- }
903
+ /**
904
+ * Get whether this block is an insertion marker block or not.
905
+ * @return {boolean} True if an insertion marker.
906
+ */
907
+ isInsertionMarker() {
908
+ return this.isInsertionMarker_;
539
909
  }
540
- return connection;
541
- };
542
910
 
543
- /**
544
- * Unplug this statement block from its superior block. Optionally reconnect
545
- * the block underneath with the block on top.
546
- * @param {boolean=} opt_healStack Disconnect child statement and reconnect
547
- * stack. Defaults to false.
548
- * @private
549
- */
550
- Block.prototype.unplugFromStack_ = function(opt_healStack) {
551
- let previousTarget = null;
552
- if (this.previousConnection.isConnected()) {
553
- // Remember the connection that any next statements need to connect to.
554
- previousTarget = this.previousConnection.targetConnection;
555
- // Detach this block from the parent's tree.
556
- this.previousConnection.disconnect();
557
- }
558
- const nextBlock = this.getNextBlock();
559
- if (opt_healStack && nextBlock && !nextBlock.isShadow()) {
560
- // Disconnect the next statement.
561
- const nextTarget = this.nextConnection.targetConnection;
562
- nextTarget.disconnect();
563
- if (previousTarget &&
564
- this.workspace.connectionChecker.canConnect(
565
- previousTarget, nextTarget, false)) {
566
- // Attach the next statement to the previous statement.
567
- previousTarget.connect(nextTarget);
568
- }
569
- }
570
- };
911
+ /**
912
+ * Set whether this block is an insertion marker block or not.
913
+ * Once set this cannot be unset.
914
+ * @param {boolean} insertionMarker True if an insertion marker.
915
+ * @package
916
+ */
917
+ setInsertionMarker(insertionMarker) {
918
+ this.isInsertionMarker_ = insertionMarker;
919
+ }
571
920
 
572
- /**
573
- * Returns all connections originating from this block.
574
- * @param {boolean} _all If true, return all connections even hidden ones.
575
- * @return {!Array<!Connection>} Array of connections.
576
- * @package
577
- */
578
- Block.prototype.getConnections_ = function(_all) {
579
- const myConnections = [];
580
- if (this.outputConnection) {
581
- myConnections.push(this.outputConnection);
582
- }
583
- if (this.previousConnection) {
584
- myConnections.push(this.previousConnection);
585
- }
586
- if (this.nextConnection) {
587
- myConnections.push(this.nextConnection);
588
- }
589
- for (let i = 0, input; (input = this.inputList[i]); i++) {
590
- if (input.connection) {
591
- myConnections.push(input.connection);
592
- }
921
+ /**
922
+ * Get whether this block is editable or not.
923
+ * @return {boolean} True if editable.
924
+ */
925
+ isEditable() {
926
+ return this.editable_ &&
927
+ !(this.workspace && this.workspace.options.readOnly);
593
928
  }
594
- return myConnections;
595
- };
596
929
 
597
- /**
598
- * Walks down a stack of blocks and finds the last next connection on the stack.
599
- * @param {boolean} ignoreShadows If true,the last connection on a non-shadow
600
- * block will be returned. If false, this will follow shadows to find the
601
- * last connection.
602
- * @return {?Connection} The last next connection on the stack, or null.
603
- * @package
604
- */
605
- Block.prototype.lastConnectionInStack = function(ignoreShadows) {
606
- let nextConnection = this.nextConnection;
607
- while (nextConnection) {
608
- const nextBlock = nextConnection.targetBlock();
609
- if (!nextBlock || (ignoreShadows && nextBlock.isShadow())) {
610
- return nextConnection;
930
+ /**
931
+ * Set whether this block is editable or not.
932
+ * @param {boolean} editable True if editable.
933
+ */
934
+ setEditable(editable) {
935
+ this.editable_ = editable;
936
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
937
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
938
+ field.updateEditable();
939
+ }
611
940
  }
612
- nextConnection = nextBlock.nextConnection;
613
941
  }
614
- return null;
615
- };
616
-
617
- /**
618
- * Bump unconnected blocks out of alignment. Two blocks which aren't actually
619
- * connected should not coincidentally line up on screen.
620
- */
621
- Block.prototype.bumpNeighbours = function() {
622
- // noop.
623
- };
624
942
 
625
- /**
626
- * Return the parent block or null if this block is at the top level. The parent
627
- * block is either the block connected to the previous connection (for a
628
- * statement block) or the block connected to the output connection (for a value
629
- * block).
630
- * @return {?Block} The block (if any) that holds the current block.
631
- */
632
- Block.prototype.getParent = function() {
633
- return this.parentBlock_;
634
- };
635
-
636
- /**
637
- * Return the input that connects to the specified block.
638
- * @param {!Block} block A block connected to an input on this block.
639
- * @return {?Input} The input (if any) that connects to the specified
640
- * block.
641
- */
642
- Block.prototype.getInputWithBlock = function(block) {
643
- for (let i = 0, input; (input = this.inputList[i]); i++) {
644
- if (input.connection && input.connection.targetBlock() === block) {
645
- return input;
646
- }
943
+ /**
944
+ * Returns if this block has been disposed of / deleted.
945
+ * @return {boolean} True if this block has been disposed of / deleted.
946
+ */
947
+ isDisposed() {
948
+ return this.disposed;
647
949
  }
648
- return null;
649
- };
650
950
 
651
- /**
652
- * Return the parent block that surrounds the current block, or null if this
653
- * block has no surrounding block. A parent block might just be the previous
654
- * statement, whereas the surrounding block is an if statement, while loop, etc.
655
- * @return {?Block} The block (if any) that surrounds the current block.
656
- */
657
- Block.prototype.getSurroundParent = function() {
658
- let block = this;
659
- let prevBlock;
660
- do {
661
- prevBlock = block;
662
- block = block.getParent();
663
- if (!block) {
664
- // Ran off the top.
665
- return null;
666
- }
667
- } while (block.getNextBlock() === prevBlock);
668
- // This block is an enclosing parent, not just a statement in a stack.
669
- return block;
670
- };
671
-
672
- /**
673
- * Return the next statement block directly connected to this block.
674
- * @return {?Block} The next statement block or null.
675
- */
676
- Block.prototype.getNextBlock = function() {
677
- return this.nextConnection && this.nextConnection.targetBlock();
678
- };
679
-
680
- /**
681
- * Returns the block connected to the previous connection.
682
- * @return {?Block} The previous statement block or null.
683
- */
684
- Block.prototype.getPreviousBlock = function() {
685
- return this.previousConnection && this.previousConnection.targetBlock();
686
- };
687
-
688
- /**
689
- * Return the connection on the first statement input on this block, or null if
690
- * there are none.
691
- * @return {?Connection} The first statement connection or null.
692
- * @package
693
- */
694
- Block.prototype.getFirstStatementConnection = function() {
695
- for (let i = 0, input; (input = this.inputList[i]); i++) {
696
- if (input.connection &&
697
- input.connection.type === ConnectionType.NEXT_STATEMENT) {
698
- return input.connection;
951
+ /**
952
+ * Find the connection on this block that corresponds to the given connection
953
+ * on the other block.
954
+ * Used to match connections between a block and its insertion marker.
955
+ * @param {!Block} otherBlock The other block to match against.
956
+ * @param {!Connection} conn The other connection to match.
957
+ * @return {?Connection} The matching connection on this block, or null.
958
+ * @package
959
+ */
960
+ getMatchingConnection(otherBlock, conn) {
961
+ const connections = this.getConnections_(true);
962
+ const otherConnections = otherBlock.getConnections_(true);
963
+ if (connections.length !== otherConnections.length) {
964
+ throw Error('Connection lists did not match in length.');
699
965
  }
700
- }
701
- return null;
702
- };
703
-
704
- /**
705
- * Return the top-most block in this block's tree.
706
- * This will return itself if this block is at the top level.
707
- * @return {!Block} The root block.
708
- */
709
- Block.prototype.getRootBlock = function() {
710
- let rootBlock;
711
- let block = this;
712
- do {
713
- rootBlock = block;
714
- block = rootBlock.parentBlock_;
715
- } while (block);
716
- return rootBlock;
717
- };
718
-
719
- /**
720
- * Walk up from the given block up through the stack of blocks to find
721
- * the top block of the sub stack. If we are nested in a statement input only
722
- * find the top-most nested block. Do not go all the way to the root block.
723
- * @return {!Block} The top block in a stack.
724
- * @package
725
- */
726
- Block.prototype.getTopStackBlock = function() {
727
- let block = this;
728
- let previous;
729
- do {
730
- previous = block.getPreviousBlock();
731
- } while (previous && previous.getNextBlock() === block && (block = previous));
732
- return block;
733
- };
734
-
735
- /**
736
- * Find all the blocks that are directly nested inside this one.
737
- * Includes value and statement inputs, as well as any following statement.
738
- * Excludes any connection on an output tab or any preceding statement.
739
- * Blocks are optionally sorted by position; top to bottom.
740
- * @param {boolean} ordered Sort the list if true.
741
- * @return {!Array<!Block>} Array of blocks.
742
- */
743
- Block.prototype.getChildren = function(ordered) {
744
- if (!ordered) {
745
- return this.childBlocks_;
746
- }
747
- const blocks = [];
748
- for (let i = 0, input; (input = this.inputList[i]); i++) {
749
- if (input.connection) {
750
- const child = input.connection.targetBlock();
751
- if (child) {
752
- blocks.push(child);
966
+ for (let i = 0; i < otherConnections.length; i++) {
967
+ if (otherConnections[i] === conn) {
968
+ return connections[i];
753
969
  }
754
970
  }
971
+ return null;
755
972
  }
756
- const next = this.getNextBlock();
757
- if (next) {
758
- blocks.push(next);
759
- }
760
- return blocks;
761
- };
762
973
 
763
- /**
764
- * Set parent of this block to be a new block or null.
765
- * @param {Block} newParent New parent block.
766
- * @package
767
- */
768
- Block.prototype.setParent = function(newParent) {
769
- if (newParent === this.parentBlock_) {
770
- return;
974
+ /**
975
+ * Set the URL of this block's help page.
976
+ * @param {string|Function} url URL string for block help, or function that
977
+ * returns a URL. Null for no help.
978
+ */
979
+ setHelpUrl(url) {
980
+ this.helpUrl = url;
771
981
  }
772
982
 
773
- // Check that block is connected to new parent if new parent is not null and
774
- // that block is not connected to superior one if new parent is null.
775
- const targetBlock =
776
- (this.previousConnection && this.previousConnection.targetBlock()) ||
777
- (this.outputConnection && this.outputConnection.targetBlock());
778
- const isConnected = !!targetBlock;
779
-
780
- if (isConnected && newParent && targetBlock !== newParent) {
781
- throw Error('Block connected to superior one that is not new parent.');
782
- } else if (!isConnected && newParent) {
783
- throw Error('Block not connected to new parent.');
784
- } else if (isConnected && !newParent) {
785
- throw Error(
786
- 'Cannot set parent to null while block is still connected to' +
787
- ' superior block.');
983
+ /**
984
+ * Sets the tooltip for this block.
985
+ * @param {!Tooltip.TipInfo} newTip The text for the tooltip, a function
986
+ * that returns the text for the tooltip, or a parent object whose tooltip
987
+ * will be used. To not display a tooltip pass the empty string.
988
+ */
989
+ setTooltip(newTip) {
990
+ this.tooltip = newTip;
788
991
  }
789
992
 
790
- if (this.parentBlock_) {
791
- // Remove this block from the old parent's child list.
792
- arrayUtils.removeElem(this.parentBlock_.childBlocks_, this);
793
-
794
- // This block hasn't actually moved on-screen, so there's no need to update
795
- // its connection locations.
796
- } else {
797
- // New parent must be non-null so remove this block from the workspace's
798
- // list of top-most blocks.
799
- this.workspace.removeTopBlock(this);
993
+ /**
994
+ * Returns the tooltip text for this block.
995
+ * @return {!string} The tooltip text for this block.
996
+ */
997
+ getTooltip() {
998
+ return Tooltip.getTooltipOfObject(this);
800
999
  }
801
1000
 
802
- this.parentBlock_ = newParent;
803
- if (newParent) {
804
- // Add this block to the new parent's child list.
805
- newParent.childBlocks_.push(this);
806
- } else {
807
- this.workspace.addTopBlock(this);
1001
+ /**
1002
+ * Get the colour of a block.
1003
+ * @return {string} #RRGGBB string.
1004
+ */
1005
+ getColour() {
1006
+ return this.colour_;
808
1007
  }
809
- };
810
1008
 
811
- /**
812
- * Find all the blocks that are directly or indirectly nested inside this one.
813
- * Includes this block in the list.
814
- * Includes value and statement inputs, as well as any following statements.
815
- * Excludes any connection on an output tab or any preceding statements.
816
- * Blocks are optionally sorted by position; top to bottom.
817
- * @param {boolean} ordered Sort the list if true.
818
- * @return {!Array<!Block>} Flattened array of blocks.
819
- */
820
- Block.prototype.getDescendants = function(ordered) {
821
- const blocks = [this];
822
- const childBlocks = this.getChildren(ordered);
823
- for (let child, i = 0; (child = childBlocks[i]); i++) {
824
- blocks.push.apply(blocks, child.getDescendants(ordered));
1009
+ /**
1010
+ * Get the name of the block style.
1011
+ * @return {string} Name of the block style.
1012
+ */
1013
+ getStyleName() {
1014
+ return this.styleName_;
825
1015
  }
826
- return blocks;
827
- };
828
1016
 
829
- /**
830
- * Get whether this block is deletable or not.
831
- * @return {boolean} True if deletable.
832
- */
833
- Block.prototype.isDeletable = function() {
834
- return this.deletable_ && !this.isShadow_ &&
835
- !(this.workspace && this.workspace.options.readOnly);
836
- };
837
-
838
- /**
839
- * Set whether this block is deletable or not.
840
- * @param {boolean} deletable True if deletable.
841
- */
842
- Block.prototype.setDeletable = function(deletable) {
843
- this.deletable_ = deletable;
844
- };
845
-
846
- /**
847
- * Get whether this block is movable or not.
848
- * @return {boolean} True if movable.
849
- */
850
- Block.prototype.isMovable = function() {
851
- return this.movable_ && !this.isShadow_ &&
852
- !(this.workspace && this.workspace.options.readOnly);
853
- };
854
-
855
- /**
856
- * Set whether this block is movable or not.
857
- * @param {boolean} movable True if movable.
858
- */
859
- Block.prototype.setMovable = function(movable) {
860
- this.movable_ = movable;
861
- };
862
-
863
- /**
864
- * Get whether is block is duplicatable or not. If duplicating this block and
865
- * descendants will put this block over the workspace's capacity this block is
866
- * not duplicatable. If duplicating this block and descendants will put any
867
- * type over their maxInstances this block is not duplicatable.
868
- * @return {boolean} True if duplicatable.
869
- */
870
- Block.prototype.isDuplicatable = function() {
871
- if (!this.workspace.hasBlockLimits()) {
872
- return true;
1017
+ /**
1018
+ * Get the HSV hue value of a block. Null if hue not set.
1019
+ * @return {?number} Hue value (0-360).
1020
+ */
1021
+ getHue() {
1022
+ return this.hue_;
873
1023
  }
874
- return this.workspace.isCapacityAvailable(
875
- common.getBlockTypeCounts(this, true));
876
- };
877
1024
 
878
- /**
879
- * Get whether this block is a shadow block or not.
880
- * @return {boolean} True if a shadow.
881
- */
882
- Block.prototype.isShadow = function() {
883
- return this.isShadow_;
884
- };
885
-
886
- /**
887
- * Set whether this block is a shadow block or not.
888
- * @param {boolean} shadow True if a shadow.
889
- * @package
890
- */
891
- Block.prototype.setShadow = function(shadow) {
892
- this.isShadow_ = shadow;
893
- };
894
-
895
- /**
896
- * Get whether this block is an insertion marker block or not.
897
- * @return {boolean} True if an insertion marker.
898
- */
899
- Block.prototype.isInsertionMarker = function() {
900
- return this.isInsertionMarker_;
901
- };
902
-
903
- /**
904
- * Set whether this block is an insertion marker block or not.
905
- * Once set this cannot be unset.
906
- * @param {boolean} insertionMarker True if an insertion marker.
907
- * @package
908
- */
909
- Block.prototype.setInsertionMarker = function(insertionMarker) {
910
- this.isInsertionMarker_ = insertionMarker;
911
- };
1025
+ /**
1026
+ * Change the colour of a block.
1027
+ * @param {number|string} colour HSV hue value (0 to 360), #RRGGBB string,
1028
+ * or a message reference string pointing to one of those two values.
1029
+ */
1030
+ setColour(colour) {
1031
+ const parsed = parsing.parseBlockColour(colour);
1032
+ this.hue_ = parsed.hue;
1033
+ this.colour_ = parsed.hex;
1034
+ }
912
1035
 
913
- /**
914
- * Get whether this block is editable or not.
915
- * @return {boolean} True if editable.
916
- */
917
- Block.prototype.isEditable = function() {
918
- return this.editable_ && !(this.workspace && this.workspace.options.readOnly);
919
- };
1036
+ /**
1037
+ * Set the style and colour values of a block.
1038
+ * @param {string} blockStyleName Name of the block style.
1039
+ */
1040
+ setStyle(blockStyleName) {
1041
+ this.styleName_ = blockStyleName;
1042
+ }
920
1043
 
921
- /**
922
- * Set whether this block is editable or not.
923
- * @param {boolean} editable True if editable.
924
- */
925
- Block.prototype.setEditable = function(editable) {
926
- this.editable_ = editable;
927
- for (let i = 0, input; (input = this.inputList[i]); i++) {
928
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
929
- field.updateEditable();
1044
+ /**
1045
+ * Sets a callback function to use whenever the block's parent workspace
1046
+ * changes, replacing any prior onchange handler. This is usually only called
1047
+ * from the constructor, the block type initializer function, or an extension
1048
+ * initializer function.
1049
+ * @param {function(Abstract)} onchangeFn The callback to call
1050
+ * when the block's workspace changes.
1051
+ * @throws {Error} if onchangeFn is not falsey and not a function.
1052
+ */
1053
+ setOnChange(onchangeFn) {
1054
+ if (onchangeFn && typeof onchangeFn !== 'function') {
1055
+ throw Error('onchange must be a function.');
1056
+ }
1057
+ if (this.onchangeWrapper_) {
1058
+ this.workspace.removeChangeListener(this.onchangeWrapper_);
1059
+ }
1060
+ this.onchange = onchangeFn;
1061
+ if (this.onchange) {
1062
+ this.onchangeWrapper_ = onchangeFn.bind(this);
1063
+ this.workspace.addChangeListener(this.onchangeWrapper_);
930
1064
  }
931
1065
  }
932
- };
933
-
934
- /**
935
- * Returns if this block has been disposed of / deleted.
936
- * @return {boolean} True if this block has been disposed of / deleted.
937
- */
938
- Block.prototype.isDisposed = function() {
939
- return this.disposed;
940
- };
941
1066
 
942
- /**
943
- * Find the connection on this block that corresponds to the given connection
944
- * on the other block.
945
- * Used to match connections between a block and its insertion marker.
946
- * @param {!Block} otherBlock The other block to match against.
947
- * @param {!Connection} conn The other connection to match.
948
- * @return {?Connection} The matching connection on this block, or null.
949
- * @package
950
- */
951
- Block.prototype.getMatchingConnection = function(otherBlock, conn) {
952
- const connections = this.getConnections_(true);
953
- const otherConnections = otherBlock.getConnections_(true);
954
- if (connections.length !== otherConnections.length) {
955
- throw Error('Connection lists did not match in length.');
956
- }
957
- for (let i = 0; i < otherConnections.length; i++) {
958
- if (otherConnections[i] === conn) {
959
- return connections[i];
1067
+ /**
1068
+ * Returns the named field from a block.
1069
+ * @param {string} name The name of the field.
1070
+ * @return {?Field} Named field, or null if field does not exist.
1071
+ */
1072
+ getField(name) {
1073
+ if (typeof name !== 'string') {
1074
+ throw TypeError(
1075
+ 'Block.prototype.getField expects a string ' +
1076
+ 'with the field name but received ' +
1077
+ (name === undefined ? 'nothing' : name + ' of type ' + typeof name) +
1078
+ ' instead');
960
1079
  }
1080
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1081
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1082
+ if (field.name === name) {
1083
+ return field;
1084
+ }
1085
+ }
1086
+ }
1087
+ return null;
961
1088
  }
962
- return null;
963
- };
964
1089
 
965
- /**
966
- * Set the URL of this block's help page.
967
- * @param {string|Function} url URL string for block help, or function that
968
- * returns a URL. Null for no help.
969
- */
970
- Block.prototype.setHelpUrl = function(url) {
971
- this.helpUrl = url;
972
- };
973
-
974
- /**
975
- * Sets the tooltip for this block.
976
- * @param {!Tooltip.TipInfo} newTip The text for the tooltip, a function
977
- * that returns the text for the tooltip, or a parent object whose tooltip
978
- * will be used. To not display a tooltip pass the empty string.
979
- */
980
- Block.prototype.setTooltip = function(newTip) {
981
- this.tooltip = newTip;
982
- };
983
-
984
- /**
985
- * Returns the tooltip text for this block.
986
- * @return {!string} The tooltip text for this block.
987
- */
988
- Block.prototype.getTooltip = function() {
989
- return Tooltip.getTooltipOfObject(this);
990
- };
991
-
992
- /**
993
- * Get the colour of a block.
994
- * @return {string} #RRGGBB string.
995
- */
996
- Block.prototype.getColour = function() {
997
- return this.colour_;
998
- };
999
-
1000
- /**
1001
- * Get the name of the block style.
1002
- * @return {string} Name of the block style.
1003
- */
1004
- Block.prototype.getStyleName = function() {
1005
- return this.styleName_;
1006
- };
1007
-
1008
- /**
1009
- * Get the HSV hue value of a block. Null if hue not set.
1010
- * @return {?number} Hue value (0-360).
1011
- */
1012
- Block.prototype.getHue = function() {
1013
- return this.hue_;
1014
- };
1090
+ /**
1091
+ * Return all variables referenced by this block.
1092
+ * @return {!Array<string>} List of variable ids.
1093
+ */
1094
+ getVars() {
1095
+ const vars = [];
1096
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1097
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1098
+ if (field.referencesVariables()) {
1099
+ vars.push(field.getValue());
1100
+ }
1101
+ }
1102
+ }
1103
+ return vars;
1104
+ }
1015
1105
 
1016
- /**
1017
- * Change the colour of a block.
1018
- * @param {number|string} colour HSV hue value (0 to 360), #RRGGBB string,
1019
- * or a message reference string pointing to one of those two values.
1020
- */
1021
- Block.prototype.setColour = function(colour) {
1022
- const parsed = parsing.parseBlockColour(colour);
1023
- this.hue_ = parsed.hue;
1024
- this.colour_ = parsed.hex;
1025
- };
1106
+ /**
1107
+ * Return all variables referenced by this block.
1108
+ * @return {!Array<!VariableModel>} List of variable models.
1109
+ * @package
1110
+ */
1111
+ getVarModels() {
1112
+ const vars = [];
1113
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1114
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1115
+ if (field.referencesVariables()) {
1116
+ const model = this.workspace.getVariableById(
1117
+ /** @type {string} */ (field.getValue()));
1118
+ // Check if the variable actually exists (and isn't just a potential
1119
+ // variable).
1120
+ if (model) {
1121
+ vars.push(model);
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ return vars;
1127
+ }
1026
1128
 
1027
- /**
1028
- * Set the style and colour values of a block.
1029
- * @param {string} blockStyleName Name of the block style.
1030
- */
1031
- Block.prototype.setStyle = function(blockStyleName) {
1032
- this.styleName_ = blockStyleName;
1033
- };
1129
+ /**
1130
+ * Notification that a variable is renaming but keeping the same ID. If the
1131
+ * variable is in use on this block, rerender to show the new name.
1132
+ * @param {!VariableModel} variable The variable being renamed.
1133
+ * @package
1134
+ */
1135
+ updateVarName(variable) {
1136
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1137
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1138
+ if (field.referencesVariables() &&
1139
+ variable.getId() === field.getValue()) {
1140
+ field.refreshVariableName();
1141
+ }
1142
+ }
1143
+ }
1144
+ }
1034
1145
 
1035
- /**
1036
- * Sets a callback function to use whenever the block's parent workspace
1037
- * changes, replacing any prior onchange handler. This is usually only called
1038
- * from the constructor, the block type initializer function, or an extension
1039
- * initializer function.
1040
- * @param {function(Abstract)} onchangeFn The callback to call
1041
- * when the block's workspace changes.
1042
- * @throws {Error} if onchangeFn is not falsey and not a function.
1043
- */
1044
- Block.prototype.setOnChange = function(onchangeFn) {
1045
- if (onchangeFn && typeof onchangeFn !== 'function') {
1046
- throw Error('onchange must be a function.');
1146
+ /**
1147
+ * Notification that a variable is renaming.
1148
+ * If the ID matches one of this block's variables, rename it.
1149
+ * @param {string} oldId ID of variable to rename.
1150
+ * @param {string} newId ID of new variable. May be the same as oldId, but
1151
+ * with an updated name.
1152
+ */
1153
+ renameVarById(oldId, newId) {
1154
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1155
+ for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1156
+ if (field.referencesVariables() && oldId === field.getValue()) {
1157
+ field.setValue(newId);
1158
+ }
1159
+ }
1160
+ }
1047
1161
  }
1048
- if (this.onchangeWrapper_) {
1049
- this.workspace.removeChangeListener(this.onchangeWrapper_);
1162
+
1163
+ /**
1164
+ * Returns the language-neutral value of the given field.
1165
+ * @param {string} name The name of the field.
1166
+ * @return {*} Value of the field or null if field does not exist.
1167
+ */
1168
+ getFieldValue(name) {
1169
+ const field = this.getField(name);
1170
+ if (field) {
1171
+ return field.getValue();
1172
+ }
1173
+ return null;
1050
1174
  }
1051
- this.onchange = onchangeFn;
1052
- if (this.onchange) {
1053
- this.onchangeWrapper_ = onchangeFn.bind(this);
1054
- this.workspace.addChangeListener(this.onchangeWrapper_);
1175
+
1176
+ /**
1177
+ * Sets the value of the given field for this block.
1178
+ * @param {*} newValue The value to set.
1179
+ * @param {string} name The name of the field to set the value of.
1180
+ */
1181
+ setFieldValue(newValue, name) {
1182
+ const field = this.getField(name);
1183
+ if (!field) {
1184
+ throw Error('Field "' + name + '" not found.');
1185
+ }
1186
+ field.setValue(newValue);
1055
1187
  }
1056
- };
1057
1188
 
1058
- /**
1059
- * Returns the named field from a block.
1060
- * @param {string} name The name of the field.
1061
- * @return {?Field} Named field, or null if field does not exist.
1062
- */
1063
- Block.prototype.getField = function(name) {
1064
- if (typeof name !== 'string') {
1065
- throw TypeError(
1066
- 'Block.prototype.getField expects a string ' +
1067
- 'with the field name but received ' +
1068
- (name === undefined ? 'nothing' : name + ' of type ' + typeof name) +
1069
- ' instead');
1070
- }
1071
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1072
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1073
- if (field.name === name) {
1074
- return field;
1189
+ /**
1190
+ * Set whether this block can chain onto the bottom of another block.
1191
+ * @param {boolean} newBoolean True if there can be a previous statement.
1192
+ * @param {(string|Array<string>|null)=} opt_check Statement type or
1193
+ * list of statement types. Null/undefined if any type could be
1194
+ * connected.
1195
+ */
1196
+ setPreviousStatement(newBoolean, opt_check) {
1197
+ if (newBoolean) {
1198
+ if (opt_check === undefined) {
1199
+ opt_check = null;
1200
+ }
1201
+ if (!this.previousConnection) {
1202
+ this.previousConnection =
1203
+ this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT);
1204
+ }
1205
+ this.previousConnection.setCheck(opt_check);
1206
+ } else {
1207
+ if (this.previousConnection) {
1208
+ if (this.previousConnection.isConnected()) {
1209
+ throw Error(
1210
+ 'Must disconnect previous statement before removing ' +
1211
+ 'connection.');
1212
+ }
1213
+ this.previousConnection.dispose();
1214
+ this.previousConnection = null;
1075
1215
  }
1076
1216
  }
1077
1217
  }
1078
- return null;
1079
- };
1080
1218
 
1081
- /**
1082
- * Return all variables referenced by this block.
1083
- * @return {!Array<string>} List of variable ids.
1084
- */
1085
- Block.prototype.getVars = function() {
1086
- const vars = [];
1087
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1088
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1089
- if (field.referencesVariables()) {
1090
- vars.push(field.getValue());
1219
+ /**
1220
+ * Set whether another block can chain onto the bottom of this block.
1221
+ * @param {boolean} newBoolean True if there can be a next statement.
1222
+ * @param {(string|Array<string>|null)=} opt_check Statement type or
1223
+ * list of statement types. Null/undefined if any type could be
1224
+ * connected.
1225
+ */
1226
+ setNextStatement(newBoolean, opt_check) {
1227
+ if (newBoolean) {
1228
+ if (opt_check === undefined) {
1229
+ opt_check = null;
1230
+ }
1231
+ if (!this.nextConnection) {
1232
+ this.nextConnection =
1233
+ this.makeConnection_(ConnectionType.NEXT_STATEMENT);
1234
+ }
1235
+ this.nextConnection.setCheck(opt_check);
1236
+ } else {
1237
+ if (this.nextConnection) {
1238
+ if (this.nextConnection.isConnected()) {
1239
+ throw Error(
1240
+ 'Must disconnect next statement before removing ' +
1241
+ 'connection.');
1242
+ }
1243
+ this.nextConnection.dispose();
1244
+ this.nextConnection = null;
1091
1245
  }
1092
1246
  }
1093
1247
  }
1094
- return vars;
1095
- };
1096
1248
 
1097
- /**
1098
- * Return all variables referenced by this block.
1099
- * @return {!Array<!VariableModel>} List of variable models.
1100
- * @package
1101
- */
1102
- Block.prototype.getVarModels = function() {
1103
- const vars = [];
1104
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1105
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1106
- if (field.referencesVariables()) {
1107
- const model = this.workspace.getVariableById(
1108
- /** @type {string} */ (field.getValue()));
1109
- // Check if the variable actually exists (and isn't just a potential
1110
- // variable).
1111
- if (model) {
1112
- vars.push(model);
1249
+ /**
1250
+ * Set whether this block returns a value.
1251
+ * @param {boolean} newBoolean True if there is an output.
1252
+ * @param {(string|Array<string>|null)=} opt_check Returned type or list
1253
+ * of returned types. Null or undefined if any type could be returned
1254
+ * (e.g. variable get).
1255
+ */
1256
+ setOutput(newBoolean, opt_check) {
1257
+ if (newBoolean) {
1258
+ if (opt_check === undefined) {
1259
+ opt_check = null;
1260
+ }
1261
+ if (!this.outputConnection) {
1262
+ this.outputConnection =
1263
+ this.makeConnection_(ConnectionType.OUTPUT_VALUE);
1264
+ }
1265
+ this.outputConnection.setCheck(opt_check);
1266
+ } else {
1267
+ if (this.outputConnection) {
1268
+ if (this.outputConnection.isConnected()) {
1269
+ throw Error(
1270
+ 'Must disconnect output value before removing connection.');
1113
1271
  }
1272
+ this.outputConnection.dispose();
1273
+ this.outputConnection = null;
1114
1274
  }
1115
1275
  }
1116
1276
  }
1117
- return vars;
1118
- };
1119
1277
 
1120
- /**
1121
- * Notification that a variable is renaming but keeping the same ID. If the
1122
- * variable is in use on this block, rerender to show the new name.
1123
- * @param {!VariableModel} variable The variable being renamed.
1124
- * @package
1125
- */
1126
- Block.prototype.updateVarName = function(variable) {
1127
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1128
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1129
- if (field.referencesVariables() &&
1130
- variable.getId() === field.getValue()) {
1131
- field.refreshVariableName();
1132
- }
1278
+ /**
1279
+ * Set whether value inputs are arranged horizontally or vertically.
1280
+ * @param {boolean} newBoolean True if inputs are horizontal.
1281
+ */
1282
+ setInputsInline(newBoolean) {
1283
+ if (this.inputsInline !== newBoolean) {
1284
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1285
+ this, 'inline', null, this.inputsInline, newBoolean));
1286
+ this.inputsInline = newBoolean;
1133
1287
  }
1134
1288
  }
1135
- };
1136
1289
 
1137
- /**
1138
- * Notification that a variable is renaming.
1139
- * If the ID matches one of this block's variables, rename it.
1140
- * @param {string} oldId ID of variable to rename.
1141
- * @param {string} newId ID of new variable. May be the same as oldId, but with
1142
- * an updated name.
1143
- */
1144
- Block.prototype.renameVarById = function(oldId, newId) {
1145
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1146
- for (let j = 0, field; (field = input.fieldRow[j]); j++) {
1147
- if (field.referencesVariables() && oldId === field.getValue()) {
1148
- field.setValue(newId);
1290
+ /**
1291
+ * Get whether value inputs are arranged horizontally or vertically.
1292
+ * @return {boolean} True if inputs are horizontal.
1293
+ */
1294
+ getInputsInline() {
1295
+ if (this.inputsInline !== undefined) {
1296
+ // Set explicitly.
1297
+ return this.inputsInline;
1298
+ }
1299
+ // Not defined explicitly. Figure out what would look best.
1300
+ for (let i = 1; i < this.inputList.length; i++) {
1301
+ if (this.inputList[i - 1].type === inputTypes.DUMMY &&
1302
+ this.inputList[i].type === inputTypes.DUMMY) {
1303
+ // Two dummy inputs in a row. Don't inline them.
1304
+ return false;
1305
+ }
1306
+ }
1307
+ for (let i = 1; i < this.inputList.length; i++) {
1308
+ if (this.inputList[i - 1].type === inputTypes.VALUE &&
1309
+ this.inputList[i].type === inputTypes.DUMMY) {
1310
+ // Dummy input after a value input. Inline them.
1311
+ return true;
1149
1312
  }
1150
1313
  }
1314
+ return false;
1151
1315
  }
1152
- };
1153
1316
 
1154
- /**
1155
- * Returns the language-neutral value of the given field.
1156
- * @param {string} name The name of the field.
1157
- * @return {*} Value of the field or null if field does not exist.
1158
- */
1159
- Block.prototype.getFieldValue = function(name) {
1160
- const field = this.getField(name);
1161
- if (field) {
1162
- return field.getValue();
1317
+ /**
1318
+ * Set the block's output shape.
1319
+ * @param {?number} outputShape Value representing an output shape.
1320
+ */
1321
+ setOutputShape(outputShape) {
1322
+ this.outputShape_ = outputShape;
1163
1323
  }
1164
- return null;
1165
- };
1166
1324
 
1167
- /**
1168
- * Sets the value of the given field for this block.
1169
- * @param {*} newValue The value to set.
1170
- * @param {string} name The name of the field to set the value of.
1171
- */
1172
- Block.prototype.setFieldValue = function(newValue, name) {
1173
- const field = this.getField(name);
1174
- if (!field) {
1175
- throw Error('Field "' + name + '" not found.');
1325
+ /**
1326
+ * Get the block's output shape.
1327
+ * @return {?number} Value representing output shape if one exists.
1328
+ */
1329
+ getOutputShape() {
1330
+ return this.outputShape_;
1176
1331
  }
1177
- field.setValue(newValue);
1178
- };
1179
1332
 
1180
- /**
1181
- * Set whether this block can chain onto the bottom of another block.
1182
- * @param {boolean} newBoolean True if there can be a previous statement.
1183
- * @param {(string|Array<string>|null)=} opt_check Statement type or
1184
- * list of statement types. Null/undefined if any type could be connected.
1185
- */
1186
- Block.prototype.setPreviousStatement = function(newBoolean, opt_check) {
1187
- if (newBoolean) {
1188
- if (opt_check === undefined) {
1189
- opt_check = null;
1190
- }
1191
- if (!this.previousConnection) {
1192
- this.previousConnection =
1193
- this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT);
1333
+ /**
1334
+ * Get whether this block is enabled or not.
1335
+ * @return {boolean} True if enabled.
1336
+ */
1337
+ isEnabled() {
1338
+ return !this.disabled;
1339
+ }
1340
+
1341
+ /**
1342
+ * Set whether the block is enabled or not.
1343
+ * @param {boolean} enabled True if enabled.
1344
+ */
1345
+ setEnabled(enabled) {
1346
+ if (this.isEnabled() !== enabled) {
1347
+ const oldValue = this.disabled;
1348
+ this.disabled = !enabled;
1349
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1350
+ this, 'disabled', null, oldValue, !enabled));
1194
1351
  }
1195
- this.previousConnection.setCheck(opt_check);
1196
- } else {
1197
- if (this.previousConnection) {
1198
- if (this.previousConnection.isConnected()) {
1199
- throw Error(
1200
- 'Must disconnect previous statement before removing ' +
1201
- 'connection.');
1352
+ }
1353
+
1354
+ /**
1355
+ * Get whether the block is disabled or not due to parents.
1356
+ * The block's own disabled property is not considered.
1357
+ * @return {boolean} True if disabled.
1358
+ */
1359
+ getInheritedDisabled() {
1360
+ let ancestor = this.getSurroundParent();
1361
+ while (ancestor) {
1362
+ if (ancestor.disabled) {
1363
+ return true;
1202
1364
  }
1203
- this.previousConnection.dispose();
1204
- this.previousConnection = null;
1365
+ ancestor = ancestor.getSurroundParent();
1205
1366
  }
1367
+ // Ran off the top.
1368
+ return false;
1206
1369
  }
1207
- };
1208
1370
 
1209
- /**
1210
- * Set whether another block can chain onto the bottom of this block.
1211
- * @param {boolean} newBoolean True if there can be a next statement.
1212
- * @param {(string|Array<string>|null)=} opt_check Statement type or
1213
- * list of statement types. Null/undefined if any type could be connected.
1214
- */
1215
- Block.prototype.setNextStatement = function(newBoolean, opt_check) {
1216
- if (newBoolean) {
1217
- if (opt_check === undefined) {
1218
- opt_check = null;
1371
+ /**
1372
+ * Get whether the block is collapsed or not.
1373
+ * @return {boolean} True if collapsed.
1374
+ */
1375
+ isCollapsed() {
1376
+ return this.collapsed_;
1377
+ }
1378
+
1379
+ /**
1380
+ * Set whether the block is collapsed or not.
1381
+ * @param {boolean} collapsed True if collapsed.
1382
+ */
1383
+ setCollapsed(collapsed) {
1384
+ if (this.collapsed_ !== collapsed) {
1385
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1386
+ this, 'collapsed', null, this.collapsed_, collapsed));
1387
+ this.collapsed_ = collapsed;
1219
1388
  }
1220
- if (!this.nextConnection) {
1221
- this.nextConnection = this.makeConnection_(ConnectionType.NEXT_STATEMENT);
1389
+ }
1390
+
1391
+ /**
1392
+ * Create a human-readable text representation of this block and any children.
1393
+ * @param {number=} opt_maxLength Truncate the string to this length.
1394
+ * @param {string=} opt_emptyToken The placeholder string used to denote an
1395
+ * empty field. If not specified, '?' is used.
1396
+ * @return {string} Text of block.
1397
+ */
1398
+ toString(opt_maxLength, opt_emptyToken) {
1399
+ let text = [];
1400
+ const emptyFieldPlaceholder = opt_emptyToken || '?';
1401
+
1402
+ // Temporarily set flag to navigate to all fields.
1403
+ const prevNavigateFields = ASTNode.NAVIGATE_ALL_FIELDS;
1404
+ ASTNode.NAVIGATE_ALL_FIELDS = true;
1405
+
1406
+ let node = ASTNode.createBlockNode(this);
1407
+ const rootNode = node;
1408
+
1409
+ /**
1410
+ * Whether or not to add parentheses around an input.
1411
+ * @param {!Connection} connection The connection.
1412
+ * @return {boolean} True if we should add parentheses around the input.
1413
+ */
1414
+ function shouldAddParentheses(connection) {
1415
+ let checks = connection.getCheck();
1416
+ if (!checks && connection.targetConnection) {
1417
+ checks = connection.targetConnection.getCheck();
1418
+ }
1419
+ return !!checks &&
1420
+ (checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1);
1222
1421
  }
1223
- this.nextConnection.setCheck(opt_check);
1224
- } else {
1225
- if (this.nextConnection) {
1226
- if (this.nextConnection.isConnected()) {
1227
- throw Error(
1228
- 'Must disconnect next statement before removing ' +
1229
- 'connection.');
1422
+
1423
+ /**
1424
+ * Check that we haven't circled back to the original root node.
1425
+ */
1426
+ function checkRoot() {
1427
+ if (node && node.getType() === rootNode.getType() &&
1428
+ node.getLocation() === rootNode.getLocation()) {
1429
+ node = null;
1230
1430
  }
1231
- this.nextConnection.dispose();
1232
- this.nextConnection = null;
1233
1431
  }
1234
- }
1235
- };
1236
1432
 
1237
- /**
1238
- * Set whether this block returns a value.
1239
- * @param {boolean} newBoolean True if there is an output.
1240
- * @param {(string|Array<string>|null)=} opt_check Returned type or list
1241
- * of returned types. Null or undefined if any type could be returned
1242
- * (e.g. variable get).
1243
- */
1244
- Block.prototype.setOutput = function(newBoolean, opt_check) {
1245
- if (newBoolean) {
1246
- if (opt_check === undefined) {
1247
- opt_check = null;
1433
+ // Traverse the AST building up our text string.
1434
+ while (node) {
1435
+ switch (node.getType()) {
1436
+ case ASTNode.types.INPUT: {
1437
+ const connection = /** @type {!Connection} */ (node.getLocation());
1438
+ if (!node.in()) {
1439
+ text.push(emptyFieldPlaceholder);
1440
+ } else if (shouldAddParentheses(connection)) {
1441
+ text.push('(');
1442
+ }
1443
+ break;
1444
+ }
1445
+ case ASTNode.types.FIELD: {
1446
+ const field = /** @type {Field} */ (node.getLocation());
1447
+ if (field.name !== constants.COLLAPSED_FIELD_NAME) {
1448
+ text.push(field.getText());
1449
+ }
1450
+ break;
1451
+ }
1452
+ }
1453
+
1454
+ const current = node;
1455
+ node = current.in() || current.next();
1456
+ if (!node) {
1457
+ // Can't go in or next, keep going out until we can go next.
1458
+ node = current.out();
1459
+ checkRoot();
1460
+ while (node && !node.next()) {
1461
+ node = node.out();
1462
+ checkRoot();
1463
+ // If we hit an input on the way up, possibly close out parentheses.
1464
+ if (node && node.getType() === ASTNode.types.INPUT &&
1465
+ shouldAddParentheses(
1466
+ /** @type {!Connection} */ (node.getLocation()))) {
1467
+ text.push(')');
1468
+ }
1469
+ }
1470
+ if (node) {
1471
+ node = node.next();
1472
+ }
1473
+ }
1248
1474
  }
1249
- if (!this.outputConnection) {
1250
- this.outputConnection = this.makeConnection_(ConnectionType.OUTPUT_VALUE);
1475
+
1476
+ // Restore state of NAVIGATE_ALL_FIELDS.
1477
+ ASTNode.NAVIGATE_ALL_FIELDS = prevNavigateFields;
1478
+
1479
+ // Run through our text array and simplify expression to remove parentheses
1480
+ // around single field blocks.
1481
+ // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?']
1482
+ for (let i = 2; i < text.length; i++) {
1483
+ if (text[i - 2] === '(' && text[i] === ')') {
1484
+ text[i - 2] = text[i - 1];
1485
+ text.splice(i - 1, 2);
1486
+ }
1251
1487
  }
1252
- this.outputConnection.setCheck(opt_check);
1253
- } else {
1254
- if (this.outputConnection) {
1255
- if (this.outputConnection.isConnected()) {
1256
- throw Error('Must disconnect output value before removing connection.');
1488
+
1489
+ // Join the text array, removing spaces around added parentheses.
1490
+ text = text.reduce(function(acc, value) {
1491
+ return acc + ((acc.substr(-1) === '(' || value === ')') ? '' : ' ') +
1492
+ value;
1493
+ }, '');
1494
+ text = text.trim() || '???';
1495
+ if (opt_maxLength) {
1496
+ // TODO: Improve truncation so that text from this block is given
1497
+ // priority. E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not
1498
+ // "1+2+3+4+5...". E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...".
1499
+ if (text.length > opt_maxLength) {
1500
+ text = text.substring(0, opt_maxLength - 3) + '...';
1257
1501
  }
1258
- this.outputConnection.dispose();
1259
- this.outputConnection = null;
1260
1502
  }
1503
+ return text;
1261
1504
  }
1262
- };
1263
1505
 
1264
- /**
1265
- * Set whether value inputs are arranged horizontally or vertically.
1266
- * @param {boolean} newBoolean True if inputs are horizontal.
1267
- */
1268
- Block.prototype.setInputsInline = function(newBoolean) {
1269
- if (this.inputsInline !== newBoolean) {
1270
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1271
- this, 'inline', null, this.inputsInline, newBoolean));
1272
- this.inputsInline = newBoolean;
1506
+ /**
1507
+ * Shortcut for appending a value input row.
1508
+ * @param {string} name Language-neutral identifier which may used to find
1509
+ * this input again. Should be unique to this block.
1510
+ * @return {!Input} The input object created.
1511
+ */
1512
+ appendValueInput(name) {
1513
+ return this.appendInput_(inputTypes.VALUE, name);
1273
1514
  }
1274
- };
1275
1515
 
1276
- /**
1277
- * Get whether value inputs are arranged horizontally or vertically.
1278
- * @return {boolean} True if inputs are horizontal.
1279
- */
1280
- Block.prototype.getInputsInline = function() {
1281
- if (this.inputsInline !== undefined) {
1282
- // Set explicitly.
1283
- return this.inputsInline;
1284
- }
1285
- // Not defined explicitly. Figure out what would look best.
1286
- for (let i = 1; i < this.inputList.length; i++) {
1287
- if (this.inputList[i - 1].type === inputTypes.DUMMY &&
1288
- this.inputList[i].type === inputTypes.DUMMY) {
1289
- // Two dummy inputs in a row. Don't inline them.
1290
- return false;
1291
- }
1292
- }
1293
- for (let i = 1; i < this.inputList.length; i++) {
1294
- if (this.inputList[i - 1].type === inputTypes.VALUE &&
1295
- this.inputList[i].type === inputTypes.DUMMY) {
1296
- // Dummy input after a value input. Inline them.
1297
- return true;
1298
- }
1516
+ /**
1517
+ * Shortcut for appending a statement input row.
1518
+ * @param {string} name Language-neutral identifier which may used to find
1519
+ * this input again. Should be unique to this block.
1520
+ * @return {!Input} The input object created.
1521
+ */
1522
+ appendStatementInput(name) {
1523
+ return this.appendInput_(inputTypes.STATEMENT, name);
1299
1524
  }
1300
- return false;
1301
- };
1302
1525
 
1303
- /**
1304
- * Set the block's output shape.
1305
- * @param {?number} outputShape Value representing an output shape.
1306
- */
1307
- Block.prototype.setOutputShape = function(outputShape) {
1308
- this.outputShape_ = outputShape;
1309
- };
1526
+ /**
1527
+ * Shortcut for appending a dummy input row.
1528
+ * @param {string=} opt_name Language-neutral identifier which may used to
1529
+ * find this input again. Should be unique to this block.
1530
+ * @return {!Input} The input object created.
1531
+ */
1532
+ appendDummyInput(opt_name) {
1533
+ return this.appendInput_(inputTypes.DUMMY, opt_name || '');
1534
+ }
1310
1535
 
1311
- /**
1312
- * Get the block's output shape.
1313
- * @return {?number} Value representing output shape if one exists.
1314
- */
1315
- Block.prototype.getOutputShape = function() {
1316
- return this.outputShape_;
1317
- };
1536
+ /**
1537
+ * Initialize this block using a cross-platform, internationalization-friendly
1538
+ * JSON description.
1539
+ * @param {!Object} json Structured data describing the block.
1540
+ */
1541
+ jsonInit(json) {
1542
+ const warningPrefix = json['type'] ? 'Block "' + json['type'] + '": ' : '';
1318
1543
 
1319
- /**
1320
- * Get whether this block is enabled or not.
1321
- * @return {boolean} True if enabled.
1322
- */
1323
- Block.prototype.isEnabled = function() {
1324
- return !this.disabled;
1325
- };
1544
+ // Validate inputs.
1545
+ if (json['output'] && json['previousStatement']) {
1546
+ throw Error(
1547
+ warningPrefix +
1548
+ 'Must not have both an output and a previousStatement.');
1549
+ }
1326
1550
 
1327
- /**
1328
- * Set whether the block is enabled or not.
1329
- * @param {boolean} enabled True if enabled.
1330
- */
1331
- Block.prototype.setEnabled = function(enabled) {
1332
- if (this.isEnabled() !== enabled) {
1333
- const oldValue = this.disabled;
1334
- this.disabled = !enabled;
1335
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1336
- this, 'disabled', null, oldValue, !enabled));
1337
- }
1338
- };
1551
+ // Set basic properties of block.
1552
+ // Makes styles backward compatible with old way of defining hat style.
1553
+ if (json['style'] && json['style'].hat) {
1554
+ this.hat = json['style'].hat;
1555
+ // Must set to null so it doesn't error when checking for style and
1556
+ // colour.
1557
+ json['style'] = null;
1558
+ }
1339
1559
 
1340
- /**
1341
- * Get whether the block is disabled or not due to parents.
1342
- * The block's own disabled property is not considered.
1343
- * @return {boolean} True if disabled.
1344
- */
1345
- Block.prototype.getInheritedDisabled = function() {
1346
- let ancestor = this.getSurroundParent();
1347
- while (ancestor) {
1348
- if (ancestor.disabled) {
1349
- return true;
1560
+ if (json['style'] && json['colour']) {
1561
+ throw Error(warningPrefix + 'Must not have both a colour and a style.');
1562
+ } else if (json['style']) {
1563
+ this.jsonInitStyle_(json, warningPrefix);
1564
+ } else {
1565
+ this.jsonInitColour_(json, warningPrefix);
1350
1566
  }
1351
- ancestor = ancestor.getSurroundParent();
1352
- }
1353
- // Ran off the top.
1354
- return false;
1355
- };
1356
1567
 
1357
- /**
1358
- * Get whether the block is collapsed or not.
1359
- * @return {boolean} True if collapsed.
1360
- */
1361
- Block.prototype.isCollapsed = function() {
1362
- return this.collapsed_;
1363
- };
1568
+ // Interpolate the message blocks.
1569
+ let i = 0;
1570
+ while (json['message' + i] !== undefined) {
1571
+ this.interpolate_(
1572
+ json['message' + i], json['args' + i] || [],
1573
+ json['lastDummyAlign' + i], warningPrefix);
1574
+ i++;
1575
+ }
1364
1576
 
1365
- /**
1366
- * Set whether the block is collapsed or not.
1367
- * @param {boolean} collapsed True if collapsed.
1368
- */
1369
- Block.prototype.setCollapsed = function(collapsed) {
1370
- if (this.collapsed_ !== collapsed) {
1371
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
1372
- this, 'collapsed', null, this.collapsed_, collapsed));
1373
- this.collapsed_ = collapsed;
1374
- }
1375
- };
1577
+ if (json['inputsInline'] !== undefined) {
1578
+ this.setInputsInline(json['inputsInline']);
1579
+ }
1580
+ // Set output and previous/next connections.
1581
+ if (json['output'] !== undefined) {
1582
+ this.setOutput(true, json['output']);
1583
+ }
1584
+ if (json['outputShape'] !== undefined) {
1585
+ this.setOutputShape(json['outputShape']);
1586
+ }
1587
+ if (json['previousStatement'] !== undefined) {
1588
+ this.setPreviousStatement(true, json['previousStatement']);
1589
+ }
1590
+ if (json['nextStatement'] !== undefined) {
1591
+ this.setNextStatement(true, json['nextStatement']);
1592
+ }
1593
+ if (json['tooltip'] !== undefined) {
1594
+ const rawValue = json['tooltip'];
1595
+ const localizedText = parsing.replaceMessageReferences(rawValue);
1596
+ this.setTooltip(localizedText);
1597
+ }
1598
+ if (json['enableContextMenu'] !== undefined) {
1599
+ this.contextMenu = !!json['enableContextMenu'];
1600
+ }
1601
+ if (json['suppressPrefixSuffix'] !== undefined) {
1602
+ this.suppressPrefixSuffix = !!json['suppressPrefixSuffix'];
1603
+ }
1604
+ if (json['helpUrl'] !== undefined) {
1605
+ const rawValue = json['helpUrl'];
1606
+ const localizedValue = parsing.replaceMessageReferences(rawValue);
1607
+ this.setHelpUrl(localizedValue);
1608
+ }
1609
+ if (typeof json['extensions'] === 'string') {
1610
+ console.warn(
1611
+ warningPrefix +
1612
+ 'JSON attribute \'extensions\' should be an array of' +
1613
+ ' strings. Found raw string in JSON for \'' + json['type'] +
1614
+ '\' block.');
1615
+ json['extensions'] = [json['extensions']]; // Correct and continue.
1616
+ }
1376
1617
 
1377
- /**
1378
- * Create a human-readable text representation of this block and any children.
1379
- * @param {number=} opt_maxLength Truncate the string to this length.
1380
- * @param {string=} opt_emptyToken The placeholder string used to denote an
1381
- * empty field. If not specified, '?' is used.
1382
- * @return {string} Text of block.
1383
- */
1384
- Block.prototype.toString = function(opt_maxLength, opt_emptyToken) {
1385
- let text = [];
1386
- const emptyFieldPlaceholder = opt_emptyToken || '?';
1618
+ // Add the mutator to the block.
1619
+ if (json['mutator'] !== undefined) {
1620
+ Extensions.apply(json['mutator'], this, true);
1621
+ }
1387
1622
 
1388
- // Temporarily set flag to navigate to all fields.
1389
- const prevNavigateFields = ASTNode.NAVIGATE_ALL_FIELDS;
1390
- ASTNode.NAVIGATE_ALL_FIELDS = true;
1623
+ const extensionNames = json['extensions'];
1624
+ if (Array.isArray(extensionNames)) {
1625
+ for (let j = 0; j < extensionNames.length; j++) {
1626
+ Extensions.apply(extensionNames[j], this, false);
1627
+ }
1628
+ }
1629
+ }
1391
1630
 
1392
- let node = ASTNode.createBlockNode(this);
1393
- const rootNode = node;
1631
+ /**
1632
+ * Initialize the colour of this block from the JSON description.
1633
+ * @param {!Object} json Structured data describing the block.
1634
+ * @param {string} warningPrefix Warning prefix string identifying block.
1635
+ * @private
1636
+ */
1637
+ jsonInitColour_(json, warningPrefix) {
1638
+ if ('colour' in json) {
1639
+ if (json['colour'] === undefined) {
1640
+ console.warn(warningPrefix + 'Undefined colour value.');
1641
+ } else {
1642
+ const rawValue = json['colour'];
1643
+ try {
1644
+ this.setColour(rawValue);
1645
+ } catch (e) {
1646
+ console.warn(warningPrefix + 'Illegal colour value: ', rawValue);
1647
+ }
1648
+ }
1649
+ }
1650
+ }
1394
1651
 
1395
1652
  /**
1396
- * Whether or not to add parentheses around an input.
1397
- * @param {!Connection} connection The connection.
1398
- * @return {boolean} True if we should add parentheses around the input.
1653
+ * Initialize the style of this block from the JSON description.
1654
+ * @param {!Object} json Structured data describing the block.
1655
+ * @param {string} warningPrefix Warning prefix string identifying block.
1656
+ * @private
1399
1657
  */
1400
- function shouldAddParentheses(connection) {
1401
- let checks = connection.getCheck();
1402
- if (!checks && connection.targetConnection) {
1403
- checks = connection.targetConnection.getCheck();
1658
+ jsonInitStyle_(json, warningPrefix) {
1659
+ const blockStyleName = json['style'];
1660
+ try {
1661
+ this.setStyle(blockStyleName);
1662
+ } catch (styleError) {
1663
+ console.warn(warningPrefix + 'Style does not exist: ', blockStyleName);
1404
1664
  }
1405
- return !!checks &&
1406
- (checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1);
1407
1665
  }
1408
1666
 
1409
1667
  /**
1410
- * Check that we haven't circled back to the original root node.
1668
+ * Add key/values from mixinObj to this block object. By default, this method
1669
+ * will check that the keys in mixinObj will not overwrite existing values in
1670
+ * the block, including prototype values. This provides some insurance against
1671
+ * mixin / extension incompatibilities with future block features. This check
1672
+ * can be disabled by passing true as the second argument.
1673
+ * @param {!Object} mixinObj The key/values pairs to add to this block object.
1674
+ * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks.
1411
1675
  */
1412
- function checkRoot() {
1413
- if (node && node.getType() === rootNode.getType() &&
1414
- node.getLocation() === rootNode.getLocation()) {
1415
- node = null;
1676
+ mixin(mixinObj, opt_disableCheck) {
1677
+ if (opt_disableCheck !== undefined &&
1678
+ typeof opt_disableCheck !== 'boolean') {
1679
+ throw Error('opt_disableCheck must be a boolean if provided');
1416
1680
  }
1417
- }
1418
-
1419
- // Traverse the AST building up our text string.
1420
- while (node) {
1421
- switch (node.getType()) {
1422
- case ASTNode.types.INPUT: {
1423
- const connection = /** @type {!Connection} */ (node.getLocation());
1424
- if (!node.in()) {
1425
- text.push(emptyFieldPlaceholder);
1426
- } else if (shouldAddParentheses(connection)) {
1427
- text.push('(');
1681
+ if (!opt_disableCheck) {
1682
+ const overwrites = [];
1683
+ for (const key in mixinObj) {
1684
+ if (this[key] !== undefined) {
1685
+ overwrites.push(key);
1428
1686
  }
1429
- break;
1430
1687
  }
1431
- case ASTNode.types.FIELD: {
1432
- const field = /** @type {Field} */ (node.getLocation());
1433
- if (field.name !== constants.COLLAPSED_FIELD_NAME) {
1434
- text.push(field.getText());
1435
- }
1436
- break;
1688
+ if (overwrites.length) {
1689
+ throw Error(
1690
+ 'Mixin will overwrite block members: ' +
1691
+ JSON.stringify(overwrites));
1437
1692
  }
1438
1693
  }
1694
+ object.mixin(this, mixinObj);
1695
+ }
1439
1696
 
1440
- const current = node;
1441
- node = current.in() || current.next();
1442
- if (!node) {
1443
- // Can't go in or next, keep going out until we can go next.
1444
- node = current.out();
1445
- checkRoot();
1446
- while (node && !node.next()) {
1447
- node = node.out();
1448
- checkRoot();
1449
- // If we hit an input on the way up, possibly close out parentheses.
1450
- if (node && node.getType() === ASTNode.types.INPUT &&
1451
- shouldAddParentheses(
1452
- /** @type {!Connection} */ (node.getLocation()))) {
1453
- text.push(')');
1697
+ /**
1698
+ * Interpolate a message description onto the block.
1699
+ * @param {string} message Text contains interpolation tokens (%1, %2, ...)
1700
+ * that match with fields or inputs defined in the args array.
1701
+ * @param {!Array} args Array of arguments to be interpolated.
1702
+ * @param {string|undefined} lastDummyAlign If a dummy input is added at the
1703
+ * end, how should it be aligned?
1704
+ * @param {string} warningPrefix Warning prefix string identifying block.
1705
+ * @private
1706
+ */
1707
+ interpolate_(message, args, lastDummyAlign, warningPrefix) {
1708
+ const tokens = parsing.tokenizeInterpolation(message);
1709
+ this.validateTokens_(tokens, args.length);
1710
+ const elements = this.interpolateArguments_(tokens, args, lastDummyAlign);
1711
+
1712
+ // An array of [field, fieldName] tuples.
1713
+ const fieldStack = [];
1714
+ for (let i = 0, element; (element = elements[i]); i++) {
1715
+ if (this.isInputKeyword_(element['type'])) {
1716
+ const input = this.inputFromJson_(element, warningPrefix);
1717
+ // Should never be null, but just in case.
1718
+ if (input) {
1719
+ for (let j = 0, tuple; (tuple = fieldStack[j]); j++) {
1720
+ input.appendField(tuple[0], tuple[1]);
1721
+ }
1722
+ fieldStack.length = 0;
1723
+ }
1724
+ } else {
1725
+ // All other types, including ones starting with 'input_' get routed
1726
+ // here.
1727
+ const field = this.fieldFromJson_(element);
1728
+ if (field) {
1729
+ fieldStack.push([field, element['name']]);
1454
1730
  }
1455
- }
1456
- if (node) {
1457
- node = node.next();
1458
1731
  }
1459
1732
  }
1460
1733
  }
1461
1734
 
1462
- // Restore state of NAVIGATE_ALL_FIELDS.
1463
- ASTNode.NAVIGATE_ALL_FIELDS = prevNavigateFields;
1464
-
1465
- // Run through our text array and simplify expression to remove parentheses
1466
- // around single field blocks.
1467
- // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?']
1468
- for (let i = 2; i < text.length; i++) {
1469
- if (text[i - 2] === '(' && text[i] === ')') {
1470
- text[i - 2] = text[i - 1];
1471
- text.splice(i - 1, 2);
1735
+ /**
1736
+ * Validates that the tokens are within the correct bounds, with no
1737
+ * duplicates, and that all of the arguments are referred to. Throws errors if
1738
+ * any of these things are not true.
1739
+ * @param {!Array<string|number>} tokens An array of tokens to validate
1740
+ * @param {number} argsCount The number of args that need to be referred to.
1741
+ * @private
1742
+ */
1743
+ validateTokens_(tokens, argsCount) {
1744
+ const visitedArgsHash = [];
1745
+ let visitedArgsCount = 0;
1746
+ for (let i = 0; i < tokens.length; i++) {
1747
+ const token = tokens[i];
1748
+ if (typeof token !== 'number') {
1749
+ continue;
1750
+ }
1751
+ if (token < 1 || token > argsCount) {
1752
+ throw Error(
1753
+ 'Block "' + this.type + '": ' +
1754
+ 'Message index %' + token + ' out of range.');
1755
+ }
1756
+ if (visitedArgsHash[token]) {
1757
+ throw Error(
1758
+ 'Block "' + this.type + '": ' +
1759
+ 'Message index %' + token + ' duplicated.');
1760
+ }
1761
+ visitedArgsHash[token] = true;
1762
+ visitedArgsCount++;
1472
1763
  }
1473
- }
1474
-
1475
- // Join the text array, removing spaces around added parentheses.
1476
- text = text.reduce(function(acc, value) {
1477
- return acc + ((acc.substr(-1) === '(' || value === ')') ? '' : ' ') + value;
1478
- }, '');
1479
- text = text.trim() || '???';
1480
- if (opt_maxLength) {
1481
- // TODO: Improve truncation so that text from this block is given priority.
1482
- // E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not "1+2+3+4+5...".
1483
- // E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...".
1484
- if (text.length > opt_maxLength) {
1485
- text = text.substring(0, opt_maxLength - 3) + '...';
1764
+ if (visitedArgsCount !== argsCount) {
1765
+ throw Error(
1766
+ 'Block "' + this.type + '": ' +
1767
+ 'Message does not reference all ' + argsCount + ' arg(s).');
1486
1768
  }
1487
1769
  }
1488
- return text;
1489
- };
1490
-
1491
- /**
1492
- * Shortcut for appending a value input row.
1493
- * @param {string} name Language-neutral identifier which may used to find this
1494
- * input again. Should be unique to this block.
1495
- * @return {!Input} The input object created.
1496
- */
1497
- Block.prototype.appendValueInput = function(name) {
1498
- return this.appendInput_(inputTypes.VALUE, name);
1499
- };
1500
-
1501
- /**
1502
- * Shortcut for appending a statement input row.
1503
- * @param {string} name Language-neutral identifier which may used to find this
1504
- * input again. Should be unique to this block.
1505
- * @return {!Input} The input object created.
1506
- */
1507
- Block.prototype.appendStatementInput = function(name) {
1508
- return this.appendInput_(inputTypes.STATEMENT, name);
1509
- };
1510
-
1511
- /**
1512
- * Shortcut for appending a dummy input row.
1513
- * @param {string=} opt_name Language-neutral identifier which may used to find
1514
- * this input again. Should be unique to this block.
1515
- * @return {!Input} The input object created.
1516
- */
1517
- Block.prototype.appendDummyInput = function(opt_name) {
1518
- return this.appendInput_(inputTypes.DUMMY, opt_name || '');
1519
- };
1520
-
1521
- /**
1522
- * Initialize this block using a cross-platform, internationalization-friendly
1523
- * JSON description.
1524
- * @param {!Object} json Structured data describing the block.
1525
- */
1526
- Block.prototype.jsonInit = function(json) {
1527
- const warningPrefix = json['type'] ? 'Block "' + json['type'] + '": ' : '';
1528
-
1529
- // Validate inputs.
1530
- if (json['output'] && json['previousStatement']) {
1531
- throw Error(
1532
- warningPrefix +
1533
- 'Must not have both an output and a previousStatement.');
1534
- }
1535
1770
 
1536
- // Set basic properties of block.
1537
- // Makes styles backward compatible with old way of defining hat style.
1538
- if (json['style'] && json['style'].hat) {
1539
- this.hat = json['style'].hat;
1540
- // Must set to null so it doesn't error when checking for style and colour.
1541
- json['style'] = null;
1542
- }
1771
+ /**
1772
+ * Inserts args in place of numerical tokens. String args are converted to
1773
+ * JSON that defines a label field. If necessary an extra dummy input is added
1774
+ * to the end of the elements.
1775
+ * @param {!Array<!string|number>} tokens The tokens to interpolate
1776
+ * @param {!Array<!Object|string>} args The arguments to insert.
1777
+ * @param {string|undefined} lastDummyAlign The alignment the added dummy
1778
+ * input should have, if we are required to add one.
1779
+ * @return {!Array<!Object>} The JSON definitions of field and inputs to add
1780
+ * to the block.
1781
+ * @private
1782
+ */
1783
+ interpolateArguments_(tokens, args, lastDummyAlign) {
1784
+ const elements = [];
1785
+ for (let i = 0; i < tokens.length; i++) {
1786
+ let element = tokens[i];
1787
+ if (typeof element === 'number') {
1788
+ element = args[element - 1];
1789
+ }
1790
+ // Args can be strings, which is why this isn't elseif.
1791
+ if (typeof element === 'string') {
1792
+ element = this.stringToFieldJson_(element);
1793
+ if (!element) {
1794
+ continue;
1795
+ }
1796
+ }
1797
+ elements.push(element);
1798
+ }
1543
1799
 
1544
- if (json['style'] && json['colour']) {
1545
- throw Error(warningPrefix + 'Must not have both a colour and a style.');
1546
- } else if (json['style']) {
1547
- this.jsonInitStyle_(json, warningPrefix);
1548
- } else {
1549
- this.jsonInitColour_(json, warningPrefix);
1550
- }
1800
+ const length = elements.length;
1801
+ if (length && !this.isInputKeyword_(elements[length - 1]['type'])) {
1802
+ const dummyInput = {'type': 'input_dummy'};
1803
+ if (lastDummyAlign) {
1804
+ dummyInput['align'] = lastDummyAlign;
1805
+ }
1806
+ elements.push(dummyInput);
1807
+ }
1551
1808
 
1552
- // Interpolate the message blocks.
1553
- let i = 0;
1554
- while (json['message' + i] !== undefined) {
1555
- this.interpolate_(
1556
- json['message' + i], json['args' + i] || [], json['lastDummyAlign' + i],
1557
- warningPrefix);
1558
- i++;
1809
+ return elements;
1559
1810
  }
1560
1811
 
1561
- if (json['inputsInline'] !== undefined) {
1562
- this.setInputsInline(json['inputsInline']);
1563
- }
1564
- // Set output and previous/next connections.
1565
- if (json['output'] !== undefined) {
1566
- this.setOutput(true, json['output']);
1567
- }
1568
- if (json['outputShape'] !== undefined) {
1569
- this.setOutputShape(json['outputShape']);
1570
- }
1571
- if (json['previousStatement'] !== undefined) {
1572
- this.setPreviousStatement(true, json['previousStatement']);
1573
- }
1574
- if (json['nextStatement'] !== undefined) {
1575
- this.setNextStatement(true, json['nextStatement']);
1576
- }
1577
- if (json['tooltip'] !== undefined) {
1578
- const rawValue = json['tooltip'];
1579
- const localizedText = parsing.replaceMessageReferences(rawValue);
1580
- this.setTooltip(localizedText);
1581
- }
1582
- if (json['enableContextMenu'] !== undefined) {
1583
- this.contextMenu = !!json['enableContextMenu'];
1584
- }
1585
- if (json['suppressPrefixSuffix'] !== undefined) {
1586
- this.suppressPrefixSuffix = !!json['suppressPrefixSuffix'];
1587
- }
1588
- if (json['helpUrl'] !== undefined) {
1589
- const rawValue = json['helpUrl'];
1590
- const localizedValue = parsing.replaceMessageReferences(rawValue);
1591
- this.setHelpUrl(localizedValue);
1592
- }
1593
- if (typeof json['extensions'] === 'string') {
1594
- console.warn(
1595
- warningPrefix + 'JSON attribute \'extensions\' should be an array of' +
1596
- ' strings. Found raw string in JSON for \'' + json['type'] +
1597
- '\' block.');
1598
- json['extensions'] = [json['extensions']]; // Correct and continue.
1812
+ /**
1813
+ * Creates a field from the JSON definition of a field. If a field with the
1814
+ * given type cannot be found, this attempts to create a different field using
1815
+ * the 'alt' property of the JSON definition (if it exists).
1816
+ * @param {{alt:(string|undefined)}} element The element to try to turn into a
1817
+ * field.
1818
+ * @return {?Field} The field defined by the JSON, or null if one
1819
+ * couldn't be created.
1820
+ * @private
1821
+ */
1822
+ fieldFromJson_(element) {
1823
+ const field = fieldRegistry.fromJson(element);
1824
+ if (!field && element['alt']) {
1825
+ if (typeof element['alt'] === 'string') {
1826
+ const json = this.stringToFieldJson_(element['alt']);
1827
+ return json ? this.fieldFromJson_(json) : null;
1828
+ }
1829
+ return this.fieldFromJson_(element['alt']);
1830
+ }
1831
+ return field;
1599
1832
  }
1600
1833
 
1601
- // Add the mutator to the block.
1602
- if (json['mutator'] !== undefined) {
1603
- Extensions.apply(json['mutator'], this, true);
1604
- }
1834
+ /**
1835
+ * Creates an input from the JSON definition of an input. Sets the input's
1836
+ * check and alignment if they are provided.
1837
+ * @param {!Object} element The JSON to turn into an input.
1838
+ * @param {string} warningPrefix The prefix to add to warnings to help the
1839
+ * developer debug.
1840
+ * @return {?Input} The input that has been created, or null if one
1841
+ * could not be created for some reason (should never happen).
1842
+ * @private
1843
+ */
1844
+ inputFromJson_(element, warningPrefix) {
1845
+ const alignmentLookup = {
1846
+ 'LEFT': Align.LEFT,
1847
+ 'RIGHT': Align.RIGHT,
1848
+ 'CENTRE': Align.CENTRE,
1849
+ 'CENTER': Align.CENTRE,
1850
+ };
1605
1851
 
1606
- const extensionNames = json['extensions'];
1607
- if (Array.isArray(extensionNames)) {
1608
- for (let j = 0; j < extensionNames.length; j++) {
1609
- Extensions.apply(extensionNames[j], this, false);
1852
+ let input = null;
1853
+ switch (element['type']) {
1854
+ case 'input_value':
1855
+ input = this.appendValueInput(element['name']);
1856
+ break;
1857
+ case 'input_statement':
1858
+ input = this.appendStatementInput(element['name']);
1859
+ break;
1860
+ case 'input_dummy':
1861
+ input = this.appendDummyInput(element['name']);
1862
+ break;
1863
+ }
1864
+ // Should never be hit because of interpolate_'s checks, but just in case.
1865
+ if (!input) {
1866
+ return null;
1610
1867
  }
1611
- }
1612
- };
1613
1868
 
1614
- /**
1615
- * Initialize the colour of this block from the JSON description.
1616
- * @param {!Object} json Structured data describing the block.
1617
- * @param {string} warningPrefix Warning prefix string identifying block.
1618
- * @private
1619
- */
1620
- Block.prototype.jsonInitColour_ = function(json, warningPrefix) {
1621
- if ('colour' in json) {
1622
- if (json['colour'] === undefined) {
1623
- console.warn(warningPrefix + 'Undefined colour value.');
1624
- } else {
1625
- const rawValue = json['colour'];
1626
- try {
1627
- this.setColour(rawValue);
1628
- } catch (e) {
1629
- console.warn(warningPrefix + 'Illegal colour value: ', rawValue);
1869
+ if (element['check']) {
1870
+ input.setCheck(element['check']);
1871
+ }
1872
+ if (element['align']) {
1873
+ const alignment = alignmentLookup[element['align'].toUpperCase()];
1874
+ if (alignment === undefined) {
1875
+ console.warn(warningPrefix + 'Illegal align value: ', element['align']);
1876
+ } else {
1877
+ input.setAlign(alignment);
1630
1878
  }
1631
1879
  }
1880
+ return input;
1632
1881
  }
1633
- };
1634
1882
 
1635
- /**
1636
- * Initialize the style of this block from the JSON description.
1637
- * @param {!Object} json Structured data describing the block.
1638
- * @param {string} warningPrefix Warning prefix string identifying block.
1639
- * @private
1640
- */
1641
- Block.prototype.jsonInitStyle_ = function(json, warningPrefix) {
1642
- const blockStyleName = json['style'];
1643
- try {
1644
- this.setStyle(blockStyleName);
1645
- } catch (styleError) {
1646
- console.warn(warningPrefix + 'Style does not exist: ', blockStyleName);
1883
+ /**
1884
+ * Returns true if the given string matches one of the input keywords.
1885
+ * @param {string} str The string to check.
1886
+ * @return {boolean} True if the given string matches one of the input
1887
+ * keywords, false otherwise.
1888
+ * @private
1889
+ */
1890
+ isInputKeyword_(str) {
1891
+ return str === 'input_value' || str === 'input_statement' ||
1892
+ str === 'input_dummy';
1647
1893
  }
1648
- };
1649
1894
 
1650
- /**
1651
- * Add key/values from mixinObj to this block object. By default, this method
1652
- * will check that the keys in mixinObj will not overwrite existing values in
1653
- * the block, including prototype values. This provides some insurance against
1654
- * mixin / extension incompatibilities with future block features. This check
1655
- * can be disabled by passing true as the second argument.
1656
- * @param {!Object} mixinObj The key/values pairs to add to this block object.
1657
- * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks.
1658
- */
1659
- Block.prototype.mixin = function(mixinObj, opt_disableCheck) {
1660
- if (opt_disableCheck !== undefined && typeof opt_disableCheck !== 'boolean') {
1661
- throw Error('opt_disableCheck must be a boolean if provided');
1662
- }
1663
- if (!opt_disableCheck) {
1664
- const overwrites = [];
1665
- for (const key in mixinObj) {
1666
- if (this[key] !== undefined) {
1667
- overwrites.push(key);
1668
- }
1895
+ /**
1896
+ * Turns a string into the JSON definition of a label field. If the string
1897
+ * becomes an empty string when trimmed, this returns null.
1898
+ * @param {string} str String to turn into the JSON definition of a label
1899
+ * field.
1900
+ * @return {?{text: string, type: string}} The JSON definition or null.
1901
+ * @private
1902
+ */
1903
+ stringToFieldJson_(str) {
1904
+ str = str.trim();
1905
+ if (str) {
1906
+ return {
1907
+ 'type': 'field_label',
1908
+ 'text': str,
1909
+ };
1669
1910
  }
1670
- if (overwrites.length) {
1671
- throw Error(
1672
- 'Mixin will overwrite block members: ' + JSON.stringify(overwrites));
1911
+ return null;
1912
+ }
1913
+
1914
+ /**
1915
+ * Add a value input, statement input or local variable to this block.
1916
+ * @param {number} type One of Blockly.inputTypes.
1917
+ * @param {string} name Language-neutral identifier which may used to find
1918
+ * this input again. Should be unique to this block.
1919
+ * @return {!Input} The input object created.
1920
+ * @protected
1921
+ */
1922
+ appendInput_(type, name) {
1923
+ let connection = null;
1924
+ if (type === inputTypes.VALUE || type === inputTypes.STATEMENT) {
1925
+ connection = this.makeConnection_(type);
1673
1926
  }
1927
+ if (type === inputTypes.STATEMENT) {
1928
+ this.statementInputCount++;
1929
+ }
1930
+ const input = new Input(type, name, this, connection);
1931
+ // Append input to list.
1932
+ this.inputList.push(input);
1933
+ return input;
1674
1934
  }
1675
- object.mixin(this, mixinObj);
1676
- };
1677
1935
 
1678
- /**
1679
- * Interpolate a message description onto the block.
1680
- * @param {string} message Text contains interpolation tokens (%1, %2, ...)
1681
- * that match with fields or inputs defined in the args array.
1682
- * @param {!Array} args Array of arguments to be interpolated.
1683
- * @param {string|undefined} lastDummyAlign If a dummy input is added at the
1684
- * end, how should it be aligned?
1685
- * @param {string} warningPrefix Warning prefix string identifying block.
1686
- * @private
1687
- */
1688
- Block.prototype.interpolate_ = function(
1689
- message, args, lastDummyAlign, warningPrefix) {
1690
- const tokens = parsing.tokenizeInterpolation(message);
1691
- this.validateTokens_(tokens, args.length);
1692
- const elements = this.interpolateArguments_(tokens, args, lastDummyAlign);
1693
-
1694
- // An array of [field, fieldName] tuples.
1695
- const fieldStack = [];
1696
- for (let i = 0, element; (element = elements[i]); i++) {
1697
- if (this.isInputKeyword_(element['type'])) {
1698
- const input = this.inputFromJson_(element, warningPrefix);
1699
- // Should never be null, but just in case.
1700
- if (input) {
1701
- for (let j = 0, tuple; (tuple = fieldStack[j]); j++) {
1702
- input.appendField(tuple[0], tuple[1]);
1936
+ /**
1937
+ * Move a named input to a different location on this block.
1938
+ * @param {string} name The name of the input to move.
1939
+ * @param {?string} refName Name of input that should be after the moved
1940
+ * input,
1941
+ * or null to be the input at the end.
1942
+ */
1943
+ moveInputBefore(name, refName) {
1944
+ if (name === refName) {
1945
+ return;
1946
+ }
1947
+ // Find both inputs.
1948
+ let inputIndex = -1;
1949
+ let refIndex = refName ? -1 : this.inputList.length;
1950
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
1951
+ if (input.name === name) {
1952
+ inputIndex = i;
1953
+ if (refIndex !== -1) {
1954
+ break;
1955
+ }
1956
+ } else if (refName && input.name === refName) {
1957
+ refIndex = i;
1958
+ if (inputIndex !== -1) {
1959
+ break;
1703
1960
  }
1704
- fieldStack.length = 0;
1705
- }
1706
- } else {
1707
- // All other types, including ones starting with 'input_' get routed here.
1708
- const field = this.fieldFromJson_(element);
1709
- if (field) {
1710
- fieldStack.push([field, element['name']]);
1711
1961
  }
1712
1962
  }
1963
+ if (inputIndex === -1) {
1964
+ throw Error('Named input "' + name + '" not found.');
1965
+ }
1966
+ if (refIndex === -1) {
1967
+ throw Error('Reference input "' + refName + '" not found.');
1968
+ }
1969
+ this.moveNumberedInputBefore(inputIndex, refIndex);
1713
1970
  }
1714
- };
1715
1971
 
1716
- /**
1717
- * Validates that the tokens are within the correct bounds, with no duplicates,
1718
- * and that all of the arguments are referred to. Throws errors if any of these
1719
- * things are not true.
1720
- * @param {!Array<string|number>} tokens An array of tokens to validate
1721
- * @param {number} argsCount The number of args that need to be referred to.
1722
- * @private
1723
- */
1724
- Block.prototype.validateTokens_ = function(tokens, argsCount) {
1725
- const visitedArgsHash = [];
1726
- let visitedArgsCount = 0;
1727
- for (let i = 0; i < tokens.length; i++) {
1728
- const token = tokens[i];
1729
- if (typeof token !== 'number') {
1730
- continue;
1731
- }
1732
- if (token < 1 || token > argsCount) {
1733
- throw Error(
1734
- 'Block "' + this.type + '": ' +
1735
- 'Message index %' + token + ' out of range.');
1972
+ /**
1973
+ * Move a numbered input to a different location on this block.
1974
+ * @param {number} inputIndex Index of the input to move.
1975
+ * @param {number} refIndex Index of input that should be after the moved
1976
+ * input.
1977
+ */
1978
+ moveNumberedInputBefore(inputIndex, refIndex) {
1979
+ // Validate arguments.
1980
+ if (inputIndex === refIndex) {
1981
+ throw Error('Can\'t move input to itself.');
1736
1982
  }
1737
- if (visitedArgsHash[token]) {
1738
- throw Error(
1739
- 'Block "' + this.type + '": ' +
1740
- 'Message index %' + token + ' duplicated.');
1983
+ if (inputIndex >= this.inputList.length) {
1984
+ throw RangeError('Input index ' + inputIndex + ' out of bounds.');
1741
1985
  }
1742
- visitedArgsHash[token] = true;
1743
- visitedArgsCount++;
1744
- }
1745
- if (visitedArgsCount !== argsCount) {
1746
- throw Error(
1747
- 'Block "' + this.type + '": ' +
1748
- 'Message does not reference all ' + argsCount + ' arg(s).');
1986
+ if (refIndex > this.inputList.length) {
1987
+ throw RangeError('Reference input ' + refIndex + ' out of bounds.');
1988
+ }
1989
+ // Remove input.
1990
+ const input = this.inputList[inputIndex];
1991
+ this.inputList.splice(inputIndex, 1);
1992
+ if (inputIndex < refIndex) {
1993
+ refIndex--;
1994
+ }
1995
+ // Reinsert input.
1996
+ this.inputList.splice(refIndex, 0, input);
1749
1997
  }
1750
- };
1751
1998
 
1752
- /**
1753
- * Inserts args in place of numerical tokens. String args are converted to JSON
1754
- * that defines a label field. If necessary an extra dummy input is added to
1755
- * the end of the elements.
1756
- * @param {!Array<!string|number>} tokens The tokens to interpolate
1757
- * @param {!Array<!Object|string>} args The arguments to insert.
1758
- * @param {string|undefined} lastDummyAlign The alignment the added dummy input
1759
- * should have, if we are required to add one.
1760
- * @return {!Array<!Object>} The JSON definitions of field and inputs to add
1761
- * to the block.
1762
- * @private
1763
- */
1764
- Block.prototype.interpolateArguments_ = function(tokens, args, lastDummyAlign) {
1765
- const elements = [];
1766
- for (let i = 0; i < tokens.length; i++) {
1767
- let element = tokens[i];
1768
- if (typeof element === 'number') {
1769
- element = args[element - 1];
1770
- }
1771
- // Args can be strings, which is why this isn't elseif.
1772
- if (typeof element === 'string') {
1773
- element = this.stringToFieldJson_(element);
1774
- if (!element) {
1775
- continue;
1999
+ /**
2000
+ * Remove an input from this block.
2001
+ * @param {string} name The name of the input.
2002
+ * @param {boolean=} opt_quiet True to prevent an error if input is not
2003
+ * present.
2004
+ * @return {boolean} True if operation succeeds, false if input is not present
2005
+ * and opt_quiet is true.
2006
+ * @throws {Error} if the input is not present and opt_quiet is not true.
2007
+ */
2008
+ removeInput(name, opt_quiet) {
2009
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
2010
+ if (input.name === name) {
2011
+ if (input.type === inputTypes.STATEMENT) {
2012
+ this.statementInputCount--;
2013
+ }
2014
+ input.dispose();
2015
+ this.inputList.splice(i, 1);
2016
+ return true;
1776
2017
  }
1777
2018
  }
1778
- elements.push(element);
1779
- }
1780
-
1781
- const length = elements.length;
1782
- if (length && !this.isInputKeyword_(elements[length - 1]['type'])) {
1783
- const dummyInput = {'type': 'input_dummy'};
1784
- if (lastDummyAlign) {
1785
- dummyInput['align'] = lastDummyAlign;
2019
+ if (opt_quiet) {
2020
+ return false;
1786
2021
  }
1787
- elements.push(dummyInput);
2022
+ throw Error('Input not found: ' + name);
1788
2023
  }
1789
2024
 
1790
- return elements;
1791
- };
1792
-
1793
- /**
1794
- * Creates a field from the JSON definition of a field. If a field with the
1795
- * given type cannot be found, this attempts to create a different field using
1796
- * the 'alt' property of the JSON definition (if it exists).
1797
- * @param {{alt:(string|undefined)}} element The element to try to turn into a
1798
- * field.
1799
- * @return {?Field} The field defined by the JSON, or null if one
1800
- * couldn't be created.
1801
- * @private
1802
- */
1803
- Block.prototype.fieldFromJson_ = function(element) {
1804
- const field = fieldRegistry.fromJson(element);
1805
- if (!field && element['alt']) {
1806
- if (typeof element['alt'] === 'string') {
1807
- const json = this.stringToFieldJson_(element['alt']);
1808
- return json ? this.fieldFromJson_(json) : null;
2025
+ /**
2026
+ * Fetches the named input object.
2027
+ * @param {string} name The name of the input.
2028
+ * @return {?Input} The input object, or null if input does not exist.
2029
+ */
2030
+ getInput(name) {
2031
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
2032
+ if (input.name === name) {
2033
+ return input;
2034
+ }
1809
2035
  }
1810
- return this.fieldFromJson_(element['alt']);
2036
+ // This input does not exist.
2037
+ return null;
1811
2038
  }
1812
- return field;
1813
- };
1814
2039
 
1815
- /**
1816
- * Creates an input from the JSON definition of an input. Sets the input's check
1817
- * and alignment if they are provided.
1818
- * @param {!Object} element The JSON to turn into an input.
1819
- * @param {string} warningPrefix The prefix to add to warnings to help the
1820
- * developer debug.
1821
- * @return {?Input} The input that has been created, or null if one
1822
- * could not be created for some reason (should never happen).
1823
- * @private
1824
- */
1825
- Block.prototype.inputFromJson_ = function(element, warningPrefix) {
1826
- const alignmentLookup = {
1827
- 'LEFT': Align.LEFT,
1828
- 'RIGHT': Align.RIGHT,
1829
- 'CENTRE': Align.CENTRE,
1830
- 'CENTER': Align.CENTRE,
1831
- };
1832
-
1833
- let input = null;
1834
- switch (element['type']) {
1835
- case 'input_value':
1836
- input = this.appendValueInput(element['name']);
1837
- break;
1838
- case 'input_statement':
1839
- input = this.appendStatementInput(element['name']);
1840
- break;
1841
- case 'input_dummy':
1842
- input = this.appendDummyInput(element['name']);
1843
- break;
1844
- }
1845
- // Should never be hit because of interpolate_'s checks, but just in case.
1846
- if (!input) {
1847
- return null;
2040
+ /**
2041
+ * Fetches the block attached to the named input.
2042
+ * @param {string} name The name of the input.
2043
+ * @return {?Block} The attached value block, or null if the input is
2044
+ * either disconnected or if the input does not exist.
2045
+ */
2046
+ getInputTargetBlock(name) {
2047
+ const input = this.getInput(name);
2048
+ return input && input.connection && input.connection.targetBlock();
1848
2049
  }
1849
2050
 
1850
- if (element['check']) {
1851
- input.setCheck(element['check']);
2051
+ /**
2052
+ * Returns the comment on this block (or null if there is no comment).
2053
+ * @return {?string} Block's comment.
2054
+ */
2055
+ getCommentText() {
2056
+ return this.commentModel.text;
1852
2057
  }
1853
- if (element['align']) {
1854
- const alignment = alignmentLookup[element['align'].toUpperCase()];
1855
- if (alignment === undefined) {
1856
- console.warn(warningPrefix + 'Illegal align value: ', element['align']);
1857
- } else {
1858
- input.setAlign(alignment);
2058
+
2059
+ /**
2060
+ * Set this block's comment text.
2061
+ * @param {?string} text The text, or null to delete.
2062
+ */
2063
+ setCommentText(text) {
2064
+ if (this.commentModel.text === text) {
2065
+ return;
1859
2066
  }
2067
+ eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
2068
+ this, 'comment', null, this.commentModel.text, text));
2069
+ this.commentModel.text = text;
2070
+ this.comment = text; // For backwards compatibility.
1860
2071
  }
1861
- return input;
1862
- };
1863
-
1864
- /**
1865
- * Returns true if the given string matches one of the input keywords.
1866
- * @param {string} str The string to check.
1867
- * @return {boolean} True if the given string matches one of the input keywords,
1868
- * false otherwise.
1869
- * @private
1870
- */
1871
- Block.prototype.isInputKeyword_ = function(str) {
1872
- return str === 'input_value' || str === 'input_statement' ||
1873
- str === 'input_dummy';
1874
- };
1875
2072
 
1876
- /**
1877
- * Turns a string into the JSON definition of a label field. If the string
1878
- * becomes an empty string when trimmed, this returns null.
1879
- * @param {string} str String to turn into the JSON definition of a label field.
1880
- * @return {?{text: string, type: string}} The JSON definition or null.
1881
- * @private
1882
- */
1883
- Block.prototype.stringToFieldJson_ = function(str) {
1884
- str = str.trim();
1885
- if (str) {
1886
- return {
1887
- 'type': 'field_label',
1888
- 'text': str,
1889
- };
2073
+ /**
2074
+ * Set this block's warning text.
2075
+ * @param {?string} _text The text, or null to delete.
2076
+ * @param {string=} _opt_id An optional ID for the warning text to be able to
2077
+ * maintain multiple warnings.
2078
+ */
2079
+ setWarningText(_text, _opt_id) {
2080
+ // NOP.
1890
2081
  }
1891
- return null;
1892
- };
1893
2082
 
1894
- /**
1895
- * Add a value input, statement input or local variable to this block.
1896
- * @param {number} type One of Blockly.inputTypes.
1897
- * @param {string} name Language-neutral identifier which may used to find this
1898
- * input again. Should be unique to this block.
1899
- * @return {!Input} The input object created.
1900
- * @protected
1901
- */
1902
- Block.prototype.appendInput_ = function(type, name) {
1903
- let connection = null;
1904
- if (type === inputTypes.VALUE || type === inputTypes.STATEMENT) {
1905
- connection = this.makeConnection_(type);
2083
+ /**
2084
+ * Give this block a mutator dialog.
2085
+ * @param {Mutator} _mutator A mutator dialog instance or null to
2086
+ * remove.
2087
+ */
2088
+ setMutator(_mutator) {
2089
+ // NOP.
1906
2090
  }
1907
- if (type === inputTypes.STATEMENT) {
1908
- this.statementInputCount++;
2091
+
2092
+ /**
2093
+ * Return the coordinates of the top-left corner of this block relative to the
2094
+ * drawing surface's origin (0,0), in workspace units.
2095
+ * @return {!Coordinate} Object with .x and .y properties.
2096
+ */
2097
+ getRelativeToSurfaceXY() {
2098
+ return this.xy_;
1909
2099
  }
1910
- const input = new Input(type, name, this, connection);
1911
- // Append input to list.
1912
- this.inputList.push(input);
1913
- return input;
1914
- };
1915
2100
 
1916
- /**
1917
- * Move a named input to a different location on this block.
1918
- * @param {string} name The name of the input to move.
1919
- * @param {?string} refName Name of input that should be after the moved input,
1920
- * or null to be the input at the end.
1921
- */
1922
- Block.prototype.moveInputBefore = function(name, refName) {
1923
- if (name === refName) {
1924
- return;
1925
- }
1926
- // Find both inputs.
1927
- let inputIndex = -1;
1928
- let refIndex = refName ? -1 : this.inputList.length;
1929
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1930
- if (input.name === name) {
1931
- inputIndex = i;
1932
- if (refIndex !== -1) {
1933
- break;
1934
- }
1935
- } else if (refName && input.name === refName) {
1936
- refIndex = i;
1937
- if (inputIndex !== -1) {
1938
- break;
1939
- }
2101
+ /**
2102
+ * Move a block by a relative offset.
2103
+ * @param {number} dx Horizontal offset, in workspace units.
2104
+ * @param {number} dy Vertical offset, in workspace units.
2105
+ */
2106
+ moveBy(dx, dy) {
2107
+ if (this.parentBlock_) {
2108
+ throw Error('Block has parent.');
1940
2109
  }
2110
+ const event = /** @type {!BlockMove} */ (
2111
+ new (eventUtils.get(eventUtils.BLOCK_MOVE))(this));
2112
+ this.xy_.translate(dx, dy);
2113
+ event.recordNew();
2114
+ eventUtils.fire(event);
1941
2115
  }
1942
- if (inputIndex === -1) {
1943
- throw Error('Named input "' + name + '" not found.');
1944
- }
1945
- if (refIndex === -1) {
1946
- throw Error('Reference input "' + refName + '" not found.');
1947
- }
1948
- this.moveNumberedInputBefore(inputIndex, refIndex);
1949
- };
1950
2116
 
1951
- /**
1952
- * Move a numbered input to a different location on this block.
1953
- * @param {number} inputIndex Index of the input to move.
1954
- * @param {number} refIndex Index of input that should be after the moved input.
1955
- */
1956
- Block.prototype.moveNumberedInputBefore = function(inputIndex, refIndex) {
1957
- // Validate arguments.
1958
- if (inputIndex === refIndex) {
1959
- throw Error('Can\'t move input to itself.');
1960
- }
1961
- if (inputIndex >= this.inputList.length) {
1962
- throw RangeError('Input index ' + inputIndex + ' out of bounds.');
1963
- }
1964
- if (refIndex > this.inputList.length) {
1965
- throw RangeError('Reference input ' + refIndex + ' out of bounds.');
1966
- }
1967
- // Remove input.
1968
- const input = this.inputList[inputIndex];
1969
- this.inputList.splice(inputIndex, 1);
1970
- if (inputIndex < refIndex) {
1971
- refIndex--;
2117
+ /**
2118
+ * Create a connection of the specified type.
2119
+ * @param {number} type The type of the connection to create.
2120
+ * @return {!Connection} A new connection of the specified type.
2121
+ * @protected
2122
+ */
2123
+ makeConnection_(type) {
2124
+ return new Connection(this, type);
1972
2125
  }
1973
- // Reinsert input.
1974
- this.inputList.splice(refIndex, 0, input);
1975
- };
1976
2126
 
1977
- /**
1978
- * Remove an input from this block.
1979
- * @param {string} name The name of the input.
1980
- * @param {boolean=} opt_quiet True to prevent an error if input is not present.
1981
- * @return {boolean} True if operation succeeds, false if input is not present
1982
- * and opt_quiet is true.
1983
- * @throws {Error} if the input is not present and opt_quiet is not true.
1984
- */
1985
- Block.prototype.removeInput = function(name, opt_quiet) {
1986
- for (let i = 0, input; (input = this.inputList[i]); i++) {
1987
- if (input.name === name) {
1988
- if (input.type === inputTypes.STATEMENT) {
1989
- this.statementInputCount--;
1990
- }
1991
- input.dispose();
1992
- this.inputList.splice(i, 1);
1993
- return true;
2127
+ /**
2128
+ * Recursively checks whether all statement and value inputs are filled with
2129
+ * blocks. Also checks all following statement blocks in this stack.
2130
+ * @param {boolean=} opt_shadowBlocksAreFilled An optional argument
2131
+ * controlling whether shadow blocks are counted as filled. Defaults to
2132
+ * true.
2133
+ * @return {boolean} True if all inputs are filled, false otherwise.
2134
+ */
2135
+ allInputsFilled(opt_shadowBlocksAreFilled) {
2136
+ // Account for the shadow block filledness toggle.
2137
+ if (opt_shadowBlocksAreFilled === undefined) {
2138
+ opt_shadowBlocksAreFilled = true;
1994
2139
  }
1995
- }
1996
- if (opt_quiet) {
1997
- return false;
1998
- }
1999
- throw Error('Input not found: ' + name);
2000
- };
2001
-
2002
- /**
2003
- * Fetches the named input object.
2004
- * @param {string} name The name of the input.
2005
- * @return {?Input} The input object, or null if input does not exist.
2006
- */
2007
- Block.prototype.getInput = function(name) {
2008
- for (let i = 0, input; (input = this.inputList[i]); i++) {
2009
- if (input.name === name) {
2010
- return input;
2140
+ if (!opt_shadowBlocksAreFilled && this.isShadow()) {
2141
+ return false;
2011
2142
  }
2012
- }
2013
- // This input does not exist.
2014
- return null;
2015
- };
2016
2143
 
2017
- /**
2018
- * Fetches the block attached to the named input.
2019
- * @param {string} name The name of the input.
2020
- * @return {?Block} The attached value block, or null if the input is
2021
- * either disconnected or if the input does not exist.
2022
- */
2023
- Block.prototype.getInputTargetBlock = function(name) {
2024
- const input = this.getInput(name);
2025
- return input && input.connection && input.connection.targetBlock();
2026
- };
2144
+ // Recursively check each input block of the current block.
2145
+ for (let i = 0, input; (input = this.inputList[i]); i++) {
2146
+ if (!input.connection) {
2147
+ continue;
2148
+ }
2149
+ const target = input.connection.targetBlock();
2150
+ if (!target || !target.allInputsFilled(opt_shadowBlocksAreFilled)) {
2151
+ return false;
2152
+ }
2153
+ }
2027
2154
 
2028
- /**
2029
- * Returns the comment on this block (or null if there is no comment).
2030
- * @return {?string} Block's comment.
2031
- */
2032
- Block.prototype.getCommentText = function() {
2033
- return this.commentModel.text;
2034
- };
2155
+ // Recursively check the next block after the current block.
2156
+ const next = this.getNextBlock();
2157
+ if (next) {
2158
+ return next.allInputsFilled(opt_shadowBlocksAreFilled);
2159
+ }
2035
2160
 
2036
- /**
2037
- * Set this block's comment text.
2038
- * @param {?string} text The text, or null to delete.
2039
- */
2040
- Block.prototype.setCommentText = function(text) {
2041
- if (this.commentModel.text === text) {
2042
- return;
2161
+ return true;
2043
2162
  }
2044
- eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))(
2045
- this, 'comment', null, this.commentModel.text, text));
2046
- this.commentModel.text = text;
2047
- this.comment = text; // For backwards compatibility.
2048
- };
2049
-
2050
- /**
2051
- * Set this block's warning text.
2052
- * @param {?string} _text The text, or null to delete.
2053
- * @param {string=} _opt_id An optional ID for the warning text to be able to
2054
- * maintain multiple warnings.
2055
- */
2056
- Block.prototype.setWarningText = function(_text, _opt_id) {
2057
- // NOP.
2058
- };
2059
-
2060
- /**
2061
- * Give this block a mutator dialog.
2062
- * @param {Mutator} _mutator A mutator dialog instance or null to
2063
- * remove.
2064
- */
2065
- Block.prototype.setMutator = function(_mutator) {
2066
- // NOP.
2067
- };
2068
2163
 
2069
- /**
2070
- * Return the coordinates of the top-left corner of this block relative to the
2071
- * drawing surface's origin (0,0), in workspace units.
2072
- * @return {!Coordinate} Object with .x and .y properties.
2073
- */
2074
- Block.prototype.getRelativeToSurfaceXY = function() {
2075
- return this.xy_;
2076
- };
2164
+ /**
2165
+ * This method returns a string describing this Block in developer terms (type
2166
+ * name and ID; English only).
2167
+ *
2168
+ * Intended to on be used in console logs and errors. If you need a string
2169
+ * that uses the user's native language (including block text, field values,
2170
+ * and child blocks), use [toString()]{@link Block#toString}.
2171
+ * @return {string} The description.
2172
+ */
2173
+ toDevString() {
2174
+ let msg = this.type ? '"' + this.type + '" block' : 'Block';
2175
+ if (this.id) {
2176
+ msg += ' (id="' + this.id + '")';
2177
+ }
2178
+ return msg;
2179
+ }
2180
+ }
2077
2181
 
2078
2182
  /**
2079
- * Move a block by a relative offset.
2080
- * @param {number} dx Horizontal offset, in workspace units.
2081
- * @param {number} dy Vertical offset, in workspace units.
2183
+ * @typedef {{
2184
+ * text:?string,
2185
+ * pinned:boolean,
2186
+ * size:Size
2187
+ * }}
2082
2188
  */
2083
- Block.prototype.moveBy = function(dx, dy) {
2084
- if (this.parentBlock_) {
2085
- throw Error('Block has parent.');
2086
- }
2087
- const event = new (eventUtils.get(eventUtils.BLOCK_MOVE))(this);
2088
- this.xy_.translate(dx, dy);
2089
- event.recordNew();
2090
- eventUtils.fire(event);
2091
- };
2189
+ Block.CommentModel;
2092
2190
 
2093
2191
  /**
2094
- * Create a connection of the specified type.
2095
- * @param {number} type The type of the connection to create.
2096
- * @return {!Connection} A new connection of the specified type.
2097
- * @protected
2192
+ * An optional callback method to use whenever the block's parent workspace
2193
+ * changes. This is usually only called from the constructor, the block type
2194
+ * initializer function, or an extension initializer function.
2195
+ * @type {undefined|?function(Abstract)}
2098
2196
  */
2099
- Block.prototype.makeConnection_ = function(type) {
2100
- return new Connection(this, type);
2101
- };
2197
+ Block.prototype.onchange;
2102
2198
 
2103
2199
  /**
2104
- * Recursively checks whether all statement and value inputs are filled with
2105
- * blocks. Also checks all following statement blocks in this stack.
2106
- * @param {boolean=} opt_shadowBlocksAreFilled An optional argument controlling
2107
- * whether shadow blocks are counted as filled. Defaults to true.
2108
- * @return {boolean} True if all inputs are filled, false otherwise.
2200
+ * The language-neutral ID given to the collapsed input.
2201
+ * @const {string}
2109
2202
  */
2110
- Block.prototype.allInputsFilled = function(opt_shadowBlocksAreFilled) {
2111
- // Account for the shadow block filledness toggle.
2112
- if (opt_shadowBlocksAreFilled === undefined) {
2113
- opt_shadowBlocksAreFilled = true;
2114
- }
2115
- if (!opt_shadowBlocksAreFilled && this.isShadow()) {
2116
- return false;
2117
- }
2118
-
2119
- // Recursively check each input block of the current block.
2120
- for (let i = 0, input; (input = this.inputList[i]); i++) {
2121
- if (!input.connection) {
2122
- continue;
2123
- }
2124
- const target = input.connection.targetBlock();
2125
- if (!target || !target.allInputsFilled(opt_shadowBlocksAreFilled)) {
2126
- return false;
2127
- }
2128
- }
2129
-
2130
- // Recursively check the next block after the current block.
2131
- const next = this.getNextBlock();
2132
- if (next) {
2133
- return next.allInputsFilled(opt_shadowBlocksAreFilled);
2134
- }
2135
-
2136
- return true;
2137
- };
2203
+ Block.COLLAPSED_INPUT_NAME = constants.COLLAPSED_INPUT_NAME;
2138
2204
 
2139
2205
  /**
2140
- * This method returns a string describing this Block in developer terms (type
2141
- * name and ID; English only).
2142
- *
2143
- * Intended to on be used in console logs and errors. If you need a string that
2144
- * uses the user's native language (including block text, field values, and
2145
- * child blocks), use [toString()]{@link Block#toString}.
2146
- * @return {string} The description.
2206
+ * The language-neutral ID given to the collapsed field.
2207
+ * @const {string}
2147
2208
  */
2148
- Block.prototype.toDevString = function() {
2149
- let msg = this.type ? '"' + this.type + '" block' : 'Block';
2150
- if (this.id) {
2151
- msg += ' (id="' + this.id + '")';
2152
- }
2153
- return msg;
2154
- };
2209
+ Block.COLLAPSED_FIELD_NAME = constants.COLLAPSED_FIELD_NAME;
2155
2210
 
2156
2211
  exports.Block = Block;