-
Notifications
You must be signed in to change notification settings - Fork 22
/
blockly.html
1138 lines (1001 loc) · 60.6 KB
/
blockly.html
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
<!--
Copyright 2018, Bart Butenaers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script type="text/javascript">
function loadResourcesFromServer(node, language, categories) {
var lastScriptToLoad;
// When no categories are passed (e.g. when there is no config node selected), then use the default categories
if (!categories) {
categories = getDefaultBlocklyCategories();
}
// Create a deep clone of the original category array (from the config node), to make sure the original array isn't updated by this function
categories = JSON.parse(JSON.stringify(categories));
node.librariesLoaded = false;
// Remove all the custom blockly scripts from the previous time.
// Because suppose a library has been removed in the config screen, then it would otherwise still be loaded and be used by blockly.
$('script[data-custom_blockly_library=true]').remove();
// Make sure that all standard Blockly library files are loaded FIRST AND IN THE CORRECT ORDER, by adding a dummy category.
// Don't use jQuery or script tags (see https://discourse.nodered.org/t/scope-of-variables-in-external-js-scripts/1048/2).
// The en.js file should be loaded before the blocks_compressed.js library, to avoid "No message string for..." console warnings.
categories.unshift({
name: "Dummy category",
files: [
"blockly-contrib/npm/blockly/blockly_compressed.js", // Creates a global Blockly variable
"blockly-contrib/npm/blockly/msg/en.js", // Fills the Blockly.Msg with english translations
"blockly-contrib/npm/blockly/blocks_compressed.js",
"blockly-contrib/npm/blockly/javascript_compressed.js",
// When the npm package name contains a path separator (e.g. @blockly/plugin-workspace-search) then the frontend will
// need to replace that separator by the string "___SEPARATOR___". Otherwise the NGinx webserver installed together
// with HomeAssistant will cause the Express.js routes to be messed up.
// See https://github.com/bartbutenaers/node-red-contrib-blockly/issues/101
"blockly-contrib/npm/@blockly___SEPARATOR___plugin-workspace-search/dist/index.js",
"blockly-contrib/npm/@blockly___SEPARATOR___zoom-to-fit/dist/index.js",
"blockly-contrib/npm/@blockly___SEPARATOR___workspace-backpack/dist/index.js",
"blockly-contrib/npm/@blockly___SEPARATOR___toolbox-search/dist/index.js",
"blockly-contrib/npm/@blockly___SEPARATOR___workspace-minimap/dist/index.js",
"blockly-contrib/npm/@blockly___SEPARATOR___plugin-cross-tab-copy-paste/dist/index.js"
]
});
// When another (not-english) language has been selected, then the english files should be loaded first.
// And afterwards the other language files will be loaded. That way there won't be a problem if some of
// the texts have not been translated: they will simply be showed in english.
// Note that the standard blockly en.js file contains a statement to clear all the Blockly.msg messages,
// which means this one needs to be loaded first. And all translations also have to be reloaded afterwards ...
if (language != "en") {
categories.forEach(function(category) {
(category.files || []).forEach(function(file) {
if(file.endsWith("/en.js")) {
var translationFile = file.replace("/en.js", "/" + language + ".js");
category.files.push(translationFile);
}
});
});
}
// As soon as the toolbox files have been loaded, the javascript files for the categories will be loaded.
// The javascript files will be loaded synchronous, because there is a dependency order that needs to be fullfilled.
// However the files will be loaded in background, so we need to wait for an event that indicates that the script is loaded...
categories.forEach(function(category) {
(category.files || []).forEach(function(file) {
// Note that the english language files have already been handled above...
if(file.endsWith(".js")) {
// Make sure that all Blockly library files are loaded in the correct order.
// Don't use jQuery (see https://discourse.nodered.org/t/scope-of-variables-in-external-js-scripts/1048/2)
lastScriptToLoad = document.createElement('script');
lastScriptToLoad.type="text/javascript";
lastScriptToLoad.async = false; // Force synchronous loading, to load them in the correct sequence
lastScriptToLoad.src = file;
// Set a user attribute on the script element, to allow us to identify it afterwards as on of the blockly related libs
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
lastScriptToLoad.dataset.custom_blockly_library = true;
document.head.appendChild(lastScriptToLoad);
}
});
});
// Currently only JS and XML files are allowed. Not sure yet how to handle other types.
categories.forEach(function(category) {
(category.files || []).forEach(function(file) {
if(!file.endsWith(".js") && !file.endsWith(".xml")) {
console.log("Unknown resource type (" + file + ")");
}
});
});
// The workspace can only be created when all script files have been loaded, otherwise errors will occur...
// By loading the standard Blockly library again, a new Blockly instance will be created which must be initialized here.
// And then the language files can be loaded into the new empty Blockly.Msg
lastScriptToLoad.onload = function() {
node.librariesLoaded = true;
// Unlike the other plugins below, the CrossTabCopyPaste plugin needs to be initialized globally, and as a resulting
// it doesn't need to be disposed. See more info on https://github.com/google/blockly-samples/pull/2061
// We will initialize the plugin here, because at this point a new empty Blockly instance has been loaded.
// On that new instance, the init method will e.g. register the 'copy' and 'paste' context menu actions.
// Note that this can't be done at the point where the other plugins are being initialized, because then an
// exception would be thrown every time the workspace is being recreated (e.g. when switching to full-screen),
// because the context menu actions have already been created. Because the global plugin is never disposed....
var copyPastePlugin = new CrossTabCopyPaste();
copyPastePlugin.init({
contextMenu: true,
shortcut: true,
});
Blockly.blocklyEditorVisible = true;
// Make sure the Blockly datetime_convert_from_date block is always aware about the number of outputs
Blockly.blocklyEditorLanguage = language;
// Make sure the Blockly node_send and node_return_message blocks are already at the beginning aware about the number of outputs
Blockly.nodeOutputs = node.outputs
// The 'msg' variable represents the parameter from the Node-Red 'input' event.
// By adding it as a reserved wordt in Javascript, we can avoid that users create their own 'msg' variable.
// Idem for the 'global', 'flow' and 'context' memory in Node-Red.
Blockly.JavaScript.addReservedWords(['msg', 'flow', 'context', 'global']);
// Blockly has an onKeyDown handler, that handles a number of key combinations (ctrl-'C' to copy the selected
// blocks, 'D' to delete the selected blocks, ctrl-'Z' to undo the last action). However afterwards the keydown event
// is passed to Node-Red which cannot handle it, resulting in errors in the log.
// See https://github.com/bartbutenaers/node-red-contrib-blockly/issues/2
// Make sure that Blockly only handles the keydown events when the Blockly editor is visible, and otherwise Node-Red will handle them.
if (Blockly.blocklyEditorVisible === undefined) {
Blockly.originalKeyDownHandler = Blockly.onKeyDown_;
Blockly.onKeyDown_ = function(e) {
if (Blockly.blocklyEditorVisible) {
// Let Blockly handle the keydown event
Blockly.originalKeyDownHandler(e);
//
if (e.altKey || e.ctrlKey || e.metaKey) {
// Don't use meta keys during drags
if (!Blockly.mainWorkspace.isDragging()) {
// When pressing CTRL-V (paste) ...
if (e.keyCode == 86) {
if (!Blockly.clipboardXml_ && Blockly.customClipboard) {
// When the originalClipboardXml_ is null and the customClipboard is not empty, this means
// we need to paste blocks that have been copied (to the customClipboard) in another node.
var xmlDom = Blockly.Xml.textToDom(Blockly.customClipboard);
Blockly.Xml.domToWorkspace(xmlDom, Blockly.mainWorkspace);
}
}
}
}
// Stop the events from propagating up the DOM tree
e.stopPropagation();
}
}
}
if (document.implementation.createDocument) {
// Create a new XML document (which represents a toolbox), and keep it as a global variable.
// All toolbox.xml files will be loaded and combined into the XML document.
// As soon as the XML document is complete, the toolbox will be displayed.
// In e.g. Chrome you can skip the third parameter, but e.g. in Firefox you need at least pass a null.
node.toolboxXmlDocument = document.implementation.createDocument("https://developers.google.com/blockly/xml", "xml", null);
}
else {
console.error('This browser cannot create a Blockly toolbox XML document (via createDocument)');
return;
}
// Load the toolbox (XML) files for all categories. This is done synchronous to make sure they are displayed in the specified order.
categories.forEach(function(category) {
(category.files || []).forEach(function(file) {
if(file.endsWith(".xml")) {
var request = new XMLHttpRequest();
request.open('GET', file, false); // `false` makes the request synchronous
request.send();
if (request.readyState == 4 && request.status == 200) {
// Get all categories in the new XML document
var newCategories = request.responseXML.getElementsByTagName("category");
// Iterate backwards since categories can be moved away from this list (to the toolbox)
// 2021-03-25 Jeff: changed to while-loop to accommadate nested categories
while (newCategories.length > 0) {
var newCategory = newCategories[0];
// Get the category name
var name = newCategory.getAttribute('name');
// Try to find an existing category with the same name.
// Indeed multiple toolboxes can put blocks in the same category...
var existingCategory = node.toolboxXmlDocument.getElementsByName(name);
if (existingCategory.length === 0) {
// If the new category didn't exist yet in the toolbox, append the entire new category to the toolbox
node.toolboxXmlDocument.documentElement.appendChild(newCategory);
}
else {
var newBlocks = newCategory.children;
// Move all the blocks (and their children) from the newCategory to the existingCategory.
// Remark: appendChild will remove the block from newBlocks!
while(newBlocks.length > 0) {
existingCategory[0].appendChild(newBlocks[0]);
}
// Remove the category from newCategories so the next loop is clean
newCategory.remove();
}
}
}
else {
console.error("The toolbox XML files for Blockly cannot be loaded");
}
}
});
});
// // Add a 'Search' category at the end, which is linked automatically by Blockly to the toolbox-search plugin.
const searchElement = document.createElementNS("http://www.w3.org/1999/xhtml", "category");
searchElement.setAttribute("name", "Search");
searchElement.setAttribute("kind", "search");
// When the search input field is clicked, a blue background appears.
// I tried to apply as color the same color as the background color (grey), but it doesn't help.
// The same happens in the official plugin demo (https://google.github.io/blockly-samples/plugins/toolbox-search/test/index.html)
searchElement.setAttribute("colour", "#B2B2B2"); // Same color as the background
node.toolboxXmlDocument.documentElement.appendChild(searchElement);
load_themes();
// Create the workspace as soon as the last script has been loaded.
// This is possible because the scripts are loaded sequentially (via async = false)
createWorkspace(node, node.workspaceXml);
}
}
let theme_guard = false;
async function load_themes() {
if (theme_guard) {
return;
}
theme_guard = true;
// Load the themes
let _themes = [
"dark",
"deuteranopia",
"highcontrast",
"modern",
"tritanopia"
];
// Ralph:
// Initially Bart tried to import the Blockly Theme modules the conventional way:
// node.themeModule = await import("/blockly-contrib/npm/@blockly___SEPARATOR___theme-" + theme + "/dist/index.js");
// This yet runs into "Cannot read properties of undefined (reading 'Blockly')".
// Looks like there's an issue with the webpackUniversalModuleDefinition implementation. I found no way to compensate for this. Bad.
// As "[...]/src/index.js" is the pure code file (not being wrapped into the webpackUniversalModuleDefinition stuff), I tried to import from there.
// Fails as well, as "import Blockly from 'blockly/core'" cannot be resolved.
// The good thing: We don't need this import at all! 'Blockly' is guaranteed to be already defined!
// Fortunately, the Blockly Theme plugins follow a very simple & identical pattern - supporting the following hack:
// * Get the script as text from the runtime.
// * Remove "import Blockly from 'blockly/core';" from the script.
// * Replace "export default ..." statement by a simple "return".
// * Wrap this script into a self executing function, to assign its value to the "Blockly.Themes" object.
// * Do those steps for all defined themes.
// * Create a script tag and let it execute the generated code.
// Works like a charm!
let _script = ["Blockly.Themes = Blockly.Themes ?? {}"];
_script.push("Blockly.Themes['classic'] = Blockly.Themes.Classic");
for (const thm of _themes) {
let request = new XMLHttpRequest();
request.open('GET', `blockly-contrib/npm/@blockly___SEPARATOR___theme-${thm}/src/index.js`, false); // `false` makes the request synchronous
request.send();
if (request.readyState == 4 && request.status == 200) {
let data = request.response;
data = data.replace("import Blockly from 'blockly/core';", "");
data = data.replace("export default Blockly.", "return Blockly.");
_script.push(`Blockly.Themes["${thm}"] = (function() {${data}})();`);
} else {
console.log(`Failed to load plugin for Blockly Theme "${thm}": ${request.response}`);
}
}
_script = _script.join(";\r\n");
let script = document.createElement('script');
script.type= "text/javascript";
script.async = false; // Force synchronous loading, to load them in the correct sequence
script.text = _script;
script.dataset.custom_blockly_library = true;
document.head.appendChild(script);
theme_guard = false;
}
function createWorkspace(node, workspaceXml) {
// Default settings in case no config node has been specified
var showTrashcan = true;
var allowComments = true;
var showZoomControl = true;
var showMiniMap = true;
var horizontalLayout = false;
var enableBackPack = false;
var toolboxPosition = "start";
var renderer = "geras";
var theme = "classic";
var configNodeId = "";
var backpackContents = [];
// When a config node has been specified, then use the settings from that node
if (node.selectedConfigNodeId && node.selectedConfigNodeId !== "_ADD_") {
var configNode = RED.nodes.node(node.selectedConfigNodeId);
if (configNode) {
showTrashcan = configNode.showTrashcan;
allowComments = configNode.allowComments;
showZoomControl = configNode.showZoomControl;
showMiniMap = configNode.showMiniMap;
renderer = configNode.renderer;
theme = configNode.theme;
enableBackPack = configNode.enableBackPack;
configNodeId = configNode.id;
// The toolboxPosition from the config screen determines two separate blockly settings!
switch(configNode.toolboxPosition) {
case "left":
horizontalLayout = false;
toolboxPosition = "start";
break;
case "right":
horizontalLayout = false;
toolboxPosition = "end";
break;
case "top":
horizontalLayout = true;
toolboxPosition = "start";
break;
}
}
}
// When previously a zoom-to-fit plugin has been activated, then clean it up
if (node.zoomToFit) {
node.zoomToFit.dispose();
node.zoomToFit = null;
}
// Persist the backpack content, to make sure it can be restored in new workspace instances (e.g. when switching to full-screen mode).
// If backpack is not enabled, further on a new workspace setting will be created without backpack ...
if (enableBackPack) {
// Note that the backpack instance is linked to this node (since the corresponding workspace instance is also stored in this node),
// but its content will be stored in the config node in the oneditsave...
if (!node.backpack || configNodeId !== node.previousConfigNodeId) {
if (node.selectedConfigNodeId && node.selectedConfigNodeId !== "_ADD_") {
var configNode = RED.nodes.node(node.selectedConfigNodeId);
if (configNode) {
// Start from scratch (starting from the backpack content stored in the config node) when:
// 1) There was previously no backpack activated in this node workspace, which means the user has enable the backpack now.
// 2) The config node has changed. Since enableBackPack is true, the user has selected another config node with its own backpack enabled.
backpackContents = configNode.backpackContents;
}
}
}
else {
if (node.backpack) {
// We are still using the same config node. Since the user might already have made changes to the config node backpack, we need
// to start again from the previous backpack instance in this workspace (since that would contain those changes).
// Otherwise all changes would be lost...
backpackContents = node.backpack.getContents();
}
}
}
// Remember the current config node id for the next time we arrive in this function
node.previousConfigNodeId = configNodeId;
cleanup_plugins(node);
// When previously another workspace was already created, then cleanup that one first (to avoid displaying multiple workspaces).
if (node.workspace) {
node.workspace.dispose();
node.workspace = null;
}
// Ralph: This doesn't work!
// try {
// // The theme plugins for Blockly are ES6 modules
// node.themeModule = await import("/blockly-contrib/npm/@blockly___SEPARATOR___theme-" + theme + "/dist/index.js");
// }
// catch (err) {
// console.error(err);
// }
// Only load the Blockly workspace when all libraries have been loaded yet, in order to avoid errors
if (node.librariesLoaded == true) {
// Create the workspace (with the specified settings)
node.workspace = Blockly.inject('blocklyDiv', {
grid: {
spacing: 25,
length: 3,
colour: '#ccc',
snap: true
},
toolbox: node.toolboxXmlDocument.firstElementChild,
zoom: {
controls: showZoomControl,
wheel: true
},
renderer: renderer,
theme: Blockly.Themes[theme],
trashcan: showTrashcan,
comments: allowComments,
disable: true,
scrollbars: true,
horizontalLayout: horizontalLayout,
toolboxPosition : toolboxPosition
});
// Enable the search bar on the workspace (via the workspace-search plugin)
const workspaceSearch = new WorkspaceSearch(node.workspace);
workspaceSearch.init();
if (showZoomControl) {
// Enable the zoom to fit control icon on the workspace (via the zoom-to-fit plugin)
node.zoomToFit = new ZoomToFitControl(node.workspace);
node.zoomToFit.init();
}
// Only show the minimap when the (fullscreen) tray is open, because the minimap is too big to fit into the node's config screen.
if (showMiniMap && node.isTrayOpen) {
// Enable the mini map on the workspace (via the workspace-minimap plugin)
node.minimap = new PositionedMinimap(node.workspace);
node.minimap.init();
}
if (enableBackPack) {
// Enable the backpack icon on the workspace (via the workspace-backpack plugin)
node.backpack = new Backpack(node.workspace);
node.backpack.init();
// Reload the previous backpack content, to make sure it stays the same in new workspace instances (e.g. when switching to full-screen mode)
if (enableBackPack) {
// Show the required backpack content
node.backpack.setContents(backpackContents);
}
}
// Trigger an event to indicate that a new Blockly workspace has been created.
// Blockly doesn't offer such an event. See https://groups.google.com/g/blockly/c/sSpvp_Kz-To
// Such an event is required, because this node switches often its workspace (and some blocks need to be aware of that...).
// Note that custom data needs to be passed via the 'detail' field...
document.dispatchEvent(new CustomEvent("blocky_workspace_changed", {
detail: {
newWorkspace: node.workspace
}
}));
try {
// Load the workspace content again from the specified XML string
var dom = Blockly.utils.xml.textToDom(workspaceXml);
Blockly.Xml.domToWorkspace(dom, node.workspace);
}
catch(err) {
// We will arrive here when the current set of block libraries (as specified in the config node) doesn't support some blocks anymore.
var errorText = "Some blocks will be removed from the workspace (because the current categories don't support them): " + err;
// When the config screen of this node is openened, Node-RED will call twice the onchange handler of the config node.
// To avoid that we would get the same error notification twice, we will skip one of both messages (during 1 second).
if (node.errorNotificationTimer) {
clearTimeout(node.errorNotificationTimer);
}
node.errorNotificationTimer = setTimeout(function() {
RED.notify(errorText, "error");
}, 500);
// When some of the block definitions are missing, we will convert the workspace to Dom and back to workspace.
// By doing that Blockly will remove the blocks without definition, and shows a workspace without those blocks.
// That is much better compared to showing an empty workspace...
// See https://groups.google.com/g/blockly/c/zdcUuRqWkxU/m/JfEdMv8MAQAJ
var dom = Blockly.Xml.workspaceToDom(node.workspace);
Blockly.Xml.domToWorkspace(dom, node.workspace);
}
// Make sure the workspace is sized correctly in the beginning
resize(node);
node.workspace.scrollCenter();
}
}
function cleanup(node) {
// Make sure that the Node-Red handles all keydown events again (e.g. 'D' to delete a node), instead of Blockly.
Blockly.blocklyEditorVisible = false;
// When blocks are still available in Blockly's clipboard, Blockly CANNOT paste them in another workspace (of another node).
// This means we can empty the clipboard (by setting it to null). However we will store first a copy of their clipboard
// (as xml string) into our own custom clipboard, which we CAN use to paste in another workspace.
if (Blockly.clipboardXml_) {
Blockly.customClipboard = '<xml xmlns="https://developers.google.com/blockly/xml">' + Blockly.Xml.domToPrettyText(Blockly.clipboardXml_) + '</xml>';
Blockly.clipboardXml_ = null;
}
// When a copy is done in this blockly node, an error will occur if that content is pasted later in another blockly node.
// Copy-paste across workspaces is not supported by Blockly (https://github.com/google/blockly/issues/334)
Blockly.clipboardXml_ = null;
Blockly.clipboardSource_ = null;
// Cleanup the ACE editor
node.aceEditor.destroy();
delete node.aceEditor;
// Jeff: Cleanup the XML editor 04/18/2021
node.aceXMLEditor.destroy();
delete node.aceXMLEditor;
cleanup_plugins(node);
// Blockly requires an empty array for the content of an empty backpack (instead of undefined or null)
if (!backpackContents) {
backpackContents = [];
}
// Cleanup the Blockly workspace
node.workspace.dispose();
delete node.workspace;
}
function cleanup_plugins(node) {
// When previously a zoom-to-fit plugin has been activated, then clean it up
if (node.zoomToFit) {
node.zoomToFit.dispose();
node.zoomToFit = null;
}
// When previously a workspace-minimap plugin has been activated, then clean it up
if (node.minimap) {
node.minimap.dispose();
node.minimap = null;
}
// When previously a workspace-backpack plugin has been activated (for the previous workspace instance), then clean it up
if (node.backpack) {
node.backpack.dispose();
node.backpack = null;
}
}
// See https://developers.google.com/blockly/guides/configure/web/resizable
function resize(node) {
// Resize the Blockly workspace, as soon as available (i.e. not when called from oneditprepare).
if (node.workspace) {
var blocklyArea = document.getElementById('blocklyArea');
var blocklyDiv = document.getElementById('blocklyDiv');
// Compute the absolute coordinates and dimensions of blocklyArea.
var element = blocklyArea;
var x = 0;
var y = 0;
//do {
x += element.offsetLeft;
y += element.offsetTop;
// element = element.offsetParent;
//} while (element);
// Position blocklyDiv over blocklyArea.
blocklyDiv.style.left = x + 'px';
blocklyDiv.style.top = y + 'px';
blocklyDiv.style.width = blocklyArea.offsetWidth + 'px';
blocklyDiv.style.height = blocklyArea.offsetHeight + 'px';
// Make sure the Blockly svg area is resized according the DIV element.
// Blockly itself also calls svgResize underneath, but only when e.g. the toolbox changes size)
Blockly.svgResize(node.workspace);
}
};
function fillAceEditor(node) {
// Store the number of output ports in Blockly, so the blocks can take that number into account (if required)
//Blockly.nodeOutputs = $("#node-input-outputs").val();
// Generate JavaScript code from the workspace content
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
var javascript = Blockly.JavaScript.workspaceToCode(node.workspace);
// Show the generated Javascript code in the Ace editor
node.aceEditor.setValue(javascript);
// After setValue all code will be selected otherwise
// Fix for clearSelection (see https://github.com/bartbutenaers/node-red-contrib-blockly/issues/74#issuecomment-862681796)
node.aceEditor.moveCursorTo(0,0);
/*
// Count the number of (syntax) errors in the generated javascript code
var errorCount = 0;
var annotations = node.aceEditor.getSession().getAnnotations();
for (var k=0; k < annotations.length; k++) {
if (annotations[k].type === "error") {
errorCount += annotations.length;
break;
}
}
// Give the "Javascript" tabsheet a red color if the generated javascript code contains (syntax) errors
if (errorCount > 0) {
$("#red-ui-tab-node-blockly-tab-javascript").css('background-color', "#EC7055");
}
else {
// No (syntax) errors in the generated java
$("#red-ui-tab-node-blockly-tab-javascript").css('background-color', "#FFFFFF");
}
*/
}
function fillAceXMLEditor(node) {
// Jeff: fill aceXMLEditor 04/18/2021
// Store the number of output ports in Blockly, so the blocks can take that number into account (if required)
//Blockly.nodeOutputs = $("#node-input-outputs").val();
// Generate JavaScript code from the workspace content
var dom = Blockly.Xml.workspaceToDom(node.workspace);
var loadedxml = Blockly.Xml.domToPrettyText(dom);
// Show the generated XML code in the Ace editor
node.aceXMLEditor.setValue(loadedxml);
// After setValue all code will be selected otherwise
// Fix for clearSelection (see https://github.com/bartbutenaers/node-red-contrib-blockly/issues/74#issuecomment-862681796)
node.aceXMLEditor.moveCursorTo(0,0);
}
function reloadBlockly(node) {
// Jeff: fill aceXMLEditor 04/18/2021
var loadedXml = node.aceXMLEditor.getValue();
//var dom = Blockly.Xml.textToDom(loadedXml);
//node.workspace.clear();
//Blockly.Xml.domToWorkspace(dom, node.workspace);
createWorkspace(node, loadedXml);
}
RED.nodes.registerType('Blockly',{
category: 'function',
color: '#FFAAAA',
defaults: {
// The generated Javascript code.
// Make sure we start without (generated) javascript code, because the Blockly workspace is also empty for new nodes.
// That way the (empty) Blockly workspace at startup is in sync with the (empty) Javascript tabsheet.
func: {value:""},
workspaceXml: {value:"<xml xmlns=\"https:\/\/developers.google.com\/blockly\/xml\"><\/xml>"}, // Needed for Blockly version "5.20210325.1". Can't be empty
outputs: {value:1}, // Standard field that will be used by Node-Red to draw N output ports in the flow editor,
timeout: {value:RED.settings.functionTimeout || 0},
blocklyConfig: {type: "blockly-config", required: false}, // No default value (see https://discourse.nodered.org/t/default-config-node/46773/9?u=bartbutenaers)
backpackContents: {value:[]},
// Use the noerr property to let Node-RED know whether the generated Javascript contains a syntax error or not.
// This way the flow editor knows whether a red triangle should be drawn for this node or not.
// The noerr property will be filled in the oneditsave, since it is useless to check the code for syntax errors every time the validator is called.
// Normally the generated function should never contain syntax errors, but due to an issue in the code generator in some block this might happen ...
noerr: {value:0,required:true, validate:function(v) { return !v; }},
name: {value:""}
},
inputs:1,
outputs:1,
icon: "font-awesome/fa-puzzle-piece",
label: function() {
return this.name||"Blockly";
},
oneditprepare: function() {
var node = this;
node.librariesLoaded = false;
node.previousEnableBackPack = "none";
node.isTrayOpen = false;
// Show a default timeout value for older nodes
if(node.timeout === null || node.timeout === "" || (typeof node.timeout === "undefined")) {
$("#node-input-timeout").val(RED.settings.functionTimeout || 0);
}
$("#node-input-outputs").spinner({
min:1,
change: function(event, ui) {
var value = this.value;
if (!value.match(/^\d+$/)) { value = 1; }
else if (value < this.min) { value = this.min; }
if (value !== this.value) { $(this).spinner("value", value); }
// Make sure the Blockly node_send and node_return_message blocks are always aware about the number of outputs
Blockly.nodeOutputs = parseInt(value);
var blocks = node.workspace.getAllBlocks();
for(var i = 0; i < blocks.length; i++) {
if (blocks[i].type === "node_send" || blocks[i].type === "node_return_message") {
if( parseInt(blocks[i].getFieldValue('OUTPUT_NR')) > parseInt(value)) {
alert("There are '" + blocks[i].type.replace(/_/g, ' ') + "' blocks available that use a higher output number");
break;
}
}
}
}
});
// 4294967 is max in node.js timeout.
$("#node-input-timeout").spinner({
min: 0,
max: 4294967,
change: function(event, ui) {
var value = this.value;
if(value == ""){
value = 0;
}
else
{
value = parseInt(value);
}
value = isNaN(value) ? 1 : value;
value = Math.max(value, parseInt($(this).attr("aria-valuemin")));
value = Math.min(value, parseInt($(this).attr("aria-valuemax")));
if (value !== this.value) { $(this).spinner("value", value); }
}
});
node.aceEditor = RED.editor.createEditor({
id: 'aceDiv',
mode: 'ace/mode/nrjavascript', // serverside NodeRed editor
value: node.func,
readOnly: true,
renderValidationDecorations: "on" // See https://discourse.nodered.org/t/show-errors-in-ace-and-monaco-editor/48529/12?u=bartbutenaers
});
node.aceEditor.setFontSize(14);
// Jeff: create XML editor
node.aceXMLEditor = RED.editor.createEditor({
id: 'aceXMLDiv',
mode: 'ace/mode/xml',
value: node.workspaceXml,
readOnly: true
});
node.aceXMLEditor.setFontSize(12);
// Jeff: invoke when either fillAceXMLEditor triggered or loaded XML from library
node.aceXMLEditor.on("change", function () {
var loadedXml = node.aceXMLEditor.getValue();
// Jeff: it seems everytime anything loads to the editor it removes the previous contents and then inject the new contents.
// so there are two changes.
if (loadedXml != "") {
Blockly.nodeOutputs = parseInt($("#node-input-outputs")[0].value);
createWorkspace(node, loadedXml);
}
});
// Show three tabsheets
var tabs = RED.tabs.create({
id: "node-blockly-tabs",
onchange: function(tab) {
// Show only the content (i.e. the children) of the selected tabsheet, and hide the others
$("#node-blockly-tabs-content").children().hide();
$("#" + tab.id).show();
// We will also arrive here when addTab is being called. In that case it has on use to continue...
if (node.librariesLoaded) {
// Every time the ace editor is displayed, the Javascript code should be regenerated (from the Blockly workspace);
// and the xml editor should be refilled (from the Blockly workspace)
if (tab.id === "node-blockly-tab-javascript") {
fillAceXMLEditor(node);
fillAceEditor(node);
}
if (tab.id === "node-blockly-tab-xml") {
fillAceXMLEditor(node);
}
if (tab.id === "node-blockly-tab-workspace") {
reloadBlockly(node);
}
}
}
});
tabs.addTab({
id: "node-blockly-tab-workspace",
label: "Editor"
});
// Put the expand button on top of the workspace tab
let expand_button = $('<div style="position: absolute; left: calc(100% - 20px - 5px); top: -1px; z-index: 99;">');
expand_button.append($('<button id="blocklyExpandDiv" class="red-ui-button red-ui-button-small"><i class="fa fa-expand"></i></button>'));
$('#red-ui-tab-node-blockly-tab-workspace').append(expand_button);
tabs.addTab({
id: "node-blockly-tab-javascript",
label: "Generated Javascript"
});
tabs.addTab({
id: "node-blockly-tab-xml",
label: "Generated XML"
});
// Store the loaded config node id (temporarliy) in the node, because the blockly-node's config screen will
// be cleaned up before we navigate to the tray screen. From then on the $("#node-input-blocklyConfig") won't be accessible anymore...
// Don't use node.blocklyConfig for this purpose, because that need to be unchanged in case the "Cancel" button is clicked.
node.selectedConfigNodeId = $("#node-input-blocklyConfig").val();
// Need to wait for it to be rendered before the sizing of the tabs can be properly calculated
setTimeout(function() {
tabs.resize();
}, 0);
RED.library.create({
url:"blockly_functions", // where to get the data from
type:"Blockly", // the type of object the library is for
// Jeff: load XML to aceXMLEditor instead aceEditor
editor:node.aceXMLEditor, // the field name the main text body goes to
mode:"ace/mode/xml",
fields:['name','outputs','timeout']
});
// Display a tip if the Node-Red version is below 0.19.0
var versionParts = RED.settings.version.split('.');
if (versionParts[0] == 0 && versionParts[1] < 19) {
$("#tip-version").show();
} else {
$("#tip-version").hide();
}
//Jeff: called when the expand button clicked
var expandTemplate =
'<!-- Blockly editor -->'+
'<div id="blocklyArea" style="width: 100%; height: 100%; min-height:350px;">'+
'<div id="blocklyDiv"></div>'+
'</div>'+
'<div id="jsArea" class="form-row node-text-editor-row" style="width: 100%; height: 100%; min-height:350px; display: none;">'+
'<div id="aceDiv" style="width: 100%; height: 100%;"></div>'+
'</div>';
var expandBlocklyHandler = function() {
return function(e) {
e.preventDefault();
RED.view.state(RED.state.EDITING);
var trayOptions = {
title: "Blockly Workspace",
width: "Infinity",
buttons: [
{
id: "node-showBlocklyArea",
text: "Back to Blockly Editor",
click: function() {
$("#jsArea").css("display","none");
$("#blocklyArea").css("display","block");
$("#node-showJSArea").css("display","block");
$("#node-showBlocklyArea").css("display","none");
var dom = Blockly.Xml.workspaceToDom(node.workspace);
var loadedXml = Blockly.Xml.domToPrettyText(dom);
createWorkspace(node, loadedXml);
}
},
{
id: "node-showJSArea",
text: "See Generated Javascript",
click: function() {
$("#blocklyArea").css("display","none");
$("#jsArea").css("display","block");
$("#node-showBlocklyArea").css("display","block");
$("#node-showJSArea").css("display","none");
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
var javascript = Blockly.JavaScript.workspaceToCode(node.workspace);
node.jseditor.setValue(javascript);
// Fix for clearSelection (see https://github.com/bartbutenaers/node-red-contrib-blockly/issues/74#issuecomment-862681796)
node.jseditor.moveCursorTo(0,0);
}
},
{
id: "node-dialog-cancel",
text: RED._("common.label.cancel"),
click: function() {
var loadedXml = node.loadedXml;
node.isTrayOpen = false;
//Jeff: re-create workspace after RED.tray.close finished
RED.tray.close(() => createWorkspace(node, loadedXml));
}
},
{
id: "node-dialog-ok",
text: RED._("common.label.done"),
class: "primary",
click: function() {
var dom = Blockly.Xml.workspaceToDom(node.workspace);
var loadedXml = Blockly.Xml.domToPrettyText(dom);
node.isTrayOpen = false;
RED.tray.close(() => createWorkspace(node, loadedXml));
}
}
],
resize: function(dimensions) {
var height = $("#blocklyArea").height();
var width = $("#blocklyArea").width();
$("#blocklyDiv").css("height",height+"px");
$("#blocklyDiv").css("width",width+"px");
Blockly.svgResize(node.workspace);
node.workspace.scrollCenter();
},
open: function(tray) {
$("#node-showBlocklyArea").css({"float":"left","display":"none"});
$("#node-showJSArea").css("float","left");
var trayBody = tray.find('.red-ui-tray-body');
//var blocklyAreaContent = $('<div id="blocklyArea" style="width: 100%; height: 100%; min-height:700px;"></div>').appendTo(trayBody);
//var blocklyDivContent = $('<div id="blocklyDiv"></div>').appendTo(blocklyAreaContent);
$(expandTemplate).appendTo(trayBody);
//Jeff: load workspace to a temp XML
var dom = Blockly.Xml.workspaceToDom(node.workspace);
node.loadedXml = Blockly.Xml.domToPrettyText(dom);
createWorkspace(node, node.loadedXml);
node.jseditor = RED.editor.createEditor({
id: 'aceDiv',
mode: 'ace/mode/nrjavascript', // serverside NodeRed editor
value: node.func,
readOnly: true
});
node.jseditor.setFontSize(14);
},
close: function() {
delete node.loadedXml;
node.jseditor.destroy();
delete node.jseditor;
},
show: function() {
}
}
node.isTrayOpen = true;
RED.tray.show(trayOptions);
}
}
//Jeff: expand Blockly editing area
$("#blocklyExpandDiv").on("click", expandBlocklyHandler());
// When a new config is selected, a new Blockly workspace should be drawn (with the new config settings)
$("#node-input-blocklyConfig").on('change', function(event) {
// Store the newly selected config node id (temporarliy) in the node, because the blockly-node's config screen will
// be cleaned up before we navigate to the tray screen. From then on the $("#node-input-blocklyConfig") won't be accessible anymore...
// Don't use node.blocklyConfig for this purpose, because that need to be unchanged in case the "Cancel" button is clicked.
node.selectedConfigNodeId = $("#node-input-blocklyConfig").val();
var counter = 0;
var language = "en";
var categories;
if (node.selectedConfigNodeId && node.selectedConfigNodeId !== "_ADD_") {
var configNode = RED.nodes.node(node.selectedConfigNodeId);
if (configNode) {
if (configNode.language) {
language = configNode.language;
}
// Only when the "customize toolbox categories" checkbox is enabled (in the config node screen), we will use the custom categories.
if (configNode.customizeToolbox) {
categories = configNode.categories;
}
}
}
// Load all the files from the servers, as specified in the config node.
// This also includes the language files. At the start we have loaded the en.js files, because we are sure that all sentences
// are available in english. Afterwards other language files can be loaded, thus overwriting the english sentences. By doing
// it that way, missing sentences in the translations are not a problem (since those sentences will simply be displayed in english).
// CAUTION: the "blockly-contrib/npm/blockly/msg/en.js" file contains a Blockly.Msg = {} , which means all previous loaded
// messages will be removed!
if (node.workspace) {
// When there has been a previous workspace, show the content of that workspace.
// Because that workspace might have changes (which have not been stored yet into node.workspaceXml), which need to be kept
var dom = Blockly.Xml.workspaceToDom(node.workspace);
node.workspaceXml = Blockly.Xml.domToPrettyText(dom);
}
loadResourcesFromServer(node, language, categories);
});
// This is being called by Node-RED also $("#node-input-blocklyConfig").change();
},
oneditsave: function() {
var node = this;
// Store the number of output ports in Blockly, so the blocks can take that number into account (if required)
//Blockly.nodeOutputs = $("#node-input-outputs").val();