-
Notifications
You must be signed in to change notification settings - Fork 482
/
block_utils.js
601 lines (548 loc) · 18.8 KB
/
block_utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import xml from './xml';
const ATTRIBUTES_TO_CLEAN = [
'uservisible',
'deletable',
'movable',
];
/**
* Create the xml for a level's toolbox
* @param {string} blocks The xml of the blocks to go in the toolbox
*/
exports.createToolbox = function (blocks) {
return '<xml id="toolbox" style="display: none;">' + blocks + '</xml>';
};
/**
* Create the xml for a block of the given type
* @param {string} type The type of the block
* @param {Object.<string,string>} [titles] Dictionary of titles mapping name to value
* @param {Object} [values] Dictionary of values mapping name to value
* @param {string} values.type Type of the value input
* @param {string} values.titleName Name of the title block
* @param {string} values.titleValue Input value
*/
exports.blockOfType = function (type, titles, values) {
let inputText = '';
if (titles) {
for (let key in titles) {
inputText += `<title name="${key}">${titles[key]}</title>`;
}
}
if (values) {
for (let key in values) {
inputText += `<value name="${key}">
<block type="${values[key].type}">
<title name="${values[key].titleName}">${values[key].titleValue}</title>
</block>
</value>`;
}
}
return `<block type="${type}">${inputText}</block>`;
};
/*
* Creates an XML node for an individual block. See blockOfType for params
*/
exports.blockAsXmlNode = function (type, inputs = {}) {
return xml
.parseElement(exports.blockOfType(type, inputs.titles, inputs.values))
.firstChild;
};
/**
* Create the xml for a block of the given type, with the provided child nested
* in a next block
* @param {string} type The type of the block
* @param {Object.<string,string>} [titles] Dictionary of titles mapping name to value
* @param {string} child Xml for the child block
*/
exports.blockWithNext = function (type, titles, child) {
var titleText = '';
if (titles) {
for (var key in titles) {
titleText += '<title name="' + key + '">' + titles[key] + '</title>';
}
}
return '<block type="' + type + '">' + titleText + '<next>' + child + '</next></block>';
};
/**
* Give a list of types, returns the xml assuming each block is a child of
* the previous block.
*/
exports.blocksFromList = function (types) {
if (types.length === 1) {
return this.blockOfType(types[0]);
}
return this.blockWithNext(types[0], {}, this.blocksFromList(types.slice(1)));
};
/**
* Create the xml for a category in a toolbox
*/
exports.createCategory = function (name, blocks, custom) {
return '<category name="' + name + '"' +
(custom ? ' custom="' + custom + '"' : '') +
'>' + blocks + '</category>';
};
/**
* Generate a simple block with a plain title and next/previous connectors.
*/
exports.generateSimpleBlock = function (blockly, generator, options) {
['name', 'title', 'tooltip', 'functionName'].forEach(function (param) {
if (!options[param]) {
throw new Error('generateSimpleBlock requires param "' + param + '"');
}
});
var name = options.name;
var helpUrl = options.helpUrl || ""; // optional param
var title = options.title;
var titleImage = options.titleImage;
var tooltip = options.tooltip;
var functionName = options.functionName;
blockly.Blocks[name] = {
helpUrl: helpUrl,
init: function () {
// Note: has a fixed HSV. Could make this customizable if need be
this.setHSV(184, 1.00, 0.74);
var input = this.appendDummyInput();
if (title) {
input.appendTitle(title);
}
if (titleImage) {
input.appendTitle(new blockly.FieldImage(titleImage));
}
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(tooltip);
}
};
generator[name] = function () {
// Generate JavaScript for putting dirt on to a tile.
return functionName + '(\'block_id_' + this.id + '\');\n';
};
};
/**
* Generates a single block from a <block/> DOM element, adding it to the main workspace
* @param blockDOM {Element}
* @returns {*}
*/
exports.domToBlock = function (blockDOM) {
return Blockly.Xml.domToBlock(Blockly.mainBlockSpace, blockDOM);
};
/**
* Generates a single block from a block XML string—e.g., <block type="testBlock"></block>,
* and adds it to the main workspace
* @param blockDOMString
* @returns {*}
*/
exports.domStringToBlock = function (blockDOMString) {
return exports.domToBlock(xml.parseElement(blockDOMString).firstChild);
};
/**
* Takes a set of start blocks, and returns them with a particular top level
* block inserted in front of the first non-function block. If we already have
* this block, does nothing.
*/
exports.forceInsertTopBlock = function (input, blockType) {
input = input || '';
if (blockType === null || input.indexOf(blockType) !== -1) {
return input;
}
var root = xml.parseElement(input);
// Extract the document from the root. The reason I do this instead of just
// using document.createElement elsewhere is
var doc = root.parentNode;
var topBlock = doc.createElement('block');
topBlock.setAttribute('type', blockType);
topBlock.setAttribute('movable', 'false');
topBlock.setAttribute('deletable', 'false');
var numChildren = root.childNodes ? root.childNodes.length : 0;
// find the first non-function definition block and extract it
var firstBlock = null, i = 0;
while (i < numChildren && firstBlock === null) {
var child = root.childNodes[i];
// only look at element nodes
if (child.nodeType === 1) {
var type = child.getAttribute('type');
if (type !== 'procedures_defnoreturn' && type !== 'procedures_defreturn') {
firstBlock = root.removeChild(child);
numChildren--;
}
}
i++;
}
if (firstBlock !== null) {
// when run -> next -> firstBlock
var next;
if (/^functional/.test(blockType)) {
next = doc.createElement('functional_input');
next.setAttribute('name', 'ARG1');
} else {
next = doc.createElement('next');
}
next.appendChild(firstBlock);
topBlock.appendChild(next);
}
if (numChildren > 0) {
root.insertBefore(topBlock, root.childNodes[0]);
} else {
root.appendChild(topBlock);
}
return xml.serialize(root);
};
/**
* Generate the xml for a block for the calc app.
* @param {string} type Type for this block
* @param {number[]|string[]} args List of args, where each arg is either the
* xml for a child block, a number, or the name of a variable.
*/
exports.calcBlockXml = function (type, args) {
var str = '<block type="' + type + '" inline="false">';
for (var i = 1; i <= args.length; i++) {
str += '<functional_input name="ARG' + i + '">';
var arg = args[i - 1];
if (typeof(arg) === "number") {
arg = '<block type="functional_math_number"><title name="NUM">' + arg +
'</title></block>';
} else if (/^<block/.test(arg)) {
// we have xml, dont make any changes
} else {
// we think we have a variable
arg = exports.calcBlockGetVar(arg);
}
str += arg;
str += '</functional_input>';
}
str += '</block>';
return str;
};
/**
* @returns the xml for a functional_parameters_get block with the given
* variableName
*/
exports.calcBlockGetVar = function (variableName) {
return '' +
'<block type="functional_parameters_get" uservisible="false">' +
' <mutation>' +
' <outputtype>Number</outputtype>' +
' </mutation>' +
' <title name="VAR">' + variableName + '</title>' +
'</block>';
};
/**
* Generate the xml for a math block (either calc or eval apps).
* @param {string} type Type for this block
* @param {Object.<string,string} inputs Dictionary mapping input name to the
xml for that input
* @param {Object.<string.string>} [titles] Dictionary of titles mapping name to value
*/
exports.mathBlockXml = function (type, inputs, titles) {
var str = '<block type="' + type + '" inline="false">';
for (var title in titles) {
str += '<title name="' + title + '">' + titles[title] + '</title>';
}
for (var input in inputs) {
str += '<functional_input name="' + input + '">' + inputs[input] + '</functional_input>';
}
str += '</block>';
return str;
};
/**
* Generate xml for a functional defintion
* @param {string} name The name of the function
* @param {string} outputType Function's output type
* @param {Object<string, string>[]} argList Name and type for each arg
* @param {string} blockXml Xml for the blocks that actually define the function
*/
exports.functionalDefinitionXml = function (name, outputType, argList, blockXml) {
var mutation = '<mutation>';
argList.forEach(function (argInfo) {
mutation += '<arg name="' + argInfo.name + '" type="' + argInfo.type + '"></arg>';
});
mutation += '<outputtype>' + outputType + '</outputtype></mutation>';
return '<block type="functional_definition" inline="false">'+
mutation +
'<title name="NAME">' + name + '</title>' +
'<functional_input name="STACK">' + blockXml + '</functional_input>' +
'</block>';
};
/**
* Generate xml for a calling a functional function
* @param {string} name The name of the function
* @param {Object<string, string>[]} argList Name and type for each arg
*/
exports.functionalCallXml = function (name, argList, inputContents) {
if (argList.length !== inputContents.length) {
throw new Error('must define contents for each arg');
}
var mutation = '<mutation name="' + name + '">';
argList.forEach(function (argInfo) {
mutation += '<arg name="' + argInfo.name + '" type="' + argInfo.type + '"></arg>';
});
mutation += '</mutation>';
var contents = '';
inputContents.forEach(function (blockXml, index) {
contents += '<functional_input name="ARG' + index + '">' + blockXml + '</functional_input>';
});
return '<block type="functional_call">' +
mutation +
contents +
'</block>';
};
/**
* Removes all the deletable, movable, and uservisible attributes from the
* blocks in blocksDom.
*/
exports.cleanBlocks = function (blocksDom) {
xml.visitAll(blocksDom, block => {
if (!block.getAttribute) {
return;
}
ATTRIBUTES_TO_CLEAN.forEach(attr => block.removeAttribute(attr));
});
};
const DROPDOWN_INPUT = 'dropdown';
const VALUE_INPUT = 'value';
const DUMMY_INPUT = 'dummy';
/**
* Given block text with input names specified in curly braces, returns a list
* of labeled inputs that should be added to the block.
*
* @param {string} text The complete message shown on the block with inputs in
* curly braces, e.g. "Move the {SPRITE} {PIXELS} to the {DIR}"
* @param {Object[]} args Define the type/options of the block's inputs.
* @param {string} args[].name Input name, conventionally all-caps
* @param {string[][]} args[].options For dropdowns, the list of options. Each
* entry is a 2-element string array with the display name first, and the
* codegen-compatible (i.e. strings should be doubly-quoted) value second.
* @param {BlockValueType} args[].type For value inputs, the type required. Use
* BlockValueType.NONE to accept any block.
*
* @returns {Object[]} a list of labeled inputs. Each one has the same fields
* as 'args', but additionally includes:
* @returns {string} return[].mode Either 'dropdown', 'value', or 'dummy'
* @returns {string} return[].label Text to display to the left of the input
*/
const determineInputs = function (text, args) {
const tokens = text.split(/[{}]/);
if (tokens[tokens.length - 1] === '') {
tokens.pop();
}
const inputs = [];
for (let i = 0; i < tokens.length; i += 2) {
const label = tokens[i];
const input = tokens[i + 1];
if (input) {
const arg = args.find(arg => arg.name === input);
if (arg.options) {
inputs.push({
mode: DROPDOWN_INPUT,
name: arg.name,
options: arg.options,
label,
});
} else if (arg.type) {
inputs.push({
mode: VALUE_INPUT,
name: arg.name,
type: arg.type,
label,
});
}
} else {
inputs.push({
mode: DUMMY_INPUT,
label,
});
}
}
return inputs;
};
exports.determineInputs = determineInputs;
/**
* Adds the specified inputs to the block
* @param {Blockly} blockly The Blockly object provided to install()
* @param {Block} block The block to add the inputs to
* @param {Object[]} inputs The list of inputs. See determineInputs() for
* the fields in each input.
*/
const interpolateInputs = function (blockly, block, inputs) {
inputs.map(input => {
let dropdown;
switch (input.mode) {
case DROPDOWN_INPUT:
dropdown = new blockly.FieldDropdown(input.options);
block.appendDummyInput()
.appendTitle(input.label)
.appendTitle(dropdown, input.name);
break;
case VALUE_INPUT:
block.appendValueInput(input.name)
.setCheck(input.type)
.appendTitle(input.label);
break;
case DUMMY_INPUT:
block.appendDummyInput()
.appendTitle(input.label);
break;
}
});
};
exports.interpolateInputs = interpolateInputs;
/**
* Add pre-labeled inputs
* @param {Blockly} blockly The Blockly object provided to install()
* @param {Block} block The block to add the inputs to
* @param {Object[]} args The list of inputs
* @param {String} args[].name The name for this input, conventionally all-caps
* @param {String} args[].type The type for this input, defaults to allowing any
* type
* @param {String} args[].label The text to display to the left of the input
*/
const addInputs = function (blockly, block, args) {
block.appendDummyInput()
.appendTitle('show title screen');
args.forEach(arg => {
block.appendValueInput(arg.name)
.setCheck(arg.type || Blockly.BlockValueType.NONE)
.setAlign(Blockly.ALIGN_RIGHT)
.appendTitle(arg.label);
});
};
/**
* Create a block generator that creats blocks that directly map to a javascript
* function call, method call, or other (hopefully simple) expression.
*
* @params {Blockly} blockly The Blockly object provided to install()
* @params {string} blocksModuleName Module name that will be prefixed to all
* the block names
* @returns {function} A function that takes a bunch of block properties and
* adds a block to the blockly.Blocks object. See param documentation below.
*/
exports.createJsWrapperBlockCreator = function (
blockly,
blocksModuleName
) {
const {
ORDER_COMMA,
ORDER_FUNCTION_CALL,
ORDER_MEMBER,
ORDER_NONE,
} = Blockly.JavaScript;
const generator = blockly.Generator.get('JavaScript');
/**
* Create a block that directly maps to a javascript function call, method
* call, or other (hopefully simple) expression.
*
* @param {Object} opts Block options
* @param {number[]} opts.color HSV block color as a 3-element number array
* @param {string} opts.func For function/method calls, the function name
* @param {string} opts.expression Instead of specifying func, use this param
* to specify an arbitrary javascript expression instead
* @param {number} opts.orderPrecedence For expressions, the minimum binding
* strength of any operators in the expression. You can omit this, and the
* code generator code will just wrap the expression in parens, see:
* https://developers.google.com/blockly/guides/create-custom-blocks/operator-precedence
* @param {string} opts.name Block name, defaults to func.
* @param {string} opts.blockText Human-readable text to show on the block,
* with params specified in curly braces, see determineInputs()
* @param {Object[]} opts.args List of block inputs, see determineInputs()
* @param {BlockValueType} opts.returnType Type of value returned by this
* block, omit if you want a block with no output.
* @param {boolean} opts.methodCall Generate a method call. The blockText
* should contain '{THIS}' in order to create an input for the instance
* @param {boolean} opts.eventBlock Generate an event block, which is just a
* block without a previous statement connector.
* @param {boolean} opts.eventLoopBlock Generate an "event loop" block, which
* looks like a loop block but without previous or next statement connectors
* @param {boolean} opts.inline Render inputs inline, defaults to false
*/
return ({
color,
func,
expression,
orderPrecedence,
name,
blockText,
args,
returnType,
methodCall,
eventBlock,
eventLoopBlock,
inline,
}) => {
if (!func === !expression) {
throw new Error('Provide either func or expression, but not both');
}
if (expression && !name) {
throw new Error('Expression blocks require a name');
}
args = args || [];
const blockName = `${blocksModuleName}_${name || func}`;
blockly.Blocks[blockName] = {
helpUrl: '',
init: function () {
this.setHSV(...color);
const inputs = [...args];
if (methodCall) {
inputs.push({
name: 'THIS',
type: Blockly.BlockValueType.NONE,
});
}
if (inline === false) {
addInputs(blockly, this, args);
} else {
interpolateInputs(blockly, this, determineInputs(blockText, inputs));
this.setInputsInline(true);
}
if (returnType) {
this.setOutput(true, returnType);
} else if (eventLoopBlock) {
this.appendStatementInput('DO');
} else if (eventBlock) {
this.setNextStatement(true);
this.skipNextBlockGeneration = true;
} else {
this.setNextStatement(true);
this.setPreviousStatement(true);
}
},
};
generator[blockName] = function () {
const values = args.map(arg => {
if (arg.options) {
return this.getTitleValue(arg.name);
} else {
return Blockly.JavaScript.valueToCode(this, arg.name, ORDER_COMMA);
}
});
let prefix = '';
if (methodCall) {
const object =
Blockly.JavaScript.valueToCode(this, 'THIS', ORDER_MEMBER);
prefix = `${object}.`;
}
if (eventLoopBlock || eventBlock) {
let handlerCode = '';
if (eventBlock) {
const nextBlock = this.nextConnection &&
this.nextConnection.targetBlock();
handlerCode = Blockly.JavaScript.blockToCode(nextBlock, true);
handlerCode = Blockly.Generator.prefixLines(handlerCode, ' ');
} else if (eventLoopBlock) {
handlerCode = Blockly.JavaScript.statementToCode(this, 'DO');
}
values.push(`function () {\n${handlerCode}}`);
}
if (expression) {
if (returnType !== undefined) {
return [`${prefix}${expression}`, orderPrecedence || ORDER_NONE];
} else {
return `${prefix}${expression}`;
}
}
if (returnType !== undefined) {
return [`${prefix}${func}(${values.join(', ')})`, ORDER_FUNCTION_CALL];
} else {
return `${prefix}${func}(${values.join(', ')});\n`;
}
};
};
};