-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
editor.js
2183 lines (1889 loc) · 92.1 KB
/
editor.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
// @ts-nocheck
/* eslint-disable sonarjs/no-duplicate-string, es/no-object-values, strict */
// Isolate this code
(function () { // eslint-disable-line sonarjs/cognitive-complexity
'use strict'
const uibDebug = location.hostname === '127.0.0.1'
const mylog = uibDebug ? console.log : function() {}
mylog('[uibuilder] DEBUG ON (because running on localhost)')
//#region ------------------- Pollyfills --------------------- //
if (!Object.entries) {
Object.entries = function( obj ) {
const ownProps = Object.keys( obj )
let i = ownProps.length
const resArray = new Array(i) // preallocate the Array
while (i--) {
resArray[i] = [ownProps[i], obj[ownProps[i]]]
}
return resArray
}
}
if (!Object.values) {
const reduce = Function.bind.call(Function.call, Array.prototype.reduce)
const keys = Reflect.ownKeys // eslint-disable-line no-undef
const concat = Function.bind.call(Function.call, Array.prototype.concat)
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable)
Object.values = function values(O) {
return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), [])
}
}
//#endregion ----------------- Pollyfills -------------------- //
//#region --------- "global" variables for the panel --------- //
/** Module name must match this nodes html file @constant {string} moduleName */
const moduleName = 'uibuilder'
/** Node's label @constant {string} paletteCategory */
const nodeLabel = 'uibuilder'
/** Node's palette category @constant {string} paletteCategory */
const paletteCategory = 'uibuilder'
/** Node's background color @constant {string} paletteColor */
const paletteColor = '#E6E0F8'
/** Default session length (in seconds) if security is active @type {Number} */
// const defaultSessionLength = 432000
/** Default JWT secret if security is active - to ensure it isn't blank @type {String} */
// const defaultJwtSecret = 'Replace This With A Real Secret'
/** Default template name */
const defaultTemplate = 'blank'
/** Track which urls have been used - required to handle copy/paste and import
* as these can contain duplicate urls before deployment.
*/
const editorInstances = {}
/** List of installed packages - rebuilt when editor is opened, updates by library mgr */
let packages = []
/** List of the instances in use by id [{node_id: url}], updated in validateUrl() */
let uibuilderInstances = RED.settings.uibuilderInstances
/** placeholder for ACE editor vars - so that they survive close/reopen admin config ui
* @typedef {object} uiace Options for the ACE/Monaco code editor
* @property {string} format What format to use for the code editor (html)
* @property {string} folder What folder was last used
* @property {string} fname What filename was last edited
* @property {boolean} fullscreen Is the editor in fullscreen mode?
*/
const uiace = {
'format': 'html',
'folder': 'src',
'fname': 'index.html',
'fullscreen': false
}
/** placeholder for instance folder list
* @type {Array<string>} */
let folders = []
//#endregion ------------------------------------------------- //
//#region --------- Node-RED Event Handlers --------- //
// These are registered once for the node type
/** Track which urls have been used - required to handle copy/paste and import
* as these can contain duplicate urls before deployment.
*/
RED.events.on('nodes:add', function(node) {
if ( node.type === 'uibuilder') {
// Keep a list of uib nodes in the editor
// may be different to the deployed list
editorInstances[node.id] = node.url
// -- IF uibuilderInstances <> editorInstances THEN there are undeployed instances. --
}
})
RED.events.on('nodes:change', function(node) {
if ( node.type === 'uibuilder') {
mylog('nodes:change:', node)
editorInstances[node.id] = node.url
}
})
RED.events.on('nodes:remove', function(node) {
if ( node.type === 'uibuilder') {
mylog('>> nodes:remove >>', node)
delete editorInstances[node.id]
}
})
// RED.events.on('deploy', function() {
// console.log('Deployed')
// })
// RED.events.on('workspace:dirty', function(data) {
// console.log('Workspace dirty:', data)
// })
// RED.events.on('runtime-state', function(event) {
// console.log('>> Runtime State >>', event)
// })
//#endregion --------- Node-RED Event Handlers --------- //
//#region --------- "global" functions for the panel --------- //
//#region ==== Package Management Functions ==== //
/** Perform a call to the package update v3 API
* @param {JQuery.ClickEvent<HTMLElement, undefined, HTMLElement, HTMLElement>} evt jQuery Click Event
*/
function doPkgUpd(evt) {
// ! TODO
console.log('>>>> do update', evt.data.pkgName)
const packageName = evt.data.pkgName
const node = evt.data.node
RED.notify('Installing npm package ' + packageName)
// Call the npm installPackage v2 API (it updates the package list)
// $.get( `uibuilder/uibnpmmanage?cmd=update&package=${packageName}&url=${node.url}&tag=${packageTag}`, function(data) {
$.get( `uibuilder/uibnpmmanage?cmd=update&package=${packageName}&url=${node.url}`, function(data) {
const npmOutput = data.result[0]
if ( data.success === true) {
packages = data.result[1]
console.log('[uibuilder:doPkgUpd:get] PACKAGE INSTALLED. ', packageName, node.url, '\n\n', npmOutput, '\n ')
RED.notify(`Successful update of npm package ${packageName}`, 'success')
// reset and populate the list
$('#node-input-packageList').editableList('empty')
$('#node-input-packageList').editableList('addItems', Object.keys(packages))
} else {
console.log('[uibuilder:doPkgUpd:get] ERROR ON INSTALLATION OF PACKAGE ', packageName, node.url, '\n\n', npmOutput, '\n ' )
RED.notify(`FAILED update of npm package ${packageName}`, 'error')
}
// Hide the progress spinner
$('i.spinner').hide()
})
.fail(function(_jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:doPkgUpd:get] Error ' + textStatus, errorThrown )
RED.notify(`FAILED update of npm package ${packageName}`, 'error')
$('i.spinner').hide()
return 'addPackageRow failed'
// TODO otherwise highlight input
})
$.ajax({
type: 'PUT',
dataType: 'json',
url: './uibuilder/admin/' + evt.data.node.url, // v3 api
data: {
'cmd': 'updatepackage',
'pkgName': evt.data.pkgName,
},
})
.done(function(data, _textStatus, jqXHR) {
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:doPkgUpd:PUT] Error ' + textStatus, errorThrown )
RED.notify(`uibuilder: Package update for '${evt.data.pkgName}' failed.<br>${errorThrown}`, { type: 'error' })
})
// Assuming update worked, hide the button - And update version string
$(`#upd_${evt.data.pkgName}`).hide()
.next().text('XXX')
}
/** AddItem function for package list
* @param {object} node A reference to the panel's `this` object
* @param {JQuery<HTMLElement>} element the jQuery DOM element to which any row content should be added
* @param {number} index the index of the row
* @param {string|*} data data object for the row. {} if add button pressed, else data passed to addItem method
*/
function addPackageRow(node, element, index, data) {
let hRow = ''; let pkgSpec = null
if (Object.entries(data).length === 0) { // Add button was pressed so we have no packageName, create an input form instead
hRow = `
<div>
<label for="packageList-input-${index}" style="width:3em;">Name:</label>
<input type="text" id="packageList-input-${index}" title="" style="width:80%" placeholder="Valid npm package name">
</div>
<div>
<label for="packageList-tag-${index}" style="width:3em;">Tag:</label>
<input type="text" id="packageList-tag-${index}" title="" style="width:80%" placeholder="npm: @tag/version, GH: #branch/tag">
</div>
<div>
<label for="packageList-button-${index}" style="width:3em;"></label>
<button id="packageList-button-${index}" style="width:5em;">Install</button>
</div>
`
} else { // existing line
/*
npm install [<@scope>/]<name>
npm install [<@scope>/]<name>@<tag>
npm install [<@scope>/]<name>@<version>
npm install [<@scope>/]<name>@<version range>
npm install <alias>@npm:<name>
npm install <git-host>:<git-user>/<repo-name>[#branch-tag-name]
npm install <git repo url>
npm install <tarball file>
npm install <tarball url>
npm install <folder>
*/
pkgSpec = packages[data]
// if wanted !== installed, show update
let upd = ''
if ( pkgSpec.outdated && pkgSpec.outdated.wanted && pkgSpec.installedVersion !== pkgSpec.outdated.wanted ) {
upd = `<button id="upd_${data}" style="color:orange;background-color:black;" title="Click to update (or install again to get a non-standard version)">UPDATE: ${pkgSpec.outdated.wanted}</button>`
$('#node-input-packageList').on('click', `#upd_${data}`, { pkgName: data, node: node }, doPkgUpd)
}
// addItem method was called with a packageName passed
hRow = `
<div id="packageList-row-${index}" class="packageList-row-data">
<div style="display:flex;justify-content:space-between;">
<div>
<a href="${pkgSpec.homepage}" target="_blank" title="Click to open package homepage in a new tab">
<b>${data}</b> <span class="emoji">ℹ️</span>
</a>
</div>
<div style="margin-left:auto;text-align:right;">
${upd}
<span title="npm version specification: ${pkgSpec.spec}">${pkgSpec.installedVersion}</span>
</div>
</div>
<div title="NB: This link is an estimate, check the package docs for the actual entry point" style="display:flex;justify-content:space-between;">
<div>Est. link:</div>
<div style="margin-left:auto;text-align:right;"><code style="white-space:inherit;text-decoration: underline;"><a href="${node.urlPrefix}${pkgSpec.url}" target="_blank">
${pkgSpec.url}
</code></div>
</div>
</div>
`
}
// Build the output row
$(hRow).appendTo(element)
// Add tooltips for the input fields
if (Object.entries(data).length === 0) {
// @ts-expect-error ts(2339)
$(`#packageList-input-${index}`).tooltip({
content: 'Enter one of:<ul><li>An npm package name (optionally with leading)</li><li>A GitHub user/repo</li><li>A filing system path to a local package</li></ul>Ensure that you select the correct "From" dropdown.'
})
// @ts-expect-error ts(2339)
$(`#packageList-ver-${index}`).tooltip({
content: 'Optional. Branch, Tag or Version to install (defaults to @latest)'
})
}
// Create a button click listener for the install button for this row
$('#packageList-button-' + index).on('click', function() {
// show activity spinner
$('i.spinner').show()
// Get the data from the input fields
const packageName = String($(`#packageList-input-${index}`).val())
const packageTag = String($(`#packageList-tag-${index}`).val())
if ( packageName.length !== 0 ) {
RED.notify('Installing npm package ' + packageName)
// Call the npm installPackage v2 API (it updates the package list)
$.get( `uibuilder/uibnpmmanage?cmd=install&package=${packageName}&url=${node.url}&tag=${packageTag}`, function(data) {
const npmOutput = data.result[0]
if ( data.success === true) {
packages = data.result[1]
console.log('[uibuilder:addPackageRow:get] PACKAGE INSTALLED. ', packageName, node.url, '\n\n', npmOutput, '\n ')
RED.notify(`Successful installation of npm package ${packageName} for ${node.url}`, 'success')
// reset and populate the list
$('#node-input-packageList').editableList('empty')
// @ts-ignore
$('#node-input-packageList').editableList('addItems', Object.keys(packages))
} else {
console.log('[uibuilder:addPackageRow:get] ERROR ON INSTALLATION OF PACKAGE ', packageName, node.url, '\n\n', npmOutput, '\n ' )
RED.notify(`FAILED installation of npm package ${packageName} for ${node.url}`, 'error')
}
// Hide the progress spinner
$('i.spinner').hide()
})
.fail(function(_jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:addPackageRow:get] Error ' + textStatus, errorThrown )
RED.notify(`FAILED installation of npm package ${packageName} for ${node.url}`, 'error')
$('i.spinner').hide()
return 'addPackageRow failed'
// TODO otherwise highlight input
})
} // else Do nothing
}) // -- end of button click -- //
} // --- End of addPackageRow() ---- //
/** RemoveItem function for package list
* @param {string} packageName Name of the npm package to remove
* @returns {string} Result text
*/
function removePackageRow(packageName) {
// If package name is an empty object - user removed an add row so ignore
if ( (packageName === '') || (typeof packageName !== 'string') ) {
return 'No package'
}
RED.notify('Starting removal of npm package ' + packageName)
// show activity spinner
$('i.spinner').show()
// Call the npm installPackage API (it updates the package list)
$.get( 'uibuilder/uibnpmmanage?cmd=remove&package=' + packageName, function(data) {
if ( data.success === true) {
console.log('[uibuilder:removePackageRow:get] PACKAGE REMOVED. ', packageName)
RED.notify('Successfully uninstalled npm package ' + packageName, 'success')
if ( packages[packageName] ) delete packages[packageName]
} else {
console.log('[uibuilder:removePackageRow:get] ERROR ON PACKAGE REMOVAL ', data.result )
RED.notify('FAILED to uninstall npm package ' + packageName, 'error')
// Put the entry back again
$('#node-input-packageList').editableList('addItem', packageName)
}
$('i.spinner').hide()
})
.fail(function(_jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:removePackageRow:get] Error ' + textStatus, errorThrown )
RED.notify('FAILED to uninstall npm package ' + packageName, 'error')
// Put the entry back again
// @ts-ignore
$('#node-input-packageList').editableList('addItem', packageName)
$('i.spinner').hide()
return 'removePackageRow failed'
// TODO otherwise highlight input
})
} // ---- End of removePackageRow ---- //
/** Get list of installed packages via v2 API - save to master list */
function packageList() {
$.ajax({
dataType: 'json',
method: 'get',
url: 'uibuilder/uibvendorpackages',
async: false,
// data: { url: node.url},
success: function(vendorPaths) {
packages = vendorPaths
},
error: function(err) {
console.log('ERROR', err)
},
})
} // --- End of packageList --- //
//#endregion ==== Package Management Functions ==== //
//#region ==== File Management Functions ==== //
/** Return a file type from a file name (or default to txt)
* ftype can be used in ACE editor modes
* @param {string} fname File name for which to return the type
* @returns {string} File type
*/
function fileType(fname) {
let ftype = 'text'
const fparts = fname.split('.')
// Take off the first entry if the file name started with a dot
if ( fparts[0] === '' ) fparts.shift()
if (fparts.length > 1) {
// Get the last element of the array
// eslint-disable-next-line newline-per-chained-call
const fext = fparts.pop().toLowerCase().trim()
switch (fext) {
case 'js':
ftype = 'javascript'
break
case 'html':
case 'css':
case 'json':
ftype = fext
break
case 'vue':
ftype = 'html'
break
case 'md':
ftype = 'markdown'
break
case 'yaml':
case 'yml':
ftype = 'yaml'
break
default:
ftype = fext
}
}
return ftype
} // --- End of fileType --- //
/** Enable/disable buttons if file has edits or not
* @param {boolean} isClean true = the file is clean, else there are pending edits that need saving
*/
function fileIsClean(isClean) {
// If clean, disable the save & reset buttons
$('#edit-save').prop('disabled', isClean)
$('#edit-reset').prop('disabled', isClean)
// If clean, enable the delete and edit buttons
// $('#edit-delete').prop('disabled', !isClean)
$('#edit-close').prop('disabled', !isClean)
$('#node-edit-file').prop('disabled', !isClean)
$('#node-input-filename').prop('disabled', !isClean)
// If not clean, disable main Done and Cancel buttons to prevent loss
$('#node-dialog-ok').prop('disabled', !isClean)
$('#node-dialog-cancel').prop('disabled', !isClean)
// If not clean, Add a user hint
if ( !isClean ) {
$('#file-action-message').text('Save Required')
$('#node-dialog-ok').css( 'cursor', 'not-allowed' )
$('#node-dialog-cancel').css( 'cursor', 'not-allowed' )
} else {
$('#node-dialog-ok').css( 'cursor', 'pointer' )
$('#node-dialog-cancel').css( 'cursor', 'pointer' )
}
} // --- End of fileIsClean --- //
/** Get the chosen file contents & set up the ACE editor */
function getFileContents() {
// Get the current url
const url = $('#node-input-url').val()
/** Get the chosen folder name - use the default/last saved on first load
* @type {string} */
// @ts-ignore
let folder = $('#node-input-folder').val()
if ( folder === null ) {
folder = localStorage.getItem('uibuilder.' + url + '.folder') || uiace.folder
}
/** Get the chosen filename - use the default/last saved on first load
* @type {string} */
// @ts-ignore
let fname = $('#node-input-filename').val()
if ( fname === null ) {
fname = localStorage.getItem('uibuilder.' + url + '.selectedFile') || uiace.fname
}
// Save the file & folder names
uiace.folder = folder
uiace.fname = fname
// Persist the folder & file name selection
localStorage.setItem('uibuilder.' + url + '.folder', uiace.folder)
localStorage.setItem('uibuilder.' + url + '.selectedFile', uiace.fname)
// Change mode to match file type
const filetype = uiace.format = fileType(fname)
$('#node-input-format').val(filetype)
// Get the file contents via API defined in uibuilder.js
$.get( 'uibuilder/uibgetfile?url=' + url + '&fname=' + fname + '&folder=' + folder, function(data) {
$('#node-input-template-editor').show()
$('#node-input-template-editor-no-file').hide()
// Add the fetched data to the editor
uiace.editorSession.setValue(data)
// Set the editor file mode
uiace.editorSession.setMode({
path: 'ace/mode/' + filetype, v: Date.now()
})
// Mark the current session as clean
uiace.editorSession.getUndoManager().isClean()
// Position the cursor in the edit area
uiace.editor.focus()
})
.fail(function(_jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:getFileContents:get] Error ' + textStatus, errorThrown )
uiace.editorSession.setValue('')
$('#node-input-template-editor').hide()
$('#node-input-template-editor-no-file').show()
})
.always(function() {
fileIsClean(true)
// Default the language selector in case it wasn't recognised
if (!$('#node-input-format option:selected').length) $('#node-input-format').val('text')
})
} // --- End of getFileContents --- //
/** Get the list of files for the chosen url & folder
* @param {string} [selectedFile] Optional. If present will select this filename after refresh, otherwise 1st file is selected.
*/
function getFileList(selectedFile) {
//#region --- Collect variables from Config UI ---
const url = /** @type {string} */ ($('#node-input-url').val())
let folder = /** @type {string} */ ($('#node-input-folder').val())
const f = /** @type {string} */ ($('#node-input-filename').val())
// Whether or not to force the index.(html|js|css) files to be copied over if missing
// var nodeInputCopyIndex = $('#node-input-copyIndex').is(':checked')
//#endregion -------------------------------------
// Collect the current filename from various places
if ( selectedFile === undefined ) selectedFile = /** @type {string} */ (f)
if ( selectedFile === null ) {
selectedFile = localStorage.getItem('uibuilder.' + url + '.selectedFile') || undefined
}
if ( folder === null ) {
folder = localStorage.getItem('uibuilder.' + url + '.folder') || undefined
}
// Clear out drop-downs ready for rebuilding
$('#node-input-filename option').remove()
$('#node-input-folder option').remove()
// Get all files/folders for this uibuilder instance from API call
$.ajax({
type: 'GET',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'cmd': 'listall',
},
})
// eslint-disable-next-line no-unused-vars
.done(function(data, _textStatus, jqXHR) {
let firstFile = ''; let indexHtml = false; let selected = false
// build folder list, pre-select src if no current folder selected #node-input-folder - Object.keys(res)
const folders = Object.keys(data).sort()
// Rebuild folder drop-down
$.each(folders, function (i, fldrname) {
// For the root folder, use empty string for folders lookup but "root" for display
if ( fldrname === '' ) fldrname = 'root'
// Build the drop-down
$('#node-input-folder').append($('<option>', {
value: fldrname,
text: fldrname,
}))
})
// if currently selected folder doesn't exist
if ( !data[folder] ) {
// Use 'src' if it exists otherwise use 'root'
if ( data.src ) folder = 'src'
else folder = 'root'
}
// Selected folder
$('#node-input-folder').val(folder)
uiace.folder = folder
// Persist the folder selection
localStorage.setItem('uibuilder.' + url + '.folder', folder)
let files = []
files = data[folder]
$.each(files, function (i, filename) {
// Build the drop-down
$('#node-input-filename').append($('<option>', {
value: filename,
text: filename,
}))
// Choose the default file. In order: selectedFile param, index.html, 1st returned
if ( i === 0 ) firstFile = filename
if ( filename === uiace.fname ) indexHtml = true
if ( filename === selectedFile ) selected = true
})
// Set default file name/type. In order: selectedFile param, index.html, 1st returned
// @ts-ignore
if ( selected === true ) uiace.fname = selectedFile
// @ts-ignore
else if ( indexHtml === true ) uiace.fname = 'index.html'
else uiace.fname = firstFile
$('#node-input-filename').val(uiace.fname)
uiace.format = fileType(uiace.fname)
// Persist the file name selection
localStorage.setItem('uibuilder.' + url + '.selectedFile', uiace.fname)
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:getFileList:getJSON] Error ' + textStatus, errorThrown )
uiace.fname = ''
uiace.format = 'text'
RED.notify(`uibuilder: Folder and file listing error.<br>${errorThrown}`, { type: 'error' })
})
.always(function() {
getFileContents()
})
} // --- End of getFileList --- //
/** Get a full list of instance folders (minus protected ones). Updates folders global var. */
function getFolders() {
const url = /** @type {string} */ ($('#node-input-url').val())
const data = $.ajax({
async: false,
type: 'GET',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'cmd': 'listfolders',
},
})
folders = data.responseJSON
$('#node-input-sourceFolder').typedInput({
types: [
{
value: 'sourceFolders',
options: folders,
}
]
})
} // --- End of getFolders --- //
/** Call v3 admin API to create a new folder
* @param {string} folder Name of new folder to create (combines with current uibuilder url)
* returns {string} Status message
*/
function createNewFolder(folder) {
// Also get the current url
const url = $('#node-input-url').val()
$.ajax({
type: 'POST',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'folder': folder,
'cmd': 'newfolder',
},
})
.done(function() { // data, textStatus, jqXHR) {
RED.notify(`uibuilder: Folder <code>${folder}</code> Created.`, { type: 'success' })
// Rebuild the file list
getFileList()
// Rebuild the folder list
getFolders()
return 'Create folder succeeded'
})
.fail(function(jqXHR, textStatus, errorThrown) {
RED.notify(`uibuilder: Create Folder Error.<br>${errorThrown}`, { type: 'error' })
return 'Create folder failed'
})
} // --- End of createNewFile --- //
/** Call v3 admin API to create a new file
* @param {string} fname Name of new file to create (combines with current selected folder and the current uibuilder url)
* returns {string} Status message
*/
function createNewFile(fname) {
// Also get the current folder & url
const folder = $('#node-input-folder').val() || uiace.folder
const url = $('#node-input-url').val()
$.ajax({
type: 'POST',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'folder': folder,
'fname': fname,
'cmd': 'newfile',
},
})
.done(function() { // data, textStatus, jqXHR) {
RED.notify(`uibuilder: File <code>${folder}/${fname}</code> Created.`, { type: 'success' })
// Rebuild the file list
getFileList(fname)
return 'Create file succeeded'
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:createNewFile:post] Error ' + textStatus, errorThrown )
RED.notify(`uibuilder: Create File Error.<br>${errorThrown}`, { type: 'error' })
return 'Create file failed'
})
} // --- End of createNewFile --- //
/** Call v3 admin API to delete the currently selected folder
* returns {string} Status message
*/
function deleteFolder() {
// Also get the current url & folder
const url = $('#node-input-url').val()
const folder = $('#node-input-folder').val()
$.ajax({
type: 'DELETE',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'folder': folder,
'cmd': 'deletefolder',
},
})
.done(function() { // data, textStatus, jqXHR) {
RED.notify(`uibuilder: Folder <code>${folder}</code> deleted.`, { type: 'success' })
// Rebuild the file list
getFileList()
return 'Delete folder succeeded'
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:deleteFolder:delete] Error ' + textStatus, errorThrown )
RED.notify(`uibuilder: Delete Folder Error.<br>${errorThrown}`, { type: 'error' })
return 'Delete folder failed'
})
} // --- End of deleteFolder --- //
/** Call v3 admin API to delete the currently selected file
* returns {string} Status message
*/
function deleteFile() {
// Get the current file, folder & url
const folder = /** @type {string} */ ($('#node-input-folder').val()) || uiace.folder
const url = /** @type {string} */ ($('#node-input-url').val())
const fname = /** @type {string} */ ($('#node-input-filename').val())
$.ajax({
type: 'DELETE',
dataType: 'json',
url: './uibuilder/admin/' + url,
data: {
'folder': folder,
'fname': fname,
'cmd': 'deletefile',
},
})
.done(function() { // data, textStatus, jqXHR) {
RED.notify(`uibuilder: File <code>${folder}/${fname}</code> Deleted.`, { type: 'success' })
// Rebuild the file list
getFileList(fname)
return 'Delete file succeeded'
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error( '[uibuilder:deleteFile:delete] Error ' + textStatus, errorThrown )
RED.notify(`uibuilder: Delete File Error.<br>${errorThrown}`, { type: 'error' })
return 'Delete file failed'
})
} // --- End of deleteFile --- //
/** Set the height of the ACE text editor box */
function setACEheight() {
let height
if ( uiace.editorLoaded === true ) {
// If the editor is in full-screen ...
if (document.fullscreenElement) {
// Force background color and add some padding to keep away from edge
$('#edit-props').css('background-color', '#f6f6f6')
.css('padding', '1em')
// Start to calculate the available height and adjust the editor to fill the ht
height = parseInt($('#edit-props').css('height'), 10) // full available height
height -= 25
// Replace the expand icon with a compress icon
$('#node-function-expand-js').css('background-color', 'black')
.html('<i class="fa fa-compress"></i>')
uiace.fullscreen = true
} else {
// Don't bother if the top of the editor is still auto
if ( $('#edit-outer').css('top') === 'auto' ) return
$('#edit-props').css('background-color', '')
.css('padding', '')
height = ($('.red-ui-tray-footer').position()).top - ($('#edit-outer').offset()).top - 35
// Replace the compress icon with a expand icon
$('#node-function-expand-js').css('background-color', '')
.html('<i class="fa fa-expand"></i>')
uiace.fullscreen = false
}
// everything but the edit box
const rows = $('#edit-props > div:not(.node-text-editor-row)')
// subtract height of each row from the total
for (let i = 0; i < rows.length; i++) {
height -= $(rows[i]).outerHeight(true)
}
// Set the height of the edit box
$('#node-input-template-editor').css('height', height + 'px')
// Get the content to match the edit box size
uiace.editor.resize()
}
} // --- End of setACEheight --- //
/** Save Edited File */
function saveFile() {
const authTokens = RED.settings.get('auth-tokens')
// Post the updated content of the file via the admin API
// NOTE: Cannot use jQuery POST function as it sets headers node trigger a CORS error. Do it using native requests only.
// Clients will be reloaded if the reload checkbox is set.
const request = new XMLHttpRequest()
const params = 'fname=' + $('#node-input-filename').val() + '&folder=' + $('#node-input-folder').val() +
'&url=' + $('#node-input-url').val() +
'&reload=' + $('#node-input-reload').prop('checked') +
'&data=' + encodeURIComponent(uiace.editorSession.getValue())
request.open('POST', 'uibuilder/uibputfile', true)
request.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
// Request successful
// display msg - blank msg when new edits present
$('#file-action-message').text('File Saved')
fileIsClean(true)
} else {
// Request failed
// display msg - blank msg when new edits present
$('#file-action-message').text('File Save FAILED')
}
}
}
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// If admin ui is protected with a login, we need to send the access token
if (authTokens) request.setRequestHeader('Authorization', 'Bearer ' + authTokens.access_token)
request.send(params)
} // ---- End of saveFile ---- //
//#endregion ==== File Management Functions ==== //
//#region ==== Validation Functions ==== //
// These are called on editor load & node added to flow as well as on form change
// Use `$('#node-input-url').length > 0` to check if form exists
/** Update the deployed instances list
* @param {object} node Pass in this
*/
function updateDeployedInstances(node) {
// Update the deployed instances list
$.ajax({
type: 'GET',
async: false,
dataType: 'json',
url: './uibuilder/admin/_', // pass dummy url _ as not needed for this query
data: {
'cmd': 'listinstances', // 'checkurls',
},
success: function(data) {
// console.log('>> update instances >>', value, data)
uibuilderInstances = data
}
})
if ( node ) node.isDeployed = uibuilderInstances[node.id] !== undefined
}
/** Find out if a server folder exists for this url
* @param {string} url URL to check
* @returns {boolean} Whether the folder exists
*/
function queryFolderExists(url) {
if (url === undefined) return false
let check = false
$.ajax({
type: 'GET',
async: false,
dataType: 'json',
url: `./uibuilder/admin/${url}`,
data: {
'cmd': 'checkfolder',
},
success: function(data) {
check = data
},
error: function(jqXHR, textStatus, errorThrown) {
if (errorThrown !== 'Not Found') {
console.error( '[uibuilder:queryFolderExists] Error ' + textStatus, errorThrown )
}
check = false
},
})
return check
} // ---- end of queryFolderExists ---- //
/** (Dis)Allow uibuilder configuration other than URL changes
* @param {object} urlErrors List of errors
* @param {boolean} enable True=Enable config editing, false=disable
*/
function enableEdit(urlErrors, enable = true) {
if (enable === true) {
// $('#node-dialog-ok')
// .prop('disabled', false)
// .css( 'cursor', 'pointer' )
// .addClass('primary')
$('#node-input-templateFolder, #btn-load-template')
.prop('disabled', false)
.css({
'cursor': 'pointer',
})
$('#red-ui-tab-tab-files, #red-ui-tab-tab-libraries, #red-ui-tab-tab-security, #red-ui-tab-tab-advanced, info')
.css({
'cursor': 'pointer',
})
$('#red-ui-tab-tab-files>a, #red-ui-tab-tab-libraries>a, #red-ui-tab-tab-security>a, #red-ui-tab-tab-advanced>a, info>a')
.prop('disabled', false)
.css({
'pointer-events': 'auto',
'cursor': 'pointer',
'opacity': 1,
})
$('#uibuilderurl, #uibinstanceconf')
.prop('disabled', false)
.css({
// 'pointer-events': 'auto',
'cursor': 'pointer',
'opacity': 1,
})
$('#url-errors').remove()
} else {
// Don't disable the Done button if the folder doesn't exist
// if (!folderExists)
// $('#node-dialog-ok')
// .prop('disabled', true)
// .css( 'cursor', 'not-allowed' )
// .removeClass('primary')
$('#node-input-templateFolder, #btn-load-template')
.prop('disabled', true)
.css({
'cursor': 'not-allowed',
})
$('#red-ui-tab-tab-files, #red-ui-tab-tab-libraries, #red-ui-tab-tab-security, #red-ui-tab-tab-advanced, info')
.css({
'cursor': 'not-allowed',
})
$('#red-ui-tab-tab-files>a, #red-ui-tab-tab-libraries>a, #red-ui-tab-tab-security>a, #red-ui-tab-tab-advanced>a, info>a')
.prop('disabled', true)
.css({
'pointer-events': 'none',
'cursor': 'not-allowed',
'opacity': 0.3,
})