forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocklyloader.ts
More file actions
3094 lines (2774 loc) · 130 KB
/
blocklyloader.ts
File metadata and controls
3094 lines (2774 loc) · 130 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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="../localtypings/blockly.d.ts" />
/// <reference path="../built/pxtlib.d.ts" />
namespace pxt.blocks {
export let promptTranslateBlock: (blockId: string, blockTranslationIds: string[]) => void;
export interface GrayBlock extends Blockly.Block {
setPythonEnabled(enabled: boolean): void;
}
export interface GrayBlockStatement extends GrayBlock {
domToMutation(xmlElement: Element): void;
mutationToDom(): Element;
getLines: () => string[];
declaredVariables: string;
}
// Parsed format of data stored in the .data attribute of blocks
export interface PXTBlockData {
commentRefs: string[];
fieldData: pxt.Map<string>;
}
const typeDefaults: Map<{ field: string, block: string, defaultValue: string }> = {
"string": {
field: "TEXT",
block: "text",
defaultValue: ""
},
"number": {
field: "NUM",
block: "math_number",
defaultValue: "0"
},
"boolean": {
field: "BOOL",
block: "logic_boolean",
defaultValue: "false"
},
"Array": {
field: "VAR",
block: "variables_get",
defaultValue: "list"
}
}
// Add numbers before input names to prevent clashes with the ones added by BlocklyLoader
export const optionalDummyInputPrefix = "0_optional_dummy";
export const optionalInputWithFieldPrefix = "0_optional_field";
// Matches arrays
export function isArrayType(type: string): string {
const arrayTypeRegex = /^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/;
let parsed = arrayTypeRegex.exec(type);
if (parsed) {
// Is an array, returns what type it is an array of
if (parsed[1]) {
// Is an array with form Array<type>
return parsed[1];
} else {
// Is an array with form type[]
return parsed[2];
}
} else {
// Not an array
return undefined;
}
}
// Matches tuples
export function isTupleType(type: string): string[] {
const tupleTypeRegex = /^\[(.+)\]$/;
let parsed = tupleTypeRegex.exec(type);
if (parsed) {
// Returns an array containing the types of the tuple
return parsed[1].split(/,\s*/);
} else {
// Not a tuple
return undefined;
}
}
const primitiveTypeRegex = /^(string|number|boolean)$/;
type NamedField = { field: Blockly.Field, name?: string };
// list of built-in blocks, should be touched.
let _builtinBlocks: Map<{
block: Blockly.BlockDefinition;
symbol?: pxtc.SymbolInfo;
}>;
export function builtinBlocks() {
if (!_builtinBlocks) {
_builtinBlocks = {};
Object.keys(Blockly.Blocks)
.forEach(k => _builtinBlocks[k] = { block: Blockly.Blocks[k] });
}
return _builtinBlocks;
}
export const buildinBlockStatements: Map<boolean> = {
"controls_if": true,
"controls_for": true,
"pxt_controls_for": true,
"controls_simple_for": true,
"controls_repeat_ext": true,
"pxt_controls_for_of": true,
"controls_for_of": true,
"variables_set": true,
"variables_change": true,
"device_while": true
}
// Cached block info from the last inject operation
let cachedBlockInfo: pxtc.BlocksInfo;
// blocks cached
interface CachedBlock {
hash: string;
fn: pxtc.SymbolInfo;
block: Blockly.BlockDefinition;
}
let cachedBlocks: Map<CachedBlock> = {};
export function blockSymbol(type: string): pxtc.SymbolInfo {
let b = cachedBlocks[type];
return b ? b.fn : undefined;
}
export function createShadowValue(info: pxtc.BlocksInfo, p: pxt.blocks.BlockParameter, shadowId?: string, defaultV?: string): Element {
defaultV = defaultV || p.defaultValue;
shadowId = shadowId || p.shadowBlockId;
if (!shadowId && p.range) shadowId = "math_number_minmax";
let defaultValue: any;
if (defaultV && defaultV.slice(0, 1) == "\"")
defaultValue = JSON.parse(defaultV);
else {
defaultValue = defaultV;
}
if (p.type == "number" && shadowId == "value") {
const field = document.createElement("field");
field.setAttribute("name", p.definitionName);
field.appendChild(document.createTextNode("0"));
return field;
}
const isVariable = shadowId == "variables_get";
const isText = shadowId == "text";
const value = document.createElement("value");
value.setAttribute("name", p.definitionName);
const isArray = isArrayType(p.type);
const shadow = document.createElement(isVariable || isArray ? "block" : "shadow");
value.appendChild(shadow);
const typeInfo = typeDefaults[isArray || p.type];
shadow.setAttribute("type", shadowId || (isArray ? 'lists_create_with' : typeInfo && typeInfo.block || p.type));
shadow.setAttribute("colour", (Blockly as any).Colours.textField);
if (isArray) {
// if an array of booleans, numbers, or strings
if (typeInfo && !shadowId) {
let fieldValues: string[];
switch (isArray) {
case "number":
fieldValues = ["0", "1"];
break;
case "string":
fieldValues = ["a", "b", "c"];
break;
case "boolean":
fieldValues = ["FALSE", "FALSE", "FALSE"];
break;
}
buildArrayShadow(shadow, typeInfo.block, typeInfo.field, fieldValues);
return value;
}
else if (shadowId && defaultValue) {
buildArrayShadow(shadow, defaultValue);
return value;
}
}
if (typeInfo && (!shadowId || typeInfo.block === shadowId || shadowId === "math_number_minmax")) {
const field = document.createElement("field");
shadow.appendChild(field);
let fieldName: string;
switch (shadowId) {
case "variables_get":
fieldName = "VAR"; break;
case "math_number_minmax":
fieldName = "SLIDER"; break;
default:
fieldName = typeInfo.field; break;
}
field.setAttribute("name", fieldName);
let value: Text;
if (p.type == "boolean") {
value = document.createTextNode((defaultValue || typeInfo.defaultValue).toUpperCase())
}
else {
value = document.createTextNode(defaultValue || typeInfo.defaultValue)
}
field.appendChild(value);
}
else if (defaultValue) {
const field = document.createElement("field");
field.textContent = defaultValue;
if (isVariable) {
field.setAttribute("name", "VAR");
shadow.appendChild(field);
}
else if (isText) {
field.setAttribute("name", "TEXT");
shadow.appendChild(field);
}
else if (shadowId) {
const shadowInfo = info.blocksById[shadowId];
if (shadowInfo && shadowInfo.attributes._def && shadowInfo.attributes._def.parameters.length) {
const shadowParam = shadowInfo.attributes._def.parameters[0];
field.setAttribute("name", shadowParam.name);
shadow.appendChild(field);
}
}
else {
field.setAttribute("name", p.definitionName);
shadow.appendChild(field);
}
}
let mut: HTMLElement;
if (p.range) {
mut = document.createElement('mutation');
mut.setAttribute('min', p.range.min.toString());
mut.setAttribute('max', p.range.max.toString());
mut.setAttribute('label', p.actualName.charAt(0).toUpperCase() + p.actualName.slice(1));
if (p.fieldOptions) {
if (p.fieldOptions['step']) mut.setAttribute('step', p.fieldOptions['step']);
if (p.fieldOptions['color']) mut.setAttribute('color', p.fieldOptions['color']);
if (p.fieldOptions['precision']) mut.setAttribute('precision', p.fieldOptions['precision']);
}
}
if (p.fieldOptions) {
if (!mut) mut = document.createElement('mutation');
mut.setAttribute(`customfield`, JSON.stringify(p.fieldOptions));
}
if (mut) {
shadow.appendChild(mut);
}
return value;
}
function buildArrayShadow(shadow: Element, blockType: string, fieldName?: string, fieldValues?: string[]) {
const itemCount = fieldValues ? fieldValues.length : 2;
const mut = document.createElement('mutation');
mut.setAttribute("items", "" + itemCount);
mut.setAttribute("horizontalafter", "" + itemCount);
shadow.appendChild(mut);
for (let i = 0; i < itemCount; i++) {
const innerValue = document.createElement("value");
innerValue.setAttribute("name", "ADD" + i);
const innerShadow = document.createElement("shadow");
innerShadow.setAttribute("type", blockType);
if (fieldName) {
const field = document.createElement("field");
field.setAttribute("name", fieldName);
if (fieldValues) {
field.appendChild(document.createTextNode(fieldValues[i]));
}
innerShadow.appendChild(field);
}
innerValue.appendChild(innerShadow);
shadow.appendChild(innerValue);
}
}
export function createFlyoutHeadingLabel(name: string, color?: string, icon?: string, iconClass?: string) {
const headingLabel = createFlyoutLabel(name, pxt.toolbox.convertColor(color), icon, iconClass);
headingLabel.setAttribute('web-class', 'blocklyFlyoutHeading');
return headingLabel;
}
export function createFlyoutGroupLabel(name: string, icon?: string, labelLineWidth?: string, helpCallback?: string) {
const groupLabel = createFlyoutLabel(name, undefined, icon);
groupLabel.setAttribute('web-class', 'blocklyFlyoutGroup');
groupLabel.setAttribute('web-line', '1.5');
if (labelLineWidth) groupLabel.setAttribute('web-line-width', labelLineWidth);
if (helpCallback) {
groupLabel.setAttribute('web-help-button', 'true');
groupLabel.setAttribute('callbackKey', helpCallback);
}
return groupLabel;
}
function createFlyoutLabel(name: string, color?: string, icon?: string, iconClass?: string): HTMLElement {
// Add the Heading label
let headingLabel = Blockly.utils.xml.createElement('label') as HTMLElement;
headingLabel.setAttribute('text', name);
if (color) {
headingLabel.setAttribute('web-icon-color', pxt.toolbox.convertColor(color));
}
if (icon) {
if (icon.length === 1) {
headingLabel.setAttribute('web-icon', icon);
if (iconClass) headingLabel.setAttribute('web-icon-class', iconClass);
}
else {
headingLabel.setAttribute('web-icon-class', `blocklyFlyoutIcon${name}`);
}
}
return headingLabel;
}
export function createFlyoutButton(callbackKey: string, label: string) {
let button = Blockly.utils.xml.createElement('button') as Element;
button.setAttribute('text', label);
button.setAttribute('callbackKey', callbackKey);
return button;
}
export function createToolboxBlock(info: pxtc.BlocksInfo, fn: pxtc.SymbolInfo, comp: pxt.blocks.BlockCompileInfo): HTMLElement {
//
// toolbox update
//
let block = document.createElement("block");
block.setAttribute("type", fn.attributes.blockId);
if (fn.attributes.blockGap)
block.setAttribute("gap", fn.attributes.blockGap);
else if (pxt.appTarget.appTheme && pxt.appTarget.appTheme.defaultBlockGap)
block.setAttribute("gap", pxt.appTarget.appTheme.defaultBlockGap.toString());
if (comp.thisParameter) {
const t = comp.thisParameter;
block.appendChild(createShadowValue(info, t, t.shadowBlockId || "variables_get", t.defaultValue || t.definitionName));
}
if (fn.parameters) {
comp.parameters.filter(pr => !pr.isOptional &&
(primitiveTypeRegex.test(pr.type)
|| primitiveTypeRegex.test(isArrayType(pr.type))
|| pr.shadowBlockId
|| pr.defaultValue))
.forEach(pr => {
block.appendChild(createShadowValue(info, pr));
})
if (fn.attributes.draggableParameters) {
comp.handlerArgs.forEach(arg => {
// draggableParameters="variable":
// <value name="HANDLER_DRAG_PARAM_arg">
// <shadow type="variables_get_reporter">
// <field name="VAR">defaultName</field>
// </shadow>
// </value>
// draggableParameters="reporter"
// <value name="HANDLER_DRAG_PARAM_arg">
// <shadow type="argument_reporter_custom">
// <mutation typename="Sprite"></mutation>
// <field name="VALUE">mySprite</field>
// </shadow>
// </value>
const useReporter = fn.attributes.draggableParameters === "reporter";
const value = document.createElement("value");
value.setAttribute("name", "HANDLER_DRAG_PARAM_" + arg.name);
const blockType = useReporter ? pxt.blocks.reporterTypeForArgType(arg.type) : "variables_get_reporter";
const shadow = document.createElement("shadow");
shadow.setAttribute("type", blockType);
if (useReporter && blockType === "argument_reporter_custom") {
const mutation = document.createElement("mutation");
mutation.setAttribute("typename", arg.type);
shadow.appendChild(mutation);
}
const field = document.createElement("field");
field.setAttribute("name", useReporter ? "VALUE" : "VAR");
field.textContent = Util.htmlEscape(arg.name);
shadow.appendChild(field);
value.appendChild(shadow);
block.appendChild(value);
});
}
else {
comp.handlerArgs.forEach(arg => {
const field = document.createElement("field");
field.setAttribute("name", "HANDLER_" + arg.name);
field.textContent = arg.name;
block.appendChild(field);
});
}
}
return block;
}
export function injectBlocks(blockInfo: pxtc.BlocksInfo): pxtc.SymbolInfo[] {
cachedBlockInfo = blockInfo;
Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(blockInfo.blocks.filter(fn => fn.attributes.duplicateShadowOnDrag).map(fn => fn.attributes.blockId));
// inject Blockly with all block definitions
return blockInfo.blocks
.map(fn => {
const comp = compileInfo(fn);
const block = createToolboxBlock(blockInfo, fn, comp);
if (fn.attributes.blockBuiltin) {
Util.assert(!!builtinBlocks()[fn.attributes.blockId]);
const builtin = builtinBlocks()[fn.attributes.blockId];
builtin.symbol = fn;
builtin.block.codeCard = mkCard(fn, block);
} else {
injectBlockDefinition(blockInfo, fn, comp, block);
}
return fn;
});
}
function injectBlockDefinition(info: pxtc.BlocksInfo, fn: pxtc.SymbolInfo, comp: pxt.blocks.BlockCompileInfo, blockXml: HTMLElement): boolean {
let id = fn.attributes.blockId;
if (builtinBlocks()[id]) {
pxt.reportError("blocks", 'trying to override builtin block', { "details": id });
return false;
}
let hash = JSON.stringify(fn);
if (cachedBlocks[id] && cachedBlocks[id].hash == hash) {
return true;
}
if (Blockly.Blocks[fn.attributes.blockId]) {
console.error("duplicate block definition: " + id);
return false;
}
let cachedBlock: CachedBlock = {
hash: hash,
fn: fn,
block: {
codeCard: mkCard(fn, blockXml),
init: function () { initBlock(this, info, fn, comp) }
}
}
if (pxt.Util.isTranslationMode()
&& pxt.blocks.promptTranslateBlock) {
cachedBlock.block.customContextMenu = (options: any[]) => {
if (fn.attributes.translationId) {
options.push({
enabled: true,
text: lf("Translate this block"),
callback: function () {
pxt.blocks.promptTranslateBlock(id, [fn.attributes.translationId]);
}
})
}
}
}
cachedBlocks[id] = cachedBlock;
Blockly.Blocks[id] = cachedBlock.block;
return true;
}
function newLabel(part: pxtc.BlockLabel | pxtc.BlockImage): Blockly.Field {
if (part.kind === "image") {
return iconToFieldImage(part.uri);
}
const txt = removeOuterSpace(part.text)
if (!txt) {
return undefined;
}
if (part.cssClass) {
return new Blockly.FieldLabel(txt, part.cssClass);
}
else if (part.style.length) {
return new pxtblockly.FieldStyledLabel(txt, {
bold: part.style.indexOf("bold") !== -1,
italics: part.style.indexOf("italics") !== -1,
blocksInfo: undefined
})
}
else {
return new Blockly.FieldLabel(txt, undefined);
}
}
function cleanOuterHTML(el: HTMLElement): string {
// remove IE11 junk
return el.outerHTML.replace(/^<\?[^>]*>/, '');
}
function mkCard(fn: pxtc.SymbolInfo, blockXml: HTMLElement): pxt.CodeCard {
return {
name: fn.namespace + '.' + fn.name,
shortName: fn.name,
description: fn.attributes.jsDoc,
url: fn.attributes.help ? 'reference/' + fn.attributes.help.replace(/^\//, '') : undefined,
blocksXml: `<xml xmlns="http://www.w3.org/1999/xhtml">${cleanOuterHTML(blockXml)}</xml>`,
}
}
function isSubtype(apis: pxtc.ApisInfo, specific: string, general: string) {
if (specific == general) return true
let inf = apis.byQName[specific]
if (inf && inf.extendsTypes)
return inf.extendsTypes.indexOf(general) >= 0
return false
}
function initBlock(block: Blockly.Block, info: pxtc.BlocksInfo, fn: pxtc.SymbolInfo, comp: pxt.blocks.BlockCompileInfo) {
const ns = (fn.attributes.blockNamespace || fn.namespace).split('.')[0];
const instance = fn.kind == pxtc.SymbolKind.Method || fn.kind == pxtc.SymbolKind.Property;
const nsinfo = info.apis.byQName[ns];
const color =
// blockNamespace overrides color on block
(fn.attributes.blockNamespace && nsinfo && nsinfo.attributes.color)
|| fn.attributes.color
|| (nsinfo && nsinfo.attributes.color)
|| pxt.toolbox.getNamespaceColor(ns)
|| 255;
if (fn.attributes.help) {
const helpUrl = fn.attributes.help.replace(/^\//, '');
if (/^github:/.test(helpUrl)) {
block.setHelpUrl(helpUrl);
} else if (helpUrl !== "none") {
block.setHelpUrl("/reference/" + helpUrl);
}
} else if (fn.pkg && !pxt.appTarget.bundledpkgs[fn.pkg]) {// added package
let anchor = fn.qName.toLowerCase().split('.');
if (anchor[0] == fn.pkg) anchor.shift();
block.setHelpUrl(`/pkg/${fn.pkg}#${encodeURIComponent(anchor.join('-'))}`)
}
block.setColour(color);
let blockShape = Blockly.OUTPUT_SHAPE_ROUND;
if (fn.retType == "boolean")
blockShape = Blockly.OUTPUT_SHAPE_HEXAGONAL;
block.setOutputShape(blockShape);
if (fn.attributes.undeletable)
block.setDeletable(false);
buildBlockFromDef(fn.attributes._def);
let hasHandler = false;
if (fn.attributes.mutate) {
addMutation(block as MutatingBlock, fn, fn.attributes.mutate);
}
else if (fn.attributes.defaultInstance) {
addMutation(block as MutatingBlock, fn, MutatorTypes.DefaultInstanceMutator);
}
else if (fn.attributes._expandedDef && fn.attributes.expandableArgumentMode !== "disabled") {
const shouldToggle = fn.attributes.expandableArgumentMode === "toggle";
initExpandableBlock(info, block, fn.attributes._expandedDef, comp, shouldToggle, () => buildBlockFromDef(fn.attributes._expandedDef, true));
}
else if (comp.handlerArgs.length) {
/**
* We support four modes for handler parameters: variable dropdowns,
* expandable variable dropdowns with +/- buttons (used for chat commands),
* draggable variable blocks, and draggable reporter blocks.
*/
hasHandler = true;
if (fn.attributes.optionalVariableArgs) {
initVariableArgsBlock(block, comp.handlerArgs);
}
else if (fn.attributes.draggableParameters) {
comp.handlerArgs.filter(a => !a.inBlockDef).forEach(arg => {
const i = block.appendValueInput("HANDLER_DRAG_PARAM_" + arg.name);
if (fn.attributes.draggableParameters == "reporter") {
i.setCheck(getBlocklyCheckForType(arg.type, info));
} else {
i.setCheck("Variable");
}
});
}
else {
let i = block.appendDummyInput();
comp.handlerArgs.filter(a => !a.inBlockDef).forEach(arg => {
i.appendField(new Blockly.FieldVariable(arg.name), "HANDLER_" + arg.name);
});
}
}
// Add mutation to save and restore custom field settings
appendMutation(block, {
mutationToDom: (el: Element) => {
block.inputList.forEach(input => {
input.fieldRow.forEach((fieldRow: Blockly.FieldCustom) => {
if (fieldRow.isFieldCustom_ && fieldRow.saveOptions) {
const getOptions = fieldRow.saveOptions();
if (getOptions) {
el.setAttribute(`customfield`, JSON.stringify(getOptions));
}
}
})
})
return el;
},
domToMutation: (saved: Element) => {
block.inputList.forEach(input => {
input.fieldRow.forEach((fieldRow: Blockly.FieldCustom) => {
if (fieldRow.isFieldCustom_ && fieldRow.restoreOptions) {
const options = JSON.parse(saved.getAttribute(`customfield`));
if (options) {
fieldRow.restoreOptions(options);
}
}
})
})
}
});
if (fn.attributes.imageLiteral) {
const columns = (fn.attributes.imageLiteralColumns || 5) * fn.attributes.imageLiteral;
const rows = fn.attributes.imageLiteralRows || 5;
const scale = fn.attributes.imageLiteralScale;
let ri = block.appendDummyInput();
ri.appendField(new pxtblockly.FieldMatrix("", { columns, rows, scale }), "LEDS");
}
if (fn.attributes.inlineInputMode === "external") {
block.setInputsInline(false);
}
else if (fn.attributes.inlineInputMode === "inline") {
block.setInputsInline(true);
}
else {
block.setInputsInline(!fn.parameters || (fn.parameters.length < 4 && !fn.attributes.imageLiteral));
}
const body = fn.parameters?.find(pr => pxtc.parameterTypeIsArrowFunction(pr));
if (body || hasHandler) {
block.appendStatementInput("HANDLER")
.setCheck(null);
block.setInputsInline(true);
}
setOutputCheck(block, fn.retType, info);
// hook up/down if return value is void
const hasHandlers = hasArrowFunction(fn);
block.setPreviousStatement(!(hasHandlers && !fn.attributes.handlerStatement) && fn.retType == "void");
block.setNextStatement(!(hasHandlers && !fn.attributes.handlerStatement) && fn.retType == "void");
block.setTooltip(/^__/.test(fn.namespace) ? "" : fn.attributes.jsDoc);
function buildBlockFromDef(def: pxtc.ParsedBlockDef, expanded = false) {
let anonIndex = 0;
let firstParam = !expanded && !!comp.thisParameter;
const inputs = splitInputs(def);
const imgConv = new ImageConverter()
if (fn.attributes.shim === "ENUM_GET" || fn.attributes.shim === "KIND_GET") {
if (comp.parameters.length > 1 || comp.thisParameter) {
console.warn(`Enum blocks may only have 1 parameter but ${fn.attributes.blockId} has ${comp.parameters.length}`);
return;
}
}
inputs.forEach(inputParts => {
const fields: NamedField[] = [];
let inputName: string;
let inputCheck: string | string[];
let hasParameter = false;
inputParts.forEach(part => {
if (part.kind !== "param") {
const f = newLabel(part);
if (f) {
fields.push({ field: f });
}
}
else if (fn.attributes.shim === "ENUM_GET") {
U.assert(!!fn.attributes.enumName, "Trying to create an ENUM_GET block without a valid enum name")
fields.push({
name: "MEMBER",
field: new pxtblockly.FieldUserEnum(info.enumsByName[fn.attributes.enumName])
});
return;
}
else if (fn.attributes.shim === "KIND_GET") {
fields.push({
name: "MEMBER",
field: new pxtblockly.FieldKind(info.kindsByName[fn.attributes.kindNamespace || fn.attributes.blockNamespace || fn.namespace])
});
return;
}
else {
// find argument
let pr = getParameterFromDef(part, comp, firstParam);
firstParam = false;
if (!pr) {
console.error("block " + fn.attributes.blockId + ": unknown parameter " + part.name + (part.ref ? ` (${part.ref})` : ""));
return;
}
if (isHandlerArg(pr)) {
inputName = "HANDLER_DRAG_PARAM_" + pr.name;
inputCheck = fn.attributes.draggableParameters === "reporter" ? getBlocklyCheckForType(pr.type, info) : "Variable";
return;
}
let typeInfo = U.lookup(info.apis.byQName, pr.type)
hasParameter = true;
const defName = pr.definitionName;
const actName = pr.actualName;
let isEnum = typeInfo && typeInfo.kind == pxtc.SymbolKind.Enum
let isFixed = typeInfo && !!typeInfo.attributes.fixedInstances && !pr.shadowBlockId;
let isConstantShim = !!fn.attributes.constantShim;
let isCombined = pr.type == "@combined@"
let customField = pr.fieldEditor;
let fieldLabel = defName.charAt(0).toUpperCase() + defName.slice(1);
let fieldType = pr.type;
if (isEnum || isFixed || isConstantShim || isCombined) {
let syms: pxtc.SymbolInfo[];
if (isEnum) {
syms = getEnumDropdownValues(info.apis, pr.type);
}
else if (isFixed) {
syms = getFixedInstanceDropdownValues(info.apis, typeInfo.qName);
}
else if (isCombined) {
syms = fn.combinedProperties.map(p => U.lookup(info.apis.byQName, p))
}
else {
syms = getConstantDropdownValues(info.apis, fn.qName);
}
if (syms.length == 0) {
console.error(`no instances of ${typeInfo.qName} found`)
}
const dd = syms.map(v => {
let k = v.attributes.block || v.attributes.blockId || v.name;
let comb = v.attributes.blockCombine
if (v.attributes.jresURL && !v.attributes.iconURL && U.startsWith(v.attributes.jresURL, "data:image/x-mkcd-f")) {
v.attributes.iconURL = imgConv.convert(v.attributes.jresURL)
}
if (!!comb)
k = k.replace(/@set/, "")
return [
v.attributes.iconURL || v.attributes.blockImage ? {
src: v.attributes.iconURL || Util.pathJoin(pxt.webConfig.commitCdnUrl, `blocks/${v.namespace.toLowerCase()}/${v.name.toLowerCase()}.png`),
alt: k,
width: 36,
height: 36,
value: v.name
} : k,
v.namespace + "." + v.name
];
});
// if a value is provided, move it first
if (pr.defaultValue) {
let shadowValueIndex = -1;
dd.some((v, i) => {
if (v[1] === (pr as BlockParameter).defaultValue) {
shadowValueIndex = i;
return true;
}
return false;
});
if (shadowValueIndex > -1) {
const shadowValue = dd.splice(shadowValueIndex, 1)[0];
dd.unshift(shadowValue);
}
}
if (customField) {
let defl = fn.attributes.paramDefl[actName] || "";
const options = {
data: dd,
colour: color,
label: fieldLabel,
type: fieldType,
blocksInfo: info
} as Blockly.FieldCustomDropdownOptions;
Util.jsonMergeFrom(options, fn.attributes.paramFieldEditorOptions && fn.attributes.paramFieldEditorOptions[actName] || {});
fields.push(namedField(createFieldEditor(customField, defl, options), defName));
}
else
fields.push(namedField(new Blockly.FieldDropdown(dd), defName));
} else if (customField) {
const defl = fn.attributes.paramDefl[pr.actualName] || "";
const options = {
colour: color,
label: fieldLabel,
type: fieldType,
blocksInfo: info
} as Blockly.FieldCustomOptions;
Util.jsonMergeFrom(options, fn.attributes.paramFieldEditorOptions && fn.attributes.paramFieldEditorOptions[pr.actualName] || {});
fields.push(namedField(createFieldEditor(customField, defl, options), pr.definitionName));
} else {
inputName = defName;
if (instance && part.name === "this") {
inputCheck = pr.type;
} else if (pr.type == "number" && pr.shadowBlockId && pr.shadowBlockId == "value") {
inputName = undefined;
fields.push(namedField(new Blockly.FieldTextInput("0", Blockly.FieldTextInput.numberValidator), defName));
} else if (pr.type == "string" && pr.shadowOptions && pr.shadowOptions.toString) {
inputCheck = null;
} else {
inputCheck = getBlocklyCheckForType(pr.type, info);
}
}
}
});
let input: Blockly.Input;
if (inputName) {
input = block.appendValueInput(inputName);
input.setAlign(Blockly.ALIGN_LEFT);
}
else if (expanded) {
const prefix = hasParameter ? optionalInputWithFieldPrefix : optionalDummyInputPrefix;
input = block.appendDummyInput(prefix + (anonIndex++));
}
else {
input = block.appendDummyInput();
}
if (inputCheck) {
input.setCheck(inputCheck);
}
fields.forEach(f => input.appendField(f.field, f.name));
});
imgConv.logTime()
}
}
function getParameterFromDef(part: pxtc.BlockParameter, comp: BlockCompileInfo, isThis = false): HandlerArg | BlockParameter {
if (part.ref) {
const result = (part.name === "this") ? comp.thisParameter : comp.actualNameToParam[part.name];
if (!result) {
let ha: HandlerArg;
comp.handlerArgs.forEach(arg => {
if (arg.name === part.name) ha = arg;
});
if (ha) return ha;
}
return result;
}
else {
return isThis ? comp.thisParameter : comp.definitionNameToParam[part.name];
}
}
function isHandlerArg(arg: HandlerArg | BlockParameter): arg is HandlerArg {
return !(arg as BlockParameter).definitionName;
}
export function hasArrowFunction(fn: pxtc.SymbolInfo): boolean {
return !!fn.parameters?.some(pr => pxtc.parameterTypeIsArrowFunction(pr));
}
export function cleanBlocks() {
pxt.debug('removing all custom blocks')
for (const b in cachedBlocks)
removeBlock(cachedBlocks[b].fn);
}
/**
* Used by pxtrunner to initialize blocks in the docs
*/
export function initializeAndInject(blockInfo: pxtc.BlocksInfo) {
init();
injectBlocks(blockInfo);
}
/**
* Used by main app to initialize blockly blocks.
* Blocks are injected separately by called injectBlocks
*/
export function initialize(blockInfo: pxtc.BlocksInfo) {
init();
initJresIcons(blockInfo);
}
let blocklyInitialized = false;
function init() {
if (blocklyInitialized) return;
blocklyInitialized = true;
goog.provide('Blockly.Blocks.device');
goog.require('Blockly.Blocks');
Blockly.FieldCheckbox.CHECK_CHAR = '■';
(<any>Blockly).Constants.ADD_START_HATS = !!pxt.appTarget.appTheme.blockHats;
initFieldEditors();
initContextMenu();
initOnStart();
initMath();
initVariables();
initFunctions();
initLists();
initLoops();
initLogic();
initText();
initDrag();
initDebugger();
initComments();
initTooltip();
// PXT is in charge of disabling, don't record undo for disabled events
(Blockly.Block as any).prototype.setEnabled = function (enabled: any) {
if (this.disabled == enabled) {
let oldRecordUndo = (Blockly as any).Events.recordUndo;
(Blockly as any).Events.recordUndo = false;
Blockly.Events.fire(new Blockly.Events.BlockChange(
this, 'disabled', null, this.disabled, !enabled));
(Blockly as any).Events.recordUndo = oldRecordUndo;
this.disabled = !enabled;
}
};
}
/**
* Converts a TypeScript type into an array of type checks for Blockly inputs/outputs. Use
* with block.setOutput() and input.setCheck().
*
* @returns An array of checks if the type is valid, undefined if there are no valid checks
* (e.g. type is void), and null if all checks should be accepted (e.g. type is generic)
*/
function getBlocklyCheckForType(type: string, info: pxtc.BlocksInfo) {
const types = type.split(/\s*\|\s*/);
const output = [];
for (const subtype of types) {
switch (subtype) {
// Blockly capitalizes primitive types for its builtin math/string/logic blocks
case "number":
output.push("Number");
break;
case "string":
output.push("String");
break;
case "boolean":
output.push("Boolean");
break;
case "T":
// The type is generic, so accept any checks. This is mostly used with functions that
// get values from arrays. This could be improved if we ever add proper type
// inference for generic types
case "any":
return null;
case "void":
return undefined;
default:
// We add "Array" to the front for array types so that they can be connected
// to the blocks that accept any array (e.g. length, push, pop, etc)
if (isArrayType(subtype)) {
if (types.length > 1) {
// type inference will potentially break non-trivial arrays in intersections
// until we have better type handling in blocks,
// so escape and allow any block to be dropped in.
return null;
} else {
output.push("Array");
}
}
// Blockly has no concept of inheritance, so we need to add all
// super classes to the check array
const si_r = info.apis.byQName[subtype];
if (si_r && si_r.extendsTypes && 0 < si_r.extendsTypes.length) {
output.push(...si_r.extendsTypes);
} else {
output.push(subtype);
}
}
}