forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposablemutations.ts
More file actions
490 lines (408 loc) · 18.8 KB
/
Copy pathcomposablemutations.ts
File metadata and controls
490 lines (408 loc) · 18.8 KB
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
/// <reference path="../localtypings/blockly.d.ts" />
declare namespace Blockly.Xml {
function domToBlock(xml: Element, workspace: Blockly.Workspace): Blockly.Block;
}
namespace pxt.blocks {
export interface ComposableMutation {
// Set to save mutations. Should return an XML element
mutationToDom(mutationElement: Element): Element;
// Set to restore mutations from save
domToMutation(savedElement: Element): void;
}
export function appendMutation(block: Blockly.Block, mutation: ComposableMutation) {
const b = block as MutatingBlock;
const oldMTD = b.mutationToDom;
const oldDTM = b.domToMutation;
b.mutationToDom = () => {
const el = oldMTD ? oldMTD() : document.createElement("mutation");
return mutation.mutationToDom(el);
};
b.domToMutation = saved => {
if (oldDTM) {
oldDTM(saved);
}
mutation.domToMutation(saved);
}
}
export function initVariableArgsBlock(b: Blockly.Block, handlerArgs: pxt.blocks.HandlerArg[]) {
let currentlyVisible = 0;
let actuallyVisible = 0;
let i = b.appendDummyInput();
let updateShape = () => {
if (currentlyVisible === actuallyVisible) {
return;
}
if (currentlyVisible > actuallyVisible) {
const diff = currentlyVisible - actuallyVisible;
for (let j = 0; j < diff; j++) {
const arg = handlerArgs[actuallyVisible + j];
i.insertFieldAt(i.fieldRow.length - 1, new pxtblockly.FieldArgumentVariable(arg.name), "HANDLER_" + arg.name);
const blockSvg = b as Blockly.BlockSvg;
if (blockSvg?.initSvg) blockSvg.initSvg(); // call initSvg on block to initialize new fields
}
}
else {
let diff = actuallyVisible - currentlyVisible;
for (let j = 0; j < diff; j++) {
const arg = handlerArgs[actuallyVisible - j - 1];
i.removeField("HANDLER_" + arg.name);
}
}
if (currentlyVisible >= handlerArgs.length) {
i.removeField("_HANDLER_ADD");
}
else if (actuallyVisible >= handlerArgs.length) {
addPlusButton();
}
actuallyVisible = currentlyVisible;
};
Blockly.Extensions.apply('inline-svgs', b, false);
addPlusButton();
appendMutation(b, {
mutationToDom: (el: Element) => {
el.setAttribute("numArgs", currentlyVisible.toString());
for (let j = 0; j < currentlyVisible; j++) {
const varField = b.getField("HANDLER_" + handlerArgs[j].name);
let varName = varField && varField.getText();
el.setAttribute("arg" + j, varName);
}
return el;
},
domToMutation: (saved: Element) => {
let numArgs = parseInt(saved.getAttribute("numargs"));
currentlyVisible = Math.min(isNaN(numArgs) ? 0 : numArgs, handlerArgs.length);
updateShape();
for (let j = 0; j < currentlyVisible; j++) {
const varName = saved.getAttribute("arg" + j);
const fieldName = "HANDLER_" + handlerArgs[j].name;
if (b.getField(fieldName)) {
setVarFieldValue(b, fieldName, varName);
}
}
}
});
function addPlusButton() {
i.appendField(new Blockly.FieldImage((b as any).ADD_IMAGE_DATAURI, 24, 24, lf("Add argument"),
() => {
currentlyVisible = Math.min(currentlyVisible + 1, handlerArgs.length);
updateShape();
}, false), "_HANDLER_ADD");
}
}
export function initExpandableBlock(info: pxtc.BlocksInfo, b: Blockly.Block, def: pxtc.ParsedBlockDef, comp: BlockCompileInfo, toggle: boolean, addInputs: () => void) {
// Add numbers before input names to prevent clashes with the ones added
// by BlocklyLoader. The number makes it an invalid JS identifier
const buttonAddName = "0_add_button";
const buttonRemName = "0_rem_button";
const numVisibleAttr = "_expanded";
const inputInitAttr = "_input_init";
const optionNames = def.parameters.map(p => p.name);
const totalOptions = def.parameters.length;
const buttonDelta = toggle ? totalOptions : 1;
const state = new MutationState(b as MutatingBlock);
state.setEventsEnabled(false);
state.setValue(numVisibleAttr, 0);
state.setValue(inputInitAttr, false);
state.setEventsEnabled(true);
Blockly.Extensions.apply('inline-svgs', b, false);
addPlusButton();
appendMutation(b, {
mutationToDom: (el: Element) => {
// The reason we store the inputsInitialized variable separately from visibleOptions
// is because it's possible for the block to get into a state where all inputs are
// initialized but they aren't visible (i.e. the user hit the - button). Blockly
// gets upset if a block has a different number of inputs when it is saved and restored.
el.setAttribute(numVisibleAttr, state.getString(numVisibleAttr));
el.setAttribute(inputInitAttr, state.getString(inputInitAttr));
return el;
},
domToMutation: (saved: Element) => {
state.setEventsEnabled(false);
if (saved.hasAttribute(inputInitAttr) && saved.getAttribute(inputInitAttr) == "true" && !state.getBoolean(inputInitAttr)) {
state.setValue(inputInitAttr, true)
initOptionalInputs();
}
if (saved.hasAttribute(numVisibleAttr)) {
const val = parseInt(saved.getAttribute(numVisibleAttr));
if (!isNaN(val)) {
const delta = val - (state.getNumber(numVisibleAttr) || 0);
if (state.getBoolean(inputInitAttr)) {
if ((b as Blockly.BlockSvg).rendered || b.isInsertionMarker()) {
updateShape(delta, true, b.isInsertionMarker());
}
else {
state.setValue(numVisibleAttr, addDelta(delta));
}
}
else {
updateShape(delta, true);
}
}
}
state.setEventsEnabled(true);
}
});
// Blockly only lets you hide an input once it is rendered, so we can't
// hide the inputs in init() or domToMutation(). This will get executed after
// the block is rendered
setTimeout(() => {
if ((b as Blockly.BlockSvg).rendered && !(b.workspace as Blockly.WorkspaceSvg).isDragging()) {
updateShape(0, undefined, true);
}
}, 1);
// Set skipRender to true if the block is still initializing. Otherwise
// the inputs will render before their shadow blocks are created and
// leave behind annoying artifacts
function updateShape(delta: number, skipRender = false, force = false) {
const newValue = addDelta(delta);
if (!force && !skipRender && newValue === state.getNumber(numVisibleAttr)) return;
state.setValue(numVisibleAttr, newValue);
const visibleOptions = newValue;
if (!state.getBoolean(inputInitAttr) && visibleOptions > 0) {
initOptionalInputs();
if (!(b as Blockly.BlockSvg).rendered) {
return;
}
}
let optIndex = 0
for (let i = 0; i < b.inputList.length; i++) {
const input = b.inputList[i];
if (Util.startsWith(input.name, optionalDummyInputPrefix)) {
// The behavior for dummy inputs (i.e. labels) is that whenever a parameter is revealed,
// all earlier labels are made visible as well. If the parameter is the last one in the
// block then all labels are made visible
setInputVisible(input, optIndex < visibleOptions || visibleOptions === totalOptions);
}
else if (Util.startsWith(input.name, optionalInputWithFieldPrefix) || optionNames.indexOf(input.name) !== -1) {
const visible = optIndex < visibleOptions;
setInputVisible(input, visible);
if (visible && input.connection && !(input.connection as any).isConnected() && !b.isInsertionMarker()) {
const param = comp.definitionNameToParam[def.parameters[optIndex].name];
let shadow = createShadowValue(info, param);
if (shadow.tagName.toLowerCase() === "value") {
// Unwrap the block
shadow = shadow.firstElementChild;
}
Blockly.Events.disable();
try {
const nb = Blockly.Xml.domToBlock(shadow, b.workspace);
if (nb) {
input.connection.connect(nb.outputConnection);
}
} catch (e) { }
Blockly.Events.enable();
}
++optIndex;
}
}
updateButtons();
if (!skipRender) (b as Blockly.BlockSvg).render();
}
function addButton(name: string, uri: string, alt: string, delta: number) {
b.appendDummyInput(name)
.appendField(new Blockly.FieldImage(uri, 24, 24, alt, () => updateShape(delta), false))
}
function updateButtons() {
const visibleOptions = state.getNumber(numVisibleAttr);
const showPlus = visibleOptions !== totalOptions;
const showMinus = visibleOptions !== 0;
const hasMinus = !!b.getInput(buttonRemName);
const hasPlus = !!b.getInput(buttonAddName);
if (!showPlus) {
b.removeInput(buttonAddName, true);
}
if (!showMinus) {
b.removeInput(buttonRemName, true);
}
if (showMinus && !hasMinus) {
addMinusButton();
}
if (showPlus) {
// make sure plus button is last in line.
if (hasPlus && b.inputList.findIndex(el => el.name === buttonAddName) !== b.inputList.length - 1) {
b.removeInput(buttonAddName, true);
addPlusButton();
} else if (!hasPlus) {
addPlusButton();
}
}
}
function addPlusButton() {
addButton(buttonAddName, (b as any).ADD_IMAGE_DATAURI, lf("Reveal optional arguments"), buttonDelta);
}
function addMinusButton() {
addButton(buttonRemName, (b as any).REMOVE_IMAGE_DATAURI, lf("Hide optional arguments"), -1 * buttonDelta);
}
function initOptionalInputs() {
state.setValue(inputInitAttr, true);
addInputs();
updateButtons();
}
function addDelta(delta: number) {
return Math.min(Math.max(state.getNumber(numVisibleAttr) + delta, 0), totalOptions);
}
function setInputVisible(input: Blockly.Input, visible: boolean) {
// If the block isn't rendered, Blockly will crash
if ((b as Blockly.BlockSvg).rendered) {
let renderList = input.setVisible(visible);
renderList.forEach((block: Blockly.BlockSvg) => {
block.render();
});
}
}
}
export function initReturnStatement(b: Blockly.Block) {
const returnDef = pxt.blocks.getBlockDefinition("function_return");
const buttonAddName = "0_add_button";
const buttonRemName = "0_rem_button";
Blockly.Extensions.apply('inline-svgs', b, false);
let returnValueVisible = true;
// When the value input is removed, we disconnect the block that was connected to it. This
// is the id of whatever block was last connected
let lastConnectedId: string;
updateShape();
b.domToMutation = saved => {
if (saved.hasAttribute("last_connected_id")) {
lastConnectedId = saved.getAttribute("last_connected_id");
}
returnValueVisible = hasReturnValue(saved);
updateShape();
}
b.mutationToDom = () => {
const mutation = document.createElement("mutation");
setReturnValue(mutation, !!b.getInput("RETURN_VALUE"));
if (lastConnectedId) {
mutation.setAttribute("last_connected_id", lastConnectedId);
}
return mutation;
}
function updateShape() {
const returnValueInput = b.getInput("RETURN_VALUE");
if (returnValueVisible) {
if (!returnValueInput) {
// Remove any labels
while (b.getInput("")) b.removeInput("");
b.jsonInit({
"message0": returnDef.block["message_with_value"],
"args0": [
{
"type": "input_value",
"name": "RETURN_VALUE",
"check": null
}
],
"previousStatement": null,
"colour": pxt.toolbox.getNamespaceColor('functions')
});
}
if (b.getInput(buttonAddName)) {
b.removeInput(buttonAddName);
}
if (!b.getInput(buttonRemName)) {
addMinusButton();
}
if (lastConnectedId) {
const lastConnected = b.workspace.getBlockById(lastConnectedId);
if (lastConnected && lastConnected.outputConnection && !lastConnected.outputConnection.targetBlock()) {
b.getInput("RETURN_VALUE").connection.connect(lastConnected.outputConnection);
}
lastConnectedId = undefined;
}
}
else {
if (returnValueInput) {
const target = returnValueInput.connection.targetBlock()
if (target) {
if (target.isShadow()) target.setShadow(false);
returnValueInput.connection.disconnect();
lastConnectedId = target.id;
}
b.removeInput("RETURN_VALUE");
b.jsonInit({
"message0": returnDef.block["message_no_value"],
"args0": [],
"previousStatement": null,
"colour": pxt.toolbox.getNamespaceColor('functions')
})
}
if (b.getInput(buttonRemName)) {
b.removeInput(buttonRemName);
}
if (!b.getInput(buttonAddName)) {
addPlusButton();
}
}
b.setInputsInline(true);
}
function setReturnValue(mutation: Element, hasReturnValue: boolean) {
mutation.setAttribute("no_return_value", hasReturnValue ? "false" : "true")
}
function hasReturnValue(mutation: Element) {
return mutation.getAttribute("no_return_value") !== "true"
}
function addPlusButton() {
addButton(buttonAddName, (b as any).ADD_IMAGE_DATAURI, lf("Add return value"));
}
function addMinusButton() {
addButton(buttonRemName, (b as any).REMOVE_IMAGE_DATAURI, lf("Remove return value"));
}
function mutationString() {
return Blockly.Xml.domToText(b.mutationToDom());
}
function fireMutationChange(pre: string, post: string) {
if (pre !== post)
Blockly.Events.fire(new Blockly.Events.BlockChange(b, "mutation", null, pre, post));
}
function addButton(name: string, uri: string, alt: string) {
b.appendDummyInput(name)
.appendField(new Blockly.FieldImage(uri, 24, 24, alt, () => {
const oldMutation = mutationString();
returnValueVisible = !returnValueVisible;
const preUpdate = mutationString()
fireMutationChange(oldMutation, preUpdate);
updateShape();
const postUpdate = mutationString();
fireMutationChange(preUpdate, postUpdate);
}, false))
}
}
class MutationState {
private state: pxt.Map<string>;
private fireEvents = true;
constructor(public block: MutatingBlock, initState?: pxt.Map<string>) {
this.state = initState || {};
}
setValue(attr: string, value: boolean | number | string) {
if (this.fireEvents && this.block.mutationToDom) {
const oldMutation = this.block.mutationToDom();
this.state[attr] = value.toString();
const newMutation = this.block.mutationToDom();
Object.keys(this.state).forEach(key => {
if (oldMutation.getAttribute(key) !== this.state[key]) {
newMutation.setAttribute(key, this.state[key]);
}
});
const oldText = Blockly.Xml.domToText(oldMutation);
const newText = Blockly.Xml.domToText(newMutation);
if (oldText != newText) {
Blockly.Events.fire(new Blockly.Events.BlockChange(this.block, "mutation", null, oldText, newText));
}
}
else {
this.state[attr] = value.toString();
}
}
getNumber(attr: string) {
return parseInt(this.state[attr]);
}
getBoolean(attr: string) {
return this.state[attr] != "false";
}
getString(attr: string) {
return this.state[attr];
}
setEventsEnabled(enabled: boolean) {
this.fireEvents = enabled;
}
}
}