/
monaco.js
1454 lines (1336 loc) · 73.7 KB
/
monaco.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
/*
* 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.
**/
/**
* @namespace RED.editor.codeEditor.monaco
*/
/*
The code editor currenlty supports 2 functions init and create.
* Init() - setup the editor / must return true
* Create() - create an editor instance / returns an editor as generated by the editor lib
* To be compatable with the original ace lib (for contrib nodes using it), the object returned by create() must (at minimum) support the following...
property .selection = {};
function .selection.getRange();
property .session //the editor object
function .session.insert = function(position, text)
function .setReadOnly(readOnly)
property .renderer = {};
function .renderer.updateFull()
function setMode(mode, cb)
function getRange();
function replace(range, text)
function selectAll
function clearSelection
function getSelectedText()
function destroy()
function resize()
function getSession()
function getLength()
function scrollToLine(lineNumber, scrollType)
function moveCursorTo(lineNumber, colNumber)
function getAnnotations()
function gotoLine(row, col)
function getCursorPosition()
function setTheme(name)
function setFontSize(size:Number) //Set a new font size (in pixels) for the editor text.
function on(name, cb)
function getUndoManager()
*/
RED.editor.codeEditor.monaco = (function() {
var initialised = false;
const type = "monaco";
const monacoThemes = ["vs","vs-dark","hc-black"]; //TODO: consider setting hc-black autmatically based on acessability?
let userSelectedTheme;
//TODO: get from externalModules.js For now this is enough for feature parity with ACE (and then some).
const knownModules = {
"assert": {package: "node", module: "assert", path: "node/assert.d.ts" },
"assert/strict": {package: "node", module: "assert/strict", path: "node/assert/strict.d.ts" },
"async_hooks": {package: "node", module: "async_hooks", path: "node/async_hooks.d.ts" },
"buffer": {package: "node", module: "buffer", path: "node/buffer.d.ts" },
"child_process": {package: "node", module: "child_process", path: "node/child_process.d.ts" },
"cluster": {package: "node", module: "cluster", path: "node/cluster.d.ts" },
"console": {package: "node", module: "console", path: "node/console.d.ts" },
"crypto": {package: "node", module: "crypto", path: "node/crypto.d.ts" },
"dgram": {package: "node", module: "dgram", path: "node/dgram.d.ts" },
"diagnostics_channel.d": {package: "node", module: "diagnostics_channel", path: "node/diagnostics_channel.d.ts" },
"dns": {package: "node", module: "dns", path: "node/dns.d.ts" },
"dns/promises": {package: "node", module: "dns/promises", path: "node/dns/promises.d.ts" },
"domain": {package: "node", module: "domain", path: "node/domain.d.ts" },
"events": {package: "node", module: "events", path: "node/events.d.ts" },
"fs": {package: "node", module: "fs", path: "node/fs.d.ts" },
"fs/promises": {package: "node", module: "fs/promises", path: "node/fs/promises.d.ts" },
"globals": {package: "node", module: "globals", path: "node/globals.d.ts" },
"http": {package: "node", module: "http", path: "node/http.d.ts" },
"http2": {package: "node", module: "http2", path: "node/http2.d.ts" },
"https": {package: "node", module: "https", path: "node/https.d.ts" },
"module": {package: "node", module: "module", path: "node/module.d.ts" },
"net": {package: "node", module: "net", path: "node/net.d.ts" },
"os": {package: "node", module: "os", path: "node/os.d.ts" },
"path": {package: "node", module: "path", path: "node/path.d.ts" },
"perf_hooks": {package: "node", module: "perf_hooks", path: "node/perf_hooks.d.ts" },
"process": {package: "node", module: "process", path: "node/process.d.ts" },
"querystring": {package: "node", module: "querystring", path: "node/querystring.d.ts" },
"readline": {package: "node", module: "readline", path: "node/readline.d.ts" },
"stream": {package: "node", module: "stream", path: "node/stream.d.ts" },
"stream/consumers": {package: "node", module: "stream/consumers", path: "node/stream/consumers.d.ts" },
"stream/promises": {package: "node", module: "stream/promises", path: "node/stream/promises.d.ts" },
"stream/web": {package: "node", module: "stream/web", path: "node/stream/web.d.ts" },
"string_decoder": {package: "node", module: "string_decoder", path: "node/string_decoder.d.ts" },
"test": {package: "node", module: "test", path: "node/test.d.ts" },
"timers": {package: "node", module: "timers", path: "node/timers.d.ts" },
"timers/promises": {package: "node", module: "timers/promises", path: "node/timers/promises.d.ts" },
"tls": {package: "node", module: "tls", path: "node/tls.d.ts" },
"trace_events": {package: "node", module: "trace_events", path: "node/trace_events.d.ts" },
"tty": {package: "node", module: "tty", path: "node/tty.d.ts" },
"url": {package: "node", module: "url", path: "node/url.d.ts" },
"util": {package: "node", module: "util", path: "node/util.d.ts" },
"v8": {package: "node", module: "v8", path: "node/v8.d.ts" },
"vm": {package: "node", module: "vm", path: "node/vm.d.ts" },
"wasi": {package: "node", module: "wasi", path: "node/wasi.d.ts" },
"worker_threads": {package: "node", module: "worker_threads", path: "node/worker_threads.d.ts" },
"zlib": {package: "node", module: "zlib", path: "node/zlib.d.ts" },
"node-red": {package: "node-red", module: "node-red", path: "node-red/index.d.ts" }, //only used if node-red types are concated by grunt.
"node-red-util": {package: "node-red", module: "util", path: "node-red/util.d.ts" },
"node-red-func": {package: "node-red", module: "func", path: "node-red/func.d.ts" },
}
const defaultServerSideTypes = [ knownModules["node-red-util"], knownModules["node-red-func"], knownModules["globals"], knownModules["console"], knownModules["buffer"], knownModules["timers"] , knownModules["util"] ];
const modulesCache = {};
/**
* Helper function to load/reload types.
* @param {string} mod - type lib to load. Only known libs are currently supported.
* @param {boolean} preloadOnly - only cache the lib
* @param {object} loadedLibs - an object used to track loaded libs (needed to destroy them upon close)
*/
function _loadModuleDTS(mod, preloadOnly, loadedLibs, cb) {
var _module;
if(typeof mod == "object") {
_module = mod;
} else {
_module = knownModules[mod];
}
if(_module) {
const libPackage = _module.package;
const libModule = _module.module;
const libPath = _module.path;
const def = modulesCache[libPath];
if( def ) {
if(!preloadOnly) {
loadedLibs.JS[libModule] = monaco.languages.typescript.javascriptDefaults.addExtraLib(def, "file://types/" + libPackage + "/" + libModule + "/index.d.ts");
}
if(cb) {
setTimeout(function() {
cb(null, _module);
}, 5);
}
} else {
var typePath = "types/" + libPath;
$.get(typePath)
.done(function(data) {
modulesCache[libPath] = data;
if(!preloadOnly) {
loadedLibs.JS[libModule] = monaco.languages.typescript.javascriptDefaults.addExtraLib(data, "file://types/" + libPackage + "/" + libModule + "/index.d.ts");
}
if(cb) { cb(null, _module) }
})
.fail(function(err) {
var warning = "Failed to load '" + typePath + "'";
modulesCache[libPath] = "/* " + warning + " */\n"; //populate the extraLibs cache to revent retries
if(cb) { cb(err, _module) }
console.warn(warning);
});
}
}
}
function init(options) {
//Handles orphaned models
//ensure loaded models that are not explicitly destroyed by a call to .destroy() are disposed
RED.events.on("editor:close",function() {
let models = window.monaco ? monaco.editor.getModels() : null;
if(models && models.length) {
console.warn("Cleaning up monaco models left behind. Any node that calls createEditor() should call .destroy().")
for (let index = 0; index < models.length; index++) {
const model = models[index];
if(!model.isDisposed()) {
model.dispose();
}
}
}
});
options = options || {};
window.MonacoEnvironment = window.MonacoEnvironment || {};
window.MonacoEnvironment.getWorkerUrl = window.MonacoEnvironment.getWorkerUrl || function (moduleId, label) {
if (label === 'json') { return './vendor/monaco/dist/json.worker.js'; }
if (label === 'css' || label === 'scss') { return './vendor/monaco/dist/css.worker.js'; }
if (label === 'html' || label === 'handlebars') { return './vendor/monaco/dist/html.worker.js'; }
if (label === 'typescript' || label === 'javascript') { return './vendor/monaco/dist/ts.worker.js'; }
return './vendor/monaco/dist/editor.worker.js';
};
var editorSettings = RED.editor.codeEditor.settings || {};
var editorOptions = editorSettings.options || {};
//if editorOptions.theme is an object (set in theme.js context()), use the plugin theme name as the monaco theme name
//if editorOptions.theme is a string, it should be the name of a pre-set theme, load that
try {
const addTheme = function (themeThemeName, theme) {
if ((theme.rules && Array.isArray(theme.rules)) || theme.colors) {
monacoThemes.push(themeThemeName); //add to list of loaded themes
monaco.editor.defineTheme(themeThemeName, theme);
monaco.editor.setTheme(themeThemeName);
userSelectedTheme = themeThemeName;
}
};
if (editorOptions.theme) {
if (typeof editorOptions.theme == "object" && RED.settings.editorTheme.theme) {
let themeThemeName = editorOptions.theme.name || RED.settings.editorTheme.theme;
addTheme(themeThemeName, editorOptions.theme);
} else if (typeof editorOptions.theme == "string") {
let themeThemeName = editorOptions.theme;
if (!monacoThemes.includes(themeThemeName)) {
$.get('vendor/monaco/dist/theme/' + themeThemeName + '.json', function (theme) {
addTheme(themeThemeName, theme);
});
}
}
}
} catch (error) {
console.warn(error);
}
//Helper function to simplify snippet setup
function createMonacoCompletionItem(label, insertText, documentation, range, kind) {
if (Array.isArray(documentation)) { documentation = documentation.join("\n"); }
return {
label: label,
kind: kind == null ? monaco.languages.CompletionItemKind.Snippet : kind,
documentation: { value: documentation },
insertText: insertText,
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
range: range
}
}
function setupJSONata(_monaco) {
// Register the language 'jsonata'
_monaco.languages.register({ id: 'jsonata' });
// Setup tokens for JSONata
_monaco.languages.setMonarchTokensProvider('jsonata',
{
// Set defaultToken to invalid to see what you do not tokenize yet
defaultToken: 'invalid',
tokenPostfix: '.js',
keywords: ["function", "true", "true", "null", "Infinity", "NaN", "undefined"].concat(Object.keys(jsonata.functions)),
// keywords: [
// "function", "$abs", "$append", "$assert", "$average",
// "$base64decode", "$base64encode", "$boolean", "$ceil", "$contains",
// "$count", "$decodeUrl", "$decodeUrlComponent", "$distinct", "$each", "$encodeUrl",
// "$encodeUrlComponent", "$env", "$error", "$eval", "$exists", "$filter", "$floor",
// "$flowContext", "$formatBase", "$formatInteger", "$formatNumber", "$fromMillis",
// "$globalContext", "$join", "$keys", "$length", "$lookup", "$lowercase", "$map",
// "$match", "$max", "$merge", "$millis", "$min", "$moment", "$not", "$now",
// "$number", "$pad", "$parseInteger", "$power", "$random", "$reduce", "$replace",
// "$reverse", "$round", "$shuffle", "$sift", "$single", "$sort", "$split",
// "$spread", "$sqrt", "$string", "$substring", "$substringAfter", "$substringBefore",
// "$sum", "$toMillis", "$trim", "$type", "$uppercase", "$zip"
// ],
operatorsKeywords: [ 'and', 'or', 'in' ],
operators: [
'<=', '>=', '!=', '==', '!=', '=>', '+', '-', '*', '/', '%',
':=', '~>', '?', ':', '..', '@', '#', '|', '^', '*', '**',
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\/\^%@#]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
digits: /\d+(_+\d+)*/,
octaldigits: /[0-7]+(_+[0-7]+)*/,
binarydigits: /[0-1]+(_+[0-1]+)*/,
hexdigits: /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,
regexpctl: /[(){}\[\]\$\^|\-*+?\.]/,
regexpesc: /\\(?:[bBdDfnrstvwWn0\\\/]|@regexpctl|c[A-Z]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/,
// The main tokenizer
tokenizer: {
root: [
[/[{}]/, 'delimiter.bracket'],
{ include: 'common' }
],
common: [
// identifiers and keywords
[/([a-zA-Z][\w$]*)|([$][\w$]*)/, {
cases: {
'@keywords': 'keyword',
'@operatorsKeywords': 'keyword',
'$2': 'variable', //when its not a key word but starts with $, use "tag" for colourisation
//'$2': 'tag', //when its not a key word but starts with $, use "tag" for colourisation
//'$2': 'constant', //alt colourisation
//'$2': 'attribute', //alt colourisation
//'$2': 'identifier.variable', //alt custom colourisation
'@default': 'identifier'
}
}],
[/[$][\w\$]*/, 'variable'],
// whitespace
{ include: '@whitespace' },
// regular expression: ensure it is terminated before beginning (otherwise it is an opeator)
[/\/(?=([^\\\/]|\\.)+\/([gimsuy]*)(\s*)(\.|;|\/|,|\)|\]|\}|$))/, { token: 'regexp', bracket: '@open', next: '@regexp' }],
// delimiters and operators
[/[()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/(@symbols)|(\.\.)/, {
cases: {
'@operators': 'operator',
'@default': ''
}
}],
// numbers
[/(@digits)[eE]([\-+]?(@digits))?/, 'number.float'],
[/(@digits)\.(@digits)([eE][\-+]?(@digits))?/, 'number.float'],
[/0[xX](@hexdigits)/, 'number.hex'],
[/0[oO]?(@octaldigits)/, 'number.octal'],
[/0[bB](@binarydigits)/, 'number.binary'],
[/(@digits)/, 'number'],
// delimiter: after number because of .\d floats
[/[?:;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string
[/'([^'\\]|\\.)*$/, 'string.invalid'], // non-teminated string
[/"/, 'string', '@string_double'],
[/'/, 'string', '@string_single'],
[/`/, 'string', '@string_backtick'],
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/\/\*\*(?!\/)/, 'comment.doc', '@jsdoc'],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],
comment: [
[/[^\/*]+/, 'comment'],
[/\*\//, 'comment', '@pop'],
[/[\/*]/, 'comment']
],
jsdoc: [
[/[^\/*]+/, 'comment.doc'],
[/\*\//, 'comment.doc', '@pop'],
[/[\/*]/, 'comment.doc']
],
// We match regular expression quite precisely
regexp: [
[/(\{)(\d+(?:,\d*)?)(\})/, ['regexp.escape.control', 'regexp.escape.control', 'regexp.escape.control']],
[/(\[)(\^?)(?=(?:[^\]\\\/]|\\.)+)/, ['regexp.escape.control', { token: 'regexp.escape.control', next: '@regexrange' }]],
[/(\()(\?:|\?=|\?!)/, ['regexp.escape.control', 'regexp.escape.control']],
[/[()]/, 'regexp.escape.control'],
[/@regexpctl/, 'regexp.escape.control'],
[/[^\\\/]/, 'regexp'],
[/@regexpesc/, 'regexp.escape'],
[/\\\./, 'regexp.invalid'],
[/(\/)([gimsuy]*)/, [{ token: 'regexp', bracket: '@close', next: '@pop' }, 'keyword.other']],
],
regexrange: [
[/-/, 'regexp.escape.control'],
[/\^/, 'regexp.invalid'],
[/@regexpesc/, 'regexp.escape'],
[/[^\]]/, 'regexp'],
[/\]/, { token: 'regexp.escape.control', next: '@pop', bracket: '@close' }],
],
string_double: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@pop']
],
string_single: [
[/[^\\']+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/'/, 'string', '@pop']
],
string_backtick: [
[/\$\{/, { token: 'delimiter.bracket', next: '@bracketCounting' }],
[/[^\\`$]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/`/, 'string', '@pop']
],
bracketCounting: [
[/\{/, 'delimiter.bracket', '@bracketCounting'],
[/\}/, 'delimiter.bracket', '@pop'],
{ include: 'common' }
],
},
}
);
// Setup JSONata language config
_monaco.languages.setLanguageConfiguration('jsonata', {
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: "'", close: "'", notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['string'] }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: "'", close: "'" },
{ open: '<', close: '>' }
],
folding: {
markers: {
start: new RegExp('^\\s*//\\s*(?:(?:#?region\\b)|(?:<editor-fold\\b))'),
end: new RegExp('^\\s*//\\s*(?:(?:#?endregion\\b)|(?:</editor-fold>))')
}
}
});
// Register a completion item provider for JSONata snippets
_monaco.languages.registerCompletionItemProvider('jsonata', {
provideCompletionItems: function (model, position) {
var _word = model.getWordUntilPosition(position);
if (!_word) { return; }
var startColumn = _word.startColumn;
var word = _word.word;
if (word[0] !== "$" && position.column > 1) { startColumn--; }
var range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: startColumn,
endColumn: _word.endColumn
};
var jsonataFunctions = Object.keys(jsonata.functions);
var jsonataSuggestions = jsonataFunctions.map(function (f) {
var args = RED._('jsonata:' + f + '.args', { defaultValue: '' });
var title = f + '(' + args + ')';
var body = RED._('jsonata:' + f + '.desc', { defaultValue: '' });
var insertText = (jsonata.getFunctionSnippet(f) + '').trim();
var documentation = { value: '`' + title + '`\n\n' + body };
return createMonacoCompletionItem(f, insertText, documentation, range, monaco.languages.CompletionItemKind.Function);
});
// sort in length order (long->short) otherwise substringAfter gets matched as substring etc.
jsonataFunctions.sort(function (A, B) {
return B.length - A.length;
});
// add snippets to suggestions
jsonataSuggestions.unshift(
createMonacoCompletionItem("randominteger", '(\n\t\\$minimum := ${1:1};\n\t\\$maximum := ${2:10};\n\t\\$round((\\$random() * (\\$maximum-\\$minimum)) + \\$minimum, 0)\n)', 'Random integer between 2 numbers', range)
);//TODO: add more JSONata snippets
return { suggestions: jsonataSuggestions };
}
});
// Register a hover provider for JSONata functions
_monaco.languages.registerHoverProvider('jsonata', {
provideHover: function (model, position) {
var w = model.getWordAtPosition(position);
var f = w && w.word;
if (!f) {return;}
if (f[0] !== "$" && position.column > 1) {
f = "$" + f;
} else {
return;
}
var args = RED._('jsonata:' + f + ".args", { defaultValue: '' });
if (!args) {return;}
var title = f + "(" + args + ")";
var body = RED._('jsonata:' + f + '.desc', { defaultValue: '' });
/** @type {monaco.Range} */
var r = new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column + w.word.length);
return {
range: r,
contents: [
{ value: '**`' + title + '`**' },
// { value: '```html\n' + body + '\n```' },
{ value: body },
]
}
}
});
}
function setupJSON(_monaco) {
//Setup JSON options
try {
var diagnosticOptionsDefault = {validate: true};
var diagnosticOptions = RED.settings.get('codeEditor.monaco.languages.json.jsonDefaults.diagnosticOptions');
var modeConfiguration = RED.settings.get('codeEditor.monaco.languages.json.jsonDefaults.modeConfiguration');
diagnosticOptions = Object.assign({}, diagnosticOptionsDefault, (diagnosticOptions || {}));
_monaco.languages.json.jsonDefaults.setDiagnosticsOptions(diagnosticOptions);
if(modeConfiguration) { _monaco.languages.json.jsonDefaults.setModeConfiguration(modeConfiguration); }
} catch (error) {
console.warn("monaco - Error setting up json options", err)
}
}
function setupHTML(_monaco) {
//Setup HTML / Handlebars options
try {
var htmlDefaults = RED.settings.get('codeEditor.monaco.languages.html.htmlDefaults.options');
var handlebarDefaults = RED.settings.get('codeEditor.monaco.languages.html.handlebarDefaults.options');
if(htmlDefaults) { _monaco.languages.html.htmlDefaults.setOptions(htmlDefaults); }
if(handlebarDefaults) { _monaco.languages.html.handlebarDefaults.setOptions(handlebarDefaults); }
} catch (error) {
console.warn("monaco - Error setting up html options", err)
}
}
function setupCSS(_monaco) {
//Setup CSS/SCSS/LESS options
try {
var cssDefaults_diagnosticsOption = RED.settings.get('codeEditor.monaco.languages.css.cssDefaults.diagnosticsOptions');
var lessDefaults_diagnosticsOption = RED.settings.get('codeEditor.monaco.languages.css.lessDefaults.diagnosticsOption');
var scssDefaults_diagnosticsOption = RED.settings.get('codeEditor.monaco.languages.css.scssDefaults.diagnosticsOption');
var cssDefaults_modeConfiguration = RED.settings.get('codeEditor.monaco.languages.css.cssDefaults.modeConfiguration');
var lessDefaults_modeConfiguration = RED.settings.get('codeEditor.monaco.languages.css.lessDefaults.modeConfiguration');
var scssDefaults_modeConfiguration = RED.settings.get('codeEditor.monaco.languages.css.scssDefaults.modeConfiguration');
if(cssDefaults_diagnosticsOption) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(cssDefaults_diagnosticsOption); }
if(lessDefaults_diagnosticsOption) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(lessDefaults_diagnosticsOption); }
if(scssDefaults_diagnosticsOption) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(scssDefaults_diagnosticsOption); }
if(cssDefaults_modeConfiguration) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(cssDefaults_modeConfiguration); }
if(lessDefaults_modeConfiguration) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(lessDefaults_modeConfiguration); }
if(scssDefaults_modeConfiguration) { _monaco.languages.css.cssDefaults.setDiagnosticsOptions(scssDefaults_modeConfiguration); }
} catch (error) {
console.warn("monaco - Error setting up CSS/SCSS/LESS options", err)
}
}
function setupJS(_monaco) {
var createJSSnippets = function(range) {
return [
//TODO: i18n for snippet descriptions?
createMonacoCompletionItem("dowhile", 'do {\n\t${2}\n} while (${1:condition});','Do-While Statement (JavaScript Language Basics)',range),
createMonacoCompletionItem("while", 'while (${1:condition}) {\n\t${2}\n}','While Statement (JavaScript Language Basics)',range),
createMonacoCompletionItem("switch", 'switch (${1:msg.topic}) {\n\tcase ${2:"value"}:\n\t\t${3}\n\t\tbreak;\n\tdefault:\n\t\t\n}','Switch Statement (JavaScript Language Basics)',range),
createMonacoCompletionItem("trycatch", 'try {\n\t${2}\n} catch (${1:error}) {\n\t\n};','Try-Catch Statement (JavaScript Language Basics)',range),
createMonacoCompletionItem("for (for loop)", 'for (let ${1:index} = 0; ${1:index} < ${2:array}.length; ${1:index}++) {\n\tconst element = ${2:array}[${1:index}];\n\t${3}\n}','for loop',range),
createMonacoCompletionItem("foreach", '${1:array}.forEach(function(${2:element}) {\n\t${3}\n});','forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void\n\nA function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.',range),
createMonacoCompletionItem("forin", 'for (${1:prop} in ${2:obj}) {\n\tif (${2:obj}.hasOwnProperty(${1:prop})) {\n\t\t${3}\n\t}\n}','for in',range),
createMonacoCompletionItem("forof", 'for (const ${1:iterator} of ${2:object}) {\n\t${3}\n}','for of',range),
createMonacoCompletionItem("function", 'function ${1:methodName}(${2:arguments}) {\n\t${3}\n}','Function Declaration',range),
createMonacoCompletionItem("func (anonymous function)", 'var ${1:fn} = function(${2:arguments}) {\n\t${3}\n}','Function Expression',range),
createMonacoCompletionItem("pt (prototype)", '${1:ClassName}.prototype.${2:methodName} = function(${3:arguments}) {\n\t${4}\n}','prototype',range),
createMonacoCompletionItem("iife", '(function(${1:arg}) {\n\t${1}\n})(${1:arg});','immediately-invoked function expression',range),
createMonacoCompletionItem("call (function call)", '${1:methodName}.call(${2:context}, ${3:arguments})','function call',range),
createMonacoCompletionItem("apply (function apply)", '${1:methodName}.apply(${2:context}, [${3:arguments}])','function apply',range),
createMonacoCompletionItem("jsonparse", 'JSON.parse(${1:json});','JSON.parse',range),
createMonacoCompletionItem("jsonstringify", 'JSON.stringify(${1:obj});','JSON.stringify',range),
createMonacoCompletionItem("setinterval", 'setInterval(function() {\n\t${2}\n}, ${1:delay});','setInterval',range),
createMonacoCompletionItem("settimeout", 'setTimeout(function() {\n\t${2}\n}, ${1:delay});','setTimeout',range),
createMonacoCompletionItem("node.log", 'node.log(${1:"info"});','Write an info message to the console (not sent to sidebar)',range),
createMonacoCompletionItem("node.warn", 'node.warn(${1:"my warning"});','Write a warning to the console and debug sidebar',range),
createMonacoCompletionItem("node.error", 'node.error(${1:"my error message"}, ${2:msg});','Send an error to the console and debug sidebar. To trigger a Catch node on the same tab, the function should call `node.error` with the original message as a second argument',range),
createMonacoCompletionItem("node.send", 'node.send(${1:msg});','async send a msg to the next node',range),
createMonacoCompletionItem("node.send (multiple)", 'var ${1:msg1} = {payload:${2:1}};\nvar ${3:msg2} = {payload:${4:2}};\nnode.send([[${1:msg1}, ${3:msg2}]]);','send 1 or more messages out of 1 output',range),
createMonacoCompletionItem("node.send (multiple outputs)", 'var ${1:msg1} = {payload:${2:1}};\nvar ${3:msg2} = {payload:${4:2}};\nnode.send([${1:msg1}, ${3:msg2}]);','send more than 1 message out of multiple outputs',range),
createMonacoCompletionItem("node.status", 'node.status({fill:"${1|red,green,yellow,blue,grey|}",shape:"${2|ring,dot|}",text:"${3:message}"});','Set the status icon and text underneath the function node',range),
createMonacoCompletionItem("get (node context)", 'context.get("${1:name}");','Get a value from node context',range),
createMonacoCompletionItem("set (node context)", 'context.set("${1:name}", ${1:value});','Set a value in node context',range),
createMonacoCompletionItem("get (flow context)", 'flow.get("${1:name}");','Get a value from flow context',range),
createMonacoCompletionItem("set (flow context)", 'flow.set("${1:name}", ${1:value});','Set a value in flow context',range),
createMonacoCompletionItem("get (global context)", 'global.get("${1:name}");','Get a value from global context',range),
createMonacoCompletionItem("set (global context)", 'global.set("${1:name}", ${1:value});','Set a value in global context',range),
createMonacoCompletionItem("get (env)", 'env.get("${1|NR_NODE_ID,NR_NODE_NAME,NR_NODE_PATH,NR_GROUP_ID,NR_GROUP_NAME,NR_FLOW_ID,NR_FLOW_NAME|}");','Get env variable value',range),
createMonacoCompletionItem("cloneMessage (RED.util)", 'RED.util.cloneMessage(${1:msg});',
["```typescript",
"RED.util.cloneMessage<T extends registry.NodeMessage>(msg: T): T",
"```",
"Safely clones a message object. This handles msg.req/msg.res objects that must not be cloned\n",
"*@param* `msg` — the msg object\n"],
range),
createMonacoCompletionItem("getObjectProperty (RED.util)", 'RED.util.getObjectProperty(${1:msg},${2:prop});',
["```typescript",
"RED.util.getObjectProperty(msg: object, expr: string): any;",
"```",
"Gets a property of an object\n",
"*@param* `msg` — the msg object\n",
"*@param* `prop` — the msg object"],
range),
createMonacoCompletionItem("setObjectProperty (RED.util)", 'RED.util.setObjectProperty(${1:msg},${2:prop},${3:value},${4:createMissing});',
["```typescript",
"RED.util.setObjectProperty(msg: object, prop: string, value: any, createMissing?: boolean): boolean",
"```",
"Sets a property of an object\n",
"`msg` — the object\n",
"`prop` — the property expression\n",
"`value` — the value to set\n",
"`createMissing` — whether to create missing parent properties"],
range),
createMonacoCompletionItem("getMessageProperty (RED.util)", 'RED.util.getMessageProperty(${1:msg},${2:prop});',
["```typescript",
"RED.util.getMessageProperty(msg: object, expr: string): any;",
"```",
"Gets a property of an object\n",
"*@param* `msg` — the msg object\n",
"*@param* `prop` — the msg object"],
range),
createMonacoCompletionItem("setMessageProperty (RED.util)", 'RED.util.setMessageProperty(${1:msg},${2:prop},${3:value},${4:createMissing});',
["```typescript",
"RED.util.setMessageProperty(msg: object, prop: string, value: any, createMissing?: boolean): boolean",
"```",
"Sets a property of an object\n",
"`msg` — the object\n",
"`prop` — the property expression\n",
"`value` — the value to set\n",
"`createMissing` — whether to create missing parent properties"],
range),
];
}
//register snippets
_monaco.languages.registerCompletionItemProvider('javascript', {
provideCompletionItems: function(model, position) {
var word = model.getWordUntilPosition(position);
var range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
return {
suggestions: createJSSnippets(range)
};
}
});
//setup JS/TS compiler & diagnostic options (defaults)
try {
//prepare compiler options
var compilerOptions = {
allowJs: true,
checkJs: true,
allowNonTsExtensions: true,
target: monaco.languages.typescript.ScriptTarget.ESNext,
strictNullChecks: false,
strictPropertyInitialization: true,
strictFunctionTypes: true,
strictBindCallApply: true,
useDefineForClassFields: true,//permit class static fields with private name to have initializer
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
module: monaco.languages.typescript.ModuleKind.CommonJS,
typeRoots: ["types"],
lib: ["esnext"] //dont load DOM by default,
}
//apply overrides from codeEditor.monaco.languages.typescript.javascriptDefaults.compilerOptions in settings.js
var settingsComilerOptions = RED.settings.get('codeEditor.monaco.languages.typescript.javascriptDefaults.compilerOptions') || {};
compilerOptions = Object.assign({}, compilerOptions, settingsComilerOptions);
/** @see https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.typescript.languageservicedefaults.html#setcompileroptions */
_monaco.languages.typescript.javascriptDefaults.setCompilerOptions(compilerOptions);
//prepare diagnostic options (defaults)
var diagnosticOptions = {
noSemanticValidation: false,
noSyntaxValidation: false,
diagnosticCodesToIgnore: [
1108, //return not inside function
1375, //'await' expressions are only allowed at the top level of a file when that file is a module
1378, //Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher
//2304, //Cannot find name - this one is heavy handed and prevents user seeing stupid errors. Would provide better ACE feature parity (i.e. no need for declaration of vars) but misses lots of errors. Lets be bold & leave it out!
2307, //Cannot find module 'xxx' or its corresponding type declarations
2322, //Type 'unknown' is not assignable to type 'string'
2339, //property does not exist on
2345, //Argument of type xxx is not assignable to parameter of type 'DateTimeFormatOptions'
7043, //i forget what this one is,
80001, //Convert to ES6 module
80004, //JSDoc types may be moved to TypeScript types.
]
};
//apply overrides from codeEditor.monaco.languages.typescript.javascriptDefaults.diagnosticsOptions settings.js
var settingsDiagnosticsOptions = RED.settings.get('codeEditor.monaco.languages.typescript.javascriptDefaults.diagnosticsOptions') || {};
diagnosticOptions = Object.assign({}, diagnosticOptions, settingsDiagnosticsOptions);
/** @see https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.typescript.languageservicedefaults.html#setdiagnosticsoptions */
_monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions(diagnosticOptions);
} catch (error) {
console.warn("monaco - Error setting javascriptDefaults", error)
}
}
setupJS(monaco);
setupJSONata(monaco);
setupJSON(monaco);
setupCSS(monaco);
setupHTML(monaco);
defaultServerSideTypes.forEach(function(m) {
_loadModuleDTS(m, true)//pre-load common libs
})
initialised = true;
return initialised;
}
function create(options) {
var editorSettings = RED.editor.codeEditor.settings || {};
var loadedLibs = {JS:{}, TS:{}};//for tracking and later disposing of loaded type libs
var watchTimer;
var createThemeMenuOption = function (theme, keybinding) {
return {
// An unique identifier of the contributed action.
id: 'set-theme-' + theme,
// A label of the action that will be presented to the user.
label: RED._('monaco.setTheme') + ' ' + theme,
precondition: null,// A precondition for this action.
keybindingContext: keybinding || null,// A rule to evaluate on top of the precondition in order to dispatch the keybindings.
// Method that will be executed when the action is triggered.
// @param editor The editor instance is passed in as a convinience
run: function (ed) {
//monaco.editor.setTheme(theme)
ed.setTheme(theme)
return null;
}
}
}
var convertAceModeToMonacoLang = function (mode) {
if (typeof mode == "object" && mode.path) {
mode = mode.path;
}
if (mode) {
mode = mode.replace("ace/mode/", "");
} else {
mode = "text";
}
switch (mode) {
case "nrjavascript":
case "mjs":
mode = "javascript";
break;
case "vue":
mode = "html";
break;
case "appcache":
case "sh":
case "bash":
mode = "shell";
break;
case "batchfile":
mode = "bat";
break;
case "protobuf":
mode = "proto";
break;
//TODO: add other compatability types.
}
return mode;
}
if(!options.stateId && options.stateId !== false) {
options.stateId = RED.editor.generateViewStateId("monaco", options, (options.mode || options.title || "").split("/").pop());
}
var el = options.element || $("#"+options.id)[0];
var toolbarRow = $("<div>").appendTo(el);
el = $("<div>").appendTo(el).addClass("red-ui-editor-text-container")[0];
var editorOptions = $.extend({}, editorSettings.options, options);
editorOptions.language = convertAceModeToMonacoLang(options.mode);
if(userSelectedTheme) {
editorOptions.theme = userSelectedTheme;//use user selected theme for this session
}
//by default, set javascript editors to text mode.
//when element becomes visible, it will be (re) set to javascript mode
//this is to ensure multiple editors sharing the model dont present its
//consts & lets to each other
if(editorOptions.language == "javascript") {
editorOptions._language = editorOptions.language;
editorOptions.language = "text"
}
//apply defaults
if (!editorOptions.minimap) {
editorOptions.minimap = {
enabled: true,
maxColumn: 50,
scale: 1,
showSlider: "mouseover",
renderCharacters: true
}
}
//common ACE flags - set equivelants in monaco
if(options.enableBasicAutocompletion === false) {
editorOptions.showSnippets = false;
editorOptions.quickSuggestions = false;
editorOptions.parameterHints = { enabled: false };
editorOptions.suggestOnTriggerCharacters = false;
editorOptions.acceptSuggestionOnEnter = "off";
editorOptions.tabCompletion = "off";
editorOptions.wordBasedSuggestions = false;
}
if (options.enableSnippets === false) { editorOptions.showSnippets = false; }
if (editorOptions.mouseWheelZoom == null) { editorOptions.mouseWheelZoom = true; }
if (editorOptions.suggestFontSize == null) { editorOptions.suggestFontSize = 12; }
if (editorOptions.formatOnPaste == null) { editorOptions.formatOnPaste = true; }
if (editorOptions.foldingHighlight == null) { editorOptions.foldingHighlight = true; }
if (editorOptions.foldStyle == null) { editorOptions.foldStyle = true; } //https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandaloneeditorconstructionoptions.html#folding
if (editorOptions.readOnly != null) { editorOptions.readOnly = editorOptions.readOnly; }
if (editorOptions.lineNumbers === false) { editorOptions.lineNumbers = false; }
if (editorOptions.theme == null) { editorOptions.theme = monacoThemes[0]; }
if (editorOptions.mode == null) { editorOptions.mode = convertAceModeToMonacoLang(options.mode); }
if (editorOptions.automaticLayout == null) { editorOptions.automaticLayout = true; }
if (options.foldStyle) {
switch (options.foldStyle) {
case "none":
editorOptions.foldStyle = false;
editorOptions.foldingHighlight = false
break;
default:
editorOptions.foldStyle = true;
editorOptions.foldingHighlight = true;
break;
}
} else {
editorOptions.foldStyle = true;
editorOptions.foldingHighlight = true;
}
//others
editorOptions.roundedSelection = editorOptions.roundedSelection === false ? false : true; //default to true
editorOptions.contextmenu = editorOptions.contextmenu === false ? false : true; //(context menu enable) default to true
editorOptions.snippetSuggestions = editorOptions.enableSnippets === false ? false : true; //default to true //https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandaloneeditorconstructionoptions.html#snippetsuggestions
editorOptions.value = options.value || "";
//if wordSeparators are not supplied, override default ones for the "j" langs
if(!editorOptions.wordSeparators) {
if (editorOptions.language == "jsonata" || editorOptions.language == "json" || editorOptions.language == "javascript") {
editorOptions.wordSeparators = "`~!@#%^&*()-=+[{]}\|;:'\",.<>/?"; //dont use $ as separator
}
}
//fixedOverflowWidgets should probably never be set to false
//fixedOverflowWidgets allows hover tips to be above other parts of UI
editorOptions.fixedOverflowWidgets = editorOptions.fixedOverflowWidgets === false ? false : true;
//#region Detect mobile / tablet and reduce functionality for small screen and lower power
var browser = RED.utils.getBrowserInfo();
if (browser.mobile || browser.tablet) {
editorOptions.minimap = { enabled: false };
editorOptions.formatOnType = false; //try to prevent cursor issues
editorOptions.formatOnPaste = false; //try to prevent cursor issues
editorOptions.disableMonospaceOptimizations = true; //speed up
editorOptions.columnSelection = false; //try to prevent cursor issues
editorOptions.matchBrackets = "never"; //speed up
editorOptions.maxTokenizationLineLength = 10000; //speed up //internal default is 20000
editorOptions.stopRenderingLineAfter = 2000; //speed up //internal default is 10000
editorOptions.roundedSelection = false; //speed up rendering
editorOptions.trimAutoWhitespace = false; //try to prevent cursor issues
editorOptions.parameterHints = { enabled: false };
editorOptions.suggestOnTriggerCharacters = false;//limit suggestions, user can still use ctrl+space
editorOptions.wordBasedSuggestions = false;
editorOptions.suggest = { maxVisibleSuggestions: 6 };
// editorOptions.codeLens = false;//If Necessary, disable this useful feature?
// editorOptions.quickSuggestions = false;//If Necessary, disable this useful feature?
// editorOptions.showSnippets = false; //If Necessary, disable this useful feature?
// editorOptions.acceptSuggestionOnEnter = "off"; //If Necessary, disable this useful feature?
// editorOptions.tabCompletion = "off"; //If Necessary, disable this useful feature?
if (!editorOptions.accessibilitySupport && browser.android) {
editorOptions.accessibilitySupport = "off"; //ref https://github.com/microsoft/pxt/pull/7099/commits/35fd3e969b0d5b68ca1e35809f96cea81ef243bc
}
}
//#endregion
//#region Load types for intellisense
//Determine if this instance is for client side or server side...
//if clientSideSuggestions option is not specified, check see if
//requested mode is "nrjavascript" or if options.globals are specifying RED or Buffer
var serverSideSuggestions = false;
if (options.clientSideSuggestions == null) {
if ( ((options.mode + "").indexOf("nrjavascript") >= 0) || (options.globals && (options.globals.RED || options.globals.Buffer )) ) {
serverSideSuggestions = true;
}
}
// compiler options - enable / disable server-side/client-side suggestions
var compilerOptions = monaco.languages.typescript.javascriptDefaults.getCompilerOptions();
if (serverSideSuggestions) {
compilerOptions.lib = ["esnext"]; //dont include DOM
defaultServerSideTypes.forEach(function(m) {
_loadModuleDTS(m, false, loadedLibs); //load common node+node-red types
})
} else {
compilerOptions.lib = ["esnext", "dom"];
}
monaco.languages.typescript.javascriptDefaults.setCompilerOptions(compilerOptions);
//check if extraLibs are to be loaded (e.g. fs or os)
refreshModuleLibs(editorOptions.extraLibs)
function refreshModuleLibs(extraModuleLibs) {
var defs = [];
var imports = [];
const id = "extraModuleLibs/index.d.ts";
const file = 'file://types/extraModuleLibs/index.d.ts';
if(!extraModuleLibs || extraModuleLibs.length == 0) {
loadedLibs.JS[id] = monaco.languages.typescript.javascriptDefaults.addExtraLib(" ", file);
} else {
var loadList = [];
Array.prototype.push.apply(loadList, extraModuleLibs);//Use this instead of spread operator to prevent IE syntax error
var loadExtraModules = {};
for (let index = 0; index < extraModuleLibs.length; index++) {
const lib = extraModuleLibs[index];
const varName = lib.var;
const moduleName = lib.module;
if(varName && moduleName) {
imports.push("import " + varName + "_import = require('" + moduleName + "');\n");
defs.push("var " + varName + ": typeof " + varName + "_import;\n");
}
var km = knownModules[moduleName];
if(km) {
loadExtraModules[moduleName] = km;
} else {
loadExtraModules[moduleName] = {package: "other", module: moduleName, path: "other/" + moduleName + ".d.ts" };
}
}
Object.values(loadExtraModules).forEach(function(m) {
_loadModuleDTS(m, false, loadedLibs, function(err, extraLib) {
loadList = loadList.filter(function(e) {return e.module != extraLib.module} );
if(loadList.length == 0) {
var _imports = imports.join("");
var _defs = "\ndeclare global {\n" + defs.join("") + "\n}";
var libSource = _imports + _defs;
setTimeout(function() {
loadedLibs.JS[id] = monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, file);
}, 500);
}
});
});
}
}
//#endregion
/*********** Create the monaco editor ***************/
var ed = monaco.editor.create(el, editorOptions);
//Unbind ctrl-Enter (default action is to insert a newline in editor) This permits the shortcut to close the tray.
try {
monaco.editor.addKeybindingRule({keybinding: 0, command: "-editor.action.insertLineAfter"});
} catch (error) {
console.warn(error)
}
ed.nodered = {
refreshModuleLibs: refreshModuleLibs //expose this for function node externalModules refresh
}
//add f1 menu items for changing theme
for (var themeIdx = 0; themeIdx < monacoThemes.length; themeIdx++) {
var themeName = monacoThemes[themeIdx];
ed.addAction(createThemeMenuOption(themeName));
}
//#region "ACE compatability"
ed.selection = {};
ed.session = ed;
ed.renderer = {};
ed.setMode = function(mode, cb, resize) {
if(resize==null) { resize = true; }
mode = convertAceModeToMonacoLang(mode);
var oldModel = ed.getModel();
var oldValue = ed.getValue();
var newModel
if (oldModel) {
var oldScrollTop = ed.getScrollTop();
var oldScrollLeft = ed.getScrollLeft();
var oldSelections = ed.getSelections();