forked from flipcomputing/flock
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathblocks.js
More file actions
1090 lines (959 loc) · 33.5 KB
/
blocks.js
File metadata and controls
1090 lines (959 loc) · 33.5 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
import * as Blockly from "blockly";
//import "@blockly/block-plus-minus";
import * as BlockDynamicConnection from "@blockly/block-dynamic-connection";
import { categoryColours, toolbox } from "./toolbox.js";
import {
deleteMeshFromBlock,
updateOrCreateMeshFromBlock,
getMeshFromBlock,
} from "./ui/blockmesh.js";
import { registerFieldColour } from "@blockly/field-colour";
registerFieldColour();
export let nextVariableIndexes = {};
export const inlineIcon =
"data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%22122.88px%22%20height%3D%2280.593px%22%20viewBox%3D%220%200%20122.88%2080.593%22%20enable-background%3D%22new%200%200%20122.88%2080.593%22%20xml%3Aspace%3D%22preserve%22%3E%3Cg%3E%3Cpolygon%20fill%3D%22white%22%20points%3D%22122.88%2C80.593%20122.88%2C49.772%2061.44%2C0%200%2C49.772%200%2C80.593%2061.44%2C30.82%20122.88%2C80.593%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E";
const baseHelpUrl = "https://docs.flockxr.com/blocks/";
export function getHelpUrlFor(blockType) {
//return baseHelpUrl + blockType;
return "https://flockxr.com";
}
// Shared utility to add the toggle button to a block
export function addToggleButton(block) {
const toggleButton = new Blockly.FieldImage(
inlineIcon, // Custom icon
30,
30,
"*", // Width, Height, Alt text
() => {
block.toggleDoBlock();
},
);
block
.appendDummyInput()
.setAlign(Blockly.inputs.Align.RIGHT)
.appendField(toggleButton, "TOGGLE_BUTTON");
}
// Shared utility for the mutationToDom function
export function mutationToDom(block) {
const container = document.createElement("mutation");
container.setAttribute("inline", block.isInline);
return container;
}
// Shared utility for the domToMutation function
export function domToMutation(block, xmlElement) {
const isInline = xmlElement.getAttribute("inline") === "true";
block.updateShape_(isInline);
}
// Shared utility to update the shape of the block
export function updateShape(block, isInline) {
block.isInline = isInline;
if (isInline) {
block.setPreviousStatement(true);
block.setNextStatement(true);
} else {
block.setPreviousStatement(false);
block.setNextStatement(false);
}
}
export function handleBlockSelect(event) {
if (event.type === Blockly.Events.SELECTED) {
const block = Blockly.getMainWorkspace().getBlockById(event.newElementId); // Get the selected block
if (
block &&
block.type !== "create_ground" &&
block.type !== "create_map" &&
(block.type.startsWith("create_") || block.type.startsWith("load_"))
) {
// If the block is a create block, update the window.currentMesh variable
window.updateCurrentMeshName(block, "ID_VAR");
}
}
}
export function handleBlockDelete(event) {
if (event.type === Blockly.Events.BLOCK_DELETE) {
// Recursively delete meshes for qualifying blocks
function deleteMeshesRecursively(blockJson) {
// Check if block type matches the prefixes
if (
blockJson.type.startsWith("load_") ||
blockJson.type.startsWith("create_")
) {
deleteMeshFromBlock(blockJson.id);
}
// Check inputs for child blocks
if (blockJson.inputs) {
for (const key in blockJson.inputs) {
const inputBlock = blockJson.inputs[key].block;
if (inputBlock) {
deleteMeshesRecursively(inputBlock);
}
}
}
// Check 'next' for connected blocks
if (blockJson.next && blockJson.next.block) {
deleteMeshesRecursively(blockJson.next.block);
}
}
// Process the main deleted block and its connections
deleteMeshesRecursively(event.oldJson);
}
}
export function handleMeshLifecycleChange(block, changeEvent) {
const mesh = getMeshFromBlock(block);
if (
changeEvent.type === Blockly.Events.BLOCK_MOVE &&
changeEvent.blockId === block.id
) {
if (block.getParent() && !mesh) {
updateOrCreateMeshFromBlock(block, changeEvent);
}
return true;
}
if (
changeEvent.type === Blockly.Events.BLOCK_CHANGE &&
changeEvent.blockId === block.id &&
changeEvent.element === "disabled"
) {
if (block.isEnabled()) {
setTimeout(() => {
if (block.getParent()) {
updateOrCreateMeshFromBlock(block, changeEvent);
}
}, 0);
} else {
deleteMeshFromBlock(block.id);
}
return true;
}
if (
changeEvent.type === Blockly.Events.BLOCK_CREATE &&
changeEvent.blockId === block.id &&
Blockly.getMainWorkspace().getBlockById(block.id)
) {
if (window.loadingCode) return true;
updateOrCreateMeshFromBlock(block, changeEvent);
return true;
}
return false;
}
export function handleFieldOrChildChange(containerBlock, changeEvent) {
if (
changeEvent.type !== Blockly.Events.BLOCK_CHANGE ||
changeEvent.element !== "field"
)
return false;
const changedBlock = Blockly.getMainWorkspace().getBlockById(
changeEvent.blockId,
);
if (!changedBlock) return false;
// Direct change on container block
if (changedBlock.id === containerBlock.id) {
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
return true;
}
// Change on an unchainable child block
const parent = changedBlock.getParent();
if (parent && parent.id === containerBlock.id) {
if (changedBlock.nextConnection || changedBlock.previousConnection)
return false;
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
return true;
}
return false;
}
export function handleParentLinkedUpdate(containerBlock, changeEvent) {
if (
changeEvent.type !== Blockly.Events.BLOCK_CREATE &&
changeEvent.type !== Blockly.Events.BLOCK_CHANGE
)
return false;
const changed = Blockly.getMainWorkspace().getBlockById(changeEvent.blockId);
const parent = findCreateBlock(changed);
if (parent === containerBlock && changed) {
if (!window.loadingCode) {
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
}
return true;
}
return false;
}
export function findCreateBlock(block) {
if (!block || typeof block.getParent !== "function") {
//console.log("no id");
return null;
}
let parent = block;
while (parent) {
if (parent.type === "scale" || parent.type === "rotate_to") {
// Don't update parent if we're modifying a nested scale or rotate
return null;
}
if (
parent.type.startsWith("create_") ||
parent.type.startsWith("load_") ||
parent.type === "set_sky_color" ||
parent.type === "set_background_color"
) {
return parent;
}
// Move up the hierarchy
parent = parent.getParent();
}
// No matching parent found
return null;
}
/*
export default Blockly.Theme.defineTheme("flock", {
base: Blockly.Themes.Modern,
componentStyles: {
workspaceBackgroundColour: "white",
toolboxBackgroundColour: "#ffffff66",
//'toolboxForegroundColour': '#fff',
//'flyoutBackgroundColour': '#252526',
//'flyoutForegroundColour': '#ccc',
//'flyoutOpacity': 1,
//'scrollbarColour': '#797979',
insertionMarkerColour: "#defd6c",
insertionMarkerOpacity: 0.3,
scrollbarOpacity: 0.4,
cursorColour: "#defd6c",
//'blackBackground': '#333',
},
});
*/
export class CustomConstantProvider extends Blockly.zelos.ConstantProvider {
constructor() {
super();
this.NOTCH_OFFSET_LEFT = 2 * this.GRID_UNIT;
this.NOTCH_HEIGHT = 2 * this.GRID_UNIT;
this.FIELD_DROPDOWN_SVG_ARROW_DATAURI =
"data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiMwMDAiLz48L3N2Zz4=";
}
}
class CustomRenderInfo extends Blockly.zelos.RenderInfo {
constructor(renderer, block) {
super(renderer, block);
}
adjustXPosition_() {}
}
export class CustomZelosRenderer extends Blockly.zelos.Renderer {
constructor(name) {
super(name);
}
// Override the method to return our custom constant provider
makeConstants_() {
return new CustomConstantProvider();
}
// Override the method to return our custom RenderInfo
makeRenderInfo_(block) {
return new CustomRenderInfo(this, block);
}
}
const mediaPath = window.location.pathname.includes("/flock")
? "/flock/blockly/media/" // For GitHub Pages
: "/blockly/media/"; // For local dev
export const options = {
theme: Blockly.Themes.Modern, // "flock"
//theme: "flockTheme",
//renderer: "zelos",
renderer: "custom_zelos_renderer",
media: mediaPath,
modalInputs: false,
zoom: {
controls: true,
wheel: false,
startScale: 0.7,
maxScale: 3,
minScale: 0.3,
scaleSpeed: 1.2,
},
move: {
scrollbars: {
horizontal: true,
vertical: true,
},
drag: true,
//dragSurface: false,
wheel: true,
},
toolbox: toolbox,
oneBasedIndex: false,
searchAllBlocks: false,
plugins: {
connectionPreviewer: BlockDynamicConnection.decoratePreviewer(),
},
// Double click the blocks to collapse/expand
// them (A feature from MIT App Inventor).
useDoubleClick: false,
// Bump neighbours after dragging to avoid overlapping.
bumpNeighbours: false,
// Keep the fields of multiple selected same-type blocks with the same value
// See note below.
multiFieldUpdate: true,
// Auto focus the workspace when the mouse enters.
workspaceAutoFocus: true,
// Use custom icon for the multi select controls.
multiselectIcon: {
hideIcon: true,
weight: 3,
enabledIcon:
"https://github.com/mit-cml/workspace-multiselect/raw/main/test/media/select.svg",
disabledIcon:
"https://github.com/mit-cml/workspace-multiselect/raw/main/test/media/unselect.svg",
},
multiSelectKeys: ["Shift"],
multiselectCopyPaste: {
crossTab: true,
menu: true,
},
};
export function initializeVariableIndexes() {
nextVariableIndexes = {
model: 1,
box: 1,
sphere: 1,
cylinder: 1,
capsule: 1,
plane: 1,
wall: 1,
text: 1,
"3dtext": 1,
sound: 1,
character: 1,
object: 1,
instrument: 1,
animation: 1,
clone: 1,
};
const allVariables = Blockly.getMainWorkspace().getVariableMap().getAllVariables(); // Retrieve all variables in the workspace
// Process each type of variable
Object.keys(nextVariableIndexes).forEach(function (type) {
let maxIndex = 0; // To keep track of the highest index used so far
// Regular expression to match variable names like 'type1', 'type2', etc.
const varPattern = new RegExp(`^${type}(\\d+)$`);
allVariables.forEach(function (variable) {
const match = variable.name.match(varPattern);
if (match) {
const currentIndex = parseInt(match[1], 10);
if (currentIndex > maxIndex) {
maxIndex = currentIndex;
}
}
});
nextVariableIndexes[type] = maxIndex + 1;
});
// Optionally return the indexes if needed elsewhere
return nextVariableIndexes;
}
export function defineBlocks() {
//BlockDynamicConnection.overrideOldBlockDefinitions();
//Blockly.Blocks['dynamic_list_create'].minInputs = 1;
// Blockly.Blocks['lists_create_with'] = Blockly.Blocks['dynamic_list_create'];
// Blockly.Blocks['text_join'] = Blockly.Blocks['dynamic_text_join'];
function updateCurrentMeshName(block, variableFieldName) {
const variableName = block.getField(variableFieldName).getText(); // Get the selected variable name
if (variableName) {
window.currentMesh = variableName;
window.currentBlock = block;
}
}
window.updateCurrentMeshName = updateCurrentMeshName;
Blockly.Blocks["create_wall"] = {
init: function () {
const variableNamePrefix = "wall";
let nextVariableName =
variableNamePrefix + nextVariableIndexes[variableNamePrefix]; // Start with "wall1";
this.jsonInit({
type: "create_wall",
message0:
"new wall %1 type %2 colour %3 \n start x %4 z %5 end x %6 z %7 y position %8",
args0: [
{
type: "field_variable",
name: "ID_VAR",
variable: nextVariableName,
},
{
type: "field_dropdown",
name: "WALL_TYPE",
options: [
["solid", "SOLID_WALL"],
["door", "WALL_WITH_DOOR"],
["window", "WALL_WITH_WINDOW"],
["floor/roof", "FLOOR"],
],
},
{
type: "input_value",
name: "COLOR",
check: "Colour",
},
{
type: "input_value",
name: "START_X",
check: "Number",
},
{
type: "input_value",
name: "START_Z",
check: "Number",
},
{
type: "input_value",
name: "END_X",
check: "Number",
},
{
type: "input_value",
name: "END_Z",
check: "Number",
},
{
type: "input_value",
name: "Y_POSITION",
check: "Number",
},
],
inputsInline: true,
previousStatement: null,
nextStatement: null,
colour: categoryColours["Scene"],
tooltip:
"Create a wall with the selected type and color between specified start and end positions.\nKeyword: wall",
});
this.setHelpUrl(getHelpUrlFor(this.type));
this.setOnChange((changeEvent) => {
if (
changeEvent.type === Blockly.Events.BLOCK_CREATE ||
changeEvent.type === Blockly.Events.BLOCK_CHANGE
) {
const blockInWorkspace = Blockly.getMainWorkspace().getBlockById(
this.id,
); // Check if block is in the main workspace
if (blockInWorkspace) {
window.updateCurrentMeshName(this, "ID_VAR"); // Call the function to update window.currentMesh
}
}
handleBlockCreateEvent(
this,
changeEvent,
variableNamePrefix,
nextVariableIndexes,
);
});
},
};
Blockly.Extensions.register("dynamic_mesh_dropdown", function () {
const dropdown = new Blockly.FieldDropdown(function () {
const options = [["everywhere", "__everywhere__"]];
const workspace = this.sourceBlock_ && this.sourceBlock_.workspace;
if (workspace) {
const variables = workspace.getVariableMap().getAllVariables();
variables.forEach((v) => {
options.push([v.name, v.name]);
});
}
return options;
});
// Attach the dropdown to the block
this.getInput("MESH_INPUT").appendField(dropdown, "MESH_NAME");
});
Blockly.Blocks["rotate_camera"] = {
init: function () {
this.jsonInit({
type: "rotate_camera",
message0: "rotate camera by %1 degrees",
args0: [
{
type: "input_value",
name: "DEGREES",
check: "Number",
},
],
inputsInline: true,
previousStatement: null,
nextStatement: null,
colour: categoryColours["Transform"],
tooltip:
"Rotate the camera left or right by the given degrees.\nKeyword: rotate",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["up"] = {
init: function () {
this.jsonInit({
type: "up",
message0: "up %1 force %2",
args0: [
{
type: "field_variable",
name: "MODEL_VAR",
variable: window.currentMesh,
},
{
type: "input_value",
name: "UP_FORCE",
check: "Number",
},
],
previousStatement: null,
nextStatement: null,
colour: categoryColours["Transform"],
tooltip: "Apply the specified upwards force.\nKeyword: up",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["random_seeded_int"] = {
init: function () {
this.jsonInit({
type: "random_seeded_int",
message0: "random integer from %1 to %2 seed: %3",
args0: [
{
type: "input_value",
name: "FROM",
check: "Number",
align: "RIGHT",
},
{
type: "input_value",
name: "TO",
check: "Number",
align: "RIGHT",
},
{
type: "input_value",
name: "SEED",
check: "Number",
align: "RIGHT",
},
],
inputsInline: true,
output: "Number",
colour: 230,
tooltip: "Generate a random integer with a seed.\n Keyword: seed",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["to_number"] = {
init: function () {
this.jsonInit({
type: "to_number",
message0: "convert %1 to %2",
args0: [
{
type: "input_value",
name: "STRING",
check: "String",
},
{
type: "field_dropdown",
name: "TYPE",
options: [
["integer", "INT"],
["float", "FLOAT"],
],
},
],
inputsInline: true,
output: "Number",
colour: 230,
tooltip: "Convert a string to an integer or float.",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["keyword_block"] = {
init: function () {
this.appendDummyInput().appendField(
new Blockly.FieldTextInput("type a keyword to add a block"),
"KEYWORD",
);
this.setTooltip("Type a keyword to change this block.");
this.setHelpUrl(getHelpUrlFor(this.type));
this.setOnChange(function (changeEvent) {
// Prevent infinite loops or multiple replacements.
if (this.isDisposed() || this.isReplaced) {
return;
}
// Get the entered keyword.
const keyword = this.getFieldValue("KEYWORD").trim();
// Lookup the new block type based on the keyword.
const blockType = findBlockTypeByKeyword(keyword);
if (blockType) {
// Mark the block as replaced.
this.isReplaced = true;
const workspace = this.workspace;
// Create the new block.
const newBlock = workspace.newBlock(blockType);
// Apply toolbox settings if defined.
const blockDefinition = findBlockDefinitionInToolbox(blockType);
if (blockDefinition && blockDefinition.inputs) {
applyToolboxSettings(newBlock, blockDefinition.inputs);
}
newBlock.initSvg();
newBlock.render();
// Position the new block where the old keyword block is.
const pos = this.getRelativeToSurfaceXY();
newBlock.moveBy(pos.x, pos.y);
if (
this.previousConnection &&
this.previousConnection.isConnected()
) {
const parentConnection = this.previousConnection.targetConnection;
if (parentConnection) {
parentConnection.disconnect();
parentConnection.connect(newBlock.previousConnection);
}
}
// Reattach any block that was connected to the keyword block's next connection.
const nextBlock = this.getNextBlock();
if (nextBlock && newBlock.nextConnection) {
newBlock.nextConnection.connect(nextBlock.previousConnection);
}
// Select the new block for immediate editing.
const selectedBlock = Blockly.getSelected();
if (selectedBlock) {
selectedBlock.unselect();
}
newBlock.select();
window.currentBlock = newBlock;
// Dispose of the old keyword block.
this.dispose();
}
});
},
};
Blockly.Blocks["keyword"] = {
init: function () {
// Call the original keyword_block init method.
Blockly.Blocks["keyword_block"].init.call(this);
// Add chaining connections.
this.setPreviousStatement(true);
this.setNextStatement(true);
},
};
function findBlockTypeByKeyword(keyword) {
// Recursive helper to search through a contents array.
function searchContents(contents) {
if (!Array.isArray(contents)) {
return null;
}
for (const item of contents) {
// If this item is a block with the matching keyword, return its type.
if (item.kind === "block" && item.keyword === keyword) {
return item.type;
}
// If the item is a category with its own contents, search recursively.
if (item.kind === "category" && Array.isArray(item.contents)) {
const result = searchContents(item.contents);
if (result !== null) {
return result;
}
}
}
return null;
}
return searchContents(toolbox.contents);
}
// Function to find block definition in the toolbox by block type
function findBlockDefinitionInToolbox(blockType) {
// Recursive helper to search through a contents array.
function searchContents(contents) {
if (!Array.isArray(contents)) {
return null;
}
for (const item of contents) {
// If this item is a block with the matching type, return its definition.
if (item.kind === "block" && item.type === blockType) {
return item;
}
// If the item is a category with its own contents, search recursively.
if (item.kind === "category" && Array.isArray(item.contents)) {
const result = searchContents(item.contents);
if (result !== null) {
return result;
}
}
}
return null;
}
return searchContents(toolbox.contents);
}
// Function to apply settings from the toolbox definition to the new block
function applyToolboxSettings(newBlock, inputs) {
for (const inputName in inputs) {
const input = inputs[inputName];
if (input.shadow) {
const shadowBlock = Blockly.getMainWorkspace().newBlock(
input.shadow.type,
);
shadowBlock.setShadow(true);
// Apply fields (default values) to the shadow block
for (const fieldName in input.shadow.fields) {
shadowBlock.setFieldValue(input.shadow.fields[fieldName], fieldName);
}
shadowBlock.initSvg();
shadowBlock.render();
newBlock
.getInput(inputName)
.connection.connect(shadowBlock.outputConnection);
Blockly.getMainWorkspace().cleanUp();
}
}
}
}
export function addDoMutatorWithToggleBehavior(block) {
// Custom function to toggle the "do" block mutation
block.toggleDoBlock = function () {
const hasDo = this.getInput("DO") ? true : false;
if (hasDo) {
this.removeInput("DO");
} else {
this.appendStatementInput("DO").setCheck(null).appendField("");
}
};
// Add the toggle button to the block
const toggleButton = new Blockly.FieldImage(
"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAiIGhlaWdodD0iMzAiIHZpZXdCb3g9IjAgMCAzMCAzMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4gPHBhdGggZmlsbD0id2hpdGUiIGQ9Ik0xNSA2djloLTl2M2g5djloM3YtOWg5di0zaC05di05eiIvPjwvc3ZnPg==", // Custom icon
30,
30,
"*", // Width, Height, Alt text
block.toggleDoBlock.bind(block), // Bind the event handler to the block
);
// Add the button to the block
block
.appendDummyInput()
.setAlign(Blockly.inputs.Align.RIGHT)
.appendField(toggleButton, "TOGGLE_BUTTON");
// Save the mutation state
block.mutationToDom = function () {
const container = document.createElement("mutation");
container.setAttribute("has_do", this.getInput("DO") ? "true" : "false");
return container;
};
// Restore the mutation state
block.domToMutation = function (xmlElement) {
const hasDo = xmlElement.getAttribute("has_do") === "true";
if (hasDo) {
this.appendStatementInput("DO").setCheck(null).appendField("");
}
};
}
export function handleBlockCreateEvent(
blockInstance,
changeEvent,
variableNamePrefix,
nextVariableIndexes,
fieldName = "ID_VAR", // Default field name to handle
) {
if (window.loadingCode) return; // Don't rename variables during code loading
if (blockInstance.id !== changeEvent.blockId) return;
// Check if this is an undo/redo operation
const isUndo = !changeEvent.recordUndo;
if (
!blockInstance.isInFlyout &&
changeEvent.type === Blockly.Events.BLOCK_CREATE &&
changeEvent.ids.includes(blockInstance.id)
) {
if (isUndo) return;
// Check if the specified field already has a value
const variableField = blockInstance.getField(fieldName);
if (variableField) {
const variableId = variableField.getValue();
const variable = blockInstance.workspace.getVariableMap().getVariableById(variableId);
// Check if the variable name matches the pattern "prefixn"
const variableNamePattern = new RegExp(`^${variableNamePrefix}\\d+$`);
const variableName = variable ? variable.name : "";
if (!variableNamePattern.test(variableName)) {
// Handle custom variables
if (variableName) {
const numberMatch = variableName.match(/^(.+?)(\d+)$/);
let newVariableName;
if (numberMatch) {
newVariableName = numberMatch[1] + (parseInt(numberMatch[2]) + 1);
} else {
newVariableName = variableName + "1";
}
let newVariable = blockInstance.workspace.getVariableMap().getVariable(newVariableName);
if (!newVariable) {
newVariable = blockInstance.workspace.createVariable(newVariableName, null);
}
variableField.setValue(newVariable.getId());
}
} else {
// Handle prefix-numbered variables (existing logic)
if (!nextVariableIndexes[variableNamePrefix]) {
nextVariableIndexes[variableNamePrefix] = 1;
}
let newVariableName = variableNamePrefix + nextVariableIndexes[variableNamePrefix];
let newVariable = blockInstance.workspace.getVariableMap().getVariable(newVariableName);
if (!newVariable) {
newVariable = blockInstance.workspace.createVariable(newVariableName, null);
}
variableField.setValue(newVariable.getId());
nextVariableIndexes[variableNamePrefix] += 1;
}
}
}
}
// Extend the built-in Blockly procedures_defreturn block to add custom toggle functionality
// Reference to the original init function of the procedures_defreturn block
Blockly.Blocks["procedures_defreturn"].init = (function (originalInit) {
return function () {
// Call the original initialization function to ensure the block retains its default behaviour
originalInit.call(this);
// Use the existing addToggleButton helper to add the button to the block
addToggleButton(this);
};
})(Blockly.Blocks["procedures_defreturn"].init);
// Create an extension that adds extra UI logic without modifying the core mutator methods
Blockly.Extensions.register("custom_procedure_ui_extension", function () {
this.toggleDoBlock = function () {
const isInline = !this.isInline;
// Disconnect block from parent if switching to top-level mode
if (!isInline) {
this.unplug(true);
}
// Update block shape (delegated to your helper)
updateShape(this, isInline);
// Optionally re-enable if previously disabled (for orphaned block UX)
if (this.hasDisabledReason && this.hasDisabledReason("ORPHANED_BLOCK")) {
this.setDisabledReason(false, "ORPHANED_BLOCK");
}
// Fire Blockly events so undo/redo and UI updates are tracked
Blockly.Events.fire(
new Blockly.Events.BlockChange(this, "mutation", null, "", ""),
);
Blockly.Events.fire(new Blockly.Events.BlockMove(this));
};
});
// Apply the extension to the built-in 'procedures_defreturn' block
Blockly.Extensions.apply(
"custom_procedure_ui_extension",
Blockly.Blocks["procedures_defreturn"],
);
// Extend the built-in Blockly procedures_defnoreturn block to add custom toggle functionality
// Reference to the original init function of the procedures_defnoreturn block
Blockly.Blocks["procedures_defnoreturn"].init = (function (originalInit) {
return function () {
// Call the original initialization function to ensure the block retains its default behaviour
originalInit.call(this);
// Use the existing addToggleButton helper to add the button to the block
addToggleButton(this);
};
})(Blockly.Blocks["procedures_defnoreturn"].init);
// Apply the extension to the built-in 'procedures_defnoreturn' block
Blockly.Extensions.apply(
"custom_procedure_ui_extension",
Blockly.Blocks["procedures_defnoreturn"],
);
// Define unique IDs for each option
Blockly.FieldVariable.ADD_VARIABLE_ID = "ADD_VARIABLE_ID";
Blockly.FieldVariable.RENAME_VARIABLE_ID = "RENAME_VARIABLE_ID";
Blockly.FieldVariable.DELETE_VARIABLE_ID = "DELETE_VARIABLE_ID";
// Extend `getOptions` to include "New variable..." at the top of the dropdown
const originalGetOptions = Blockly.FieldVariable.prototype.getOptions;
Blockly.FieldVariable.prototype.getOptions = function () {
// Retrieve the default options
const options = originalGetOptions.call(this);
// Add the "New variable..." option at the beginning
options.unshift(["New variable...", Blockly.FieldVariable.ADD_VARIABLE_ID]);
return options;
};
// Save a reference to the original `onItemSelected_` method
const originalOnItemSelected = Blockly.FieldVariable.prototype.onItemSelected_;
Blockly.FieldVariable.prototype.onItemSelected_ = function (menu, menuItem) {
const id = menuItem.getValue();
if (id === Blockly.FieldVariable.ADD_VARIABLE_ID) {
// Open the variable creation dialog, receiving the new variable name
Blockly.Variables.createVariableButtonHandler(
this.sourceBlock_.workspace,
(newVariableName) => {
if (newVariableName) {
// Find the variable by its name to get the full variable object
const newVariable =
this.sourceBlock_.workspace.getVariableMap().getVariable(newVariableName);