[CCSDK-683] fixed dg import from local git repo
[ccsdk/distribution.git] / dgbuilder / public / red / ui / editor.js
1 /**
2  * Copyright 2013, 2014 IBM Corp.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  **/
16 RED.editor = (function() {
17     var editing_node = null;
18     // TODO: should IMPORT/EXPORT get their own dialogs?
19
20     function getCredentialsURL(nodeType, nodeID) {
21         var dashedType = nodeType.replace(/\s+/g, '-');
22         return  'credentials/' + dashedType + "/" + nodeID;
23     }
24
25     /**
26      * Validate a node 
27      * @param node - the node being validated
28      * @returns {boolean} whether the node is valid. Sets node.dirty if needed
29      */
30     function validateNode(node) {
31         var oldValue = node.valid;
32         node.valid = validateNodeProperties(node, node._def.defaults, node);
33         if (node._def._creds) {
34             node.valid = node.valid && validateNodeProperties(node, node._def.credentials, node._def._creds);
35         }
36         if (oldValue != node.valid) {
37             node.dirty = true;
38         }
39     }
40     
41     /**
42      * Validate a node's properties for the given set of property definitions
43      * @param node - the node being validated
44      * @param definition - the node property definitions (either def.defaults or def.creds)
45      * @param properties - the node property values to validate
46      * @returns {boolean} whether the node's properties are valid
47      */
48     function validateNodeProperties(node, definition, properties) {
49         var isValid = true;
50         for (var prop in definition) {
51             if (definition.hasOwnProperty(prop)) {
52                 if (!validateNodeProperty(node, definition, prop, properties[prop])) {
53                     isValid = false;
54                 }
55             }
56         }
57         return isValid;
58     }
59
60     /**
61      * Validate a individual node property
62      * @param node - the node being validated
63      * @param definition - the node property definitions (either def.defaults or def.creds)
64      * @param property - the property name being validated
65      * @param value - the property value being validated
66      * @returns {boolean} whether the node proprty is valid
67      */
68     function validateNodeProperty(node,definition,property,value) {
69         var valid = true;
70         if ("required" in definition[property] && definition[property].required) {
71             valid = value !== "";
72         }
73         if (valid && "validate" in definition[property]) {
74             valid = definition[property].validate.call(node,value);
75         }
76         if (valid && definition[property].type && RED.nodes.getType(definition[property].type) && !("validate" in definition[property])) {
77             if (!value || value == "_ADD_") {
78                 valid = false;
79             } else {
80                 var v = RED.nodes.node(value).valid;
81                 valid = (v==null || v);
82             }
83         }
84         return valid;
85     }
86
87     /**
88      * Called when the node's properties have changed.
89      * Marks the node as dirty and needing a size check.
90      * Removes any links to non-existant outputs.
91      * @param node - the node that has been updated
92      * @returns {array} the links that were removed due to this update
93      */
94     function updateNodeProperties(node) {
95         node.resize = true;
96         node.dirty = true;
97         var removedLinks = [];
98         if (node.outputs < node.ports.length) {
99             while (node.outputs < node.ports.length) {
100                 node.ports.pop();
101             }
102             RED.nodes.eachLink(function(l) {
103                     if (l.source === node && l.sourcePort >= node.outputs) {
104                         removedLinks.push(l);
105                     }
106             });
107             for (var l=0;l<removedLinks.length;l++) {
108                 RED.nodes.removeLink(removedLinks[l]);
109             }
110         } else if (node.outputs > node.ports.length) {
111             while (node.outputs > node.ports.length) {
112                 node.ports.push(node.ports.length);
113             }
114         }
115         return removedLinks;
116     }
117
118
119
120     $( "#dialog" ).dialog({
121             modal: true,
122             autoOpen: false,
123             closeOnEscape: false,
124             width: 500,
125             buttons: [
126                 {
127                     id: "node-dialog-ok",
128                     text: "Ok",
129                     click: function() {
130                         if (editing_node) {
131                             var changes = {};
132                             var changed = false;
133                             var wasDirty = RED.view.dirty();
134                             var d;
135
136                             if (editing_node._def.oneditsave) {
137                                 var oldValues = {};
138                                 for (d in editing_node._def.defaults) {
139                                     if (editing_node._def.defaults.hasOwnProperty(d)) {
140                                         if (typeof editing_node[d] === "string" || typeof editing_node[d] === "number") {
141                                             oldValues[d] = editing_node[d];
142                                         } else {
143                                             oldValues[d] = $.extend(true,{},{v:editing_node[d]}).v;
144                                         }
145                                     }
146                                 }
147                                 var rc = editing_node._def.oneditsave.call(editing_node);
148                                 if (rc === true) {
149                                     changed = true;
150                                 }
151
152                                 for (d in editing_node._def.defaults) {
153                                     if (editing_node._def.defaults.hasOwnProperty(d)) {
154                                         if (oldValues[d] === null || typeof oldValues[d] === "string" || typeof oldValues[d] === "number") {
155                                             if (oldValues[d] !== editing_node[d]) {
156                                                 changes[d] = oldValues[d];
157                                                 changed = true;
158                                             }
159                                         } else {
160                                             if (JSON.stringify(oldValues[d]) !== JSON.stringify(editing_node[d])) {
161                                                 changes[d] = oldValues[d];
162                                                 changed = true;
163                                             }
164                                         }
165                                     }
166                                 }
167
168
169                             }
170
171                             if (editing_node._def.defaults) {
172                                 for (d in editing_node._def.defaults) {
173                                     if (editing_node._def.defaults.hasOwnProperty(d)) {
174                                         var input = $("#node-input-"+d);
175                                         var newValue;
176                                         if (input.attr('type') === "checkbox") {
177                                             newValue = input.prop('checked');
178                                         } else {
179                                             newValue = input.val();
180                                         }
181                                         if (newValue != null) {
182                                             if (editing_node[d] != newValue) {
183                                                 if (editing_node._def.defaults[d].type) {
184                                                     if (newValue == "_ADD_") {
185                                                         newValue = "";
186                                                     }
187                                                     // Change to a related config node
188                                                     var configNode = RED.nodes.node(editing_node[d]);
189                                                     if (configNode) {
190                                                         var users = configNode.users;
191                                                         users.splice(users.indexOf(editing_node),1);
192                                                     }
193                                                     configNode = RED.nodes.node(newValue);
194                                                     if (configNode) {
195                                                         configNode.users.push(editing_node);
196                                                     }
197                                                 }
198     
199                                                 changes[d] = editing_node[d];
200                                                 editing_node[d] = newValue;
201                                                 changed = true;
202                                             }
203                                         }
204                                     }
205                                 }
206                             }
207                             if (editing_node._def.credentials) {
208                                 var prefix = 'node-input';
209                                 var credDefinition = editing_node._def.credentials;
210                                 var credsChanged = updateNodeCredentials(editing_node,credDefinition,prefix);
211                                 changed = changed || credsChanged;
212                             }
213
214
215                             var removedLinks = updateNodeProperties(editing_node);
216                             if (changed) {
217                                 var wasChanged = editing_node.changed;
218                                 editing_node.changed = true;
219                                 RED.view.dirty(true);
220                                 RED.history.push({t:'edit',node:editing_node,changes:changes,links:removedLinks,dirty:wasDirty,changed:wasChanged});
221                             }
222                             editing_node.dirty = true;
223                             validateNode(editing_node);
224                             RED.view.redraw();
225                         } else if (RED.view.state() == RED.state.EXPORT) {
226                             if (/library/.test($( "#dialog" ).dialog("option","title"))) {
227                                 //TODO: move this to RED.library
228                                 var flowName = $("#node-input-filename").val();
229                                 if (!/^\s*$/.test(flowName)) {
230                                     $.post('library/flows/'+flowName,$("#node-input-filename").attr('nodes'),function() {
231                                             RED.library.loadFlowLibrary();
232                                             RED.notify("Saved nodes","success");
233                                     });
234                                 }
235                             }
236                         } else if (RED.view.state() == RED.state.IMPORT) {
237                                 var nodeSet = getCurrentFlowNodeSet();
238                                 //console.dir(nodeSet);
239                                 if(nodeSet != null && nodeSet.length == 0){
240                                         RED.view.setIsImportAction(true);
241                                 }
242                             RED.view.importNodes($("#node-input-import").val());
243                         }
244                         $( this ).dialog( "close" );
245                     }
246                 },
247                 {
248                     id: "node-dialog-cancel",
249                     text: "Cancel",
250                     click: function() {
251                         $( this ).dialog( "close" );
252                     }
253                 }
254             ],
255             resize: function(e,ui) {
256                 if (editing_node) {
257                     $(this).dialog('option',"sizeCache-"+editing_node.type,ui.size);
258                 }
259             },
260             open: function(e) {
261                 RED.keyboard.disable();
262                 if (editing_node) {
263                     var size = $(this).dialog('option','sizeCache-'+editing_node.type);
264                     if (size) {
265                         $(this).dialog('option','width',size.width);
266                         $(this).dialog('option','height',size.height);
267                     }
268                 }
269             },
270             close: function(e) {
271                 RED.keyboard.enable();
272
273                 if (RED.view.state() != RED.state.IMPORT_DRAGGING) {
274                     RED.view.state(RED.state.DEFAULT);
275                 }
276                 $( this ).dialog('option','height','auto');
277                 $( this ).dialog('option','width','500');
278                 if (editing_node) {
279                     RED.sidebar.info.refresh(editing_node);
280                 }
281                 RED.sidebar.config.refresh();
282                 editing_node = null;
283             }
284     });
285
286     /**
287      * Create a config-node select box for this property
288      * @param node - the node being edited
289      * @param property - the name of the field
290      * @param type - the type of the config-node
291      */
292     function prepareConfigNodeSelect(node,property,type) {
293         var input = $("#node-input-"+property);
294         var node_def = RED.nodes.getType(type);
295
296         input.replaceWith('<select style="width: 60%;" id="node-input-'+property+'"></select>');
297         updateConfigNodeSelect(property,type,node[property]);
298         var select = $("#node-input-"+property);
299         select.after(' <a id="node-input-lookup-'+property+'" class="btn"><i class="fa fa-pencil"></i></a>');
300         $('#node-input-lookup-'+property).click(function(e) {
301             showEditConfigNodeDialog(property,type,select.find(":selected").val());
302             e.preventDefault();
303         });
304         var label = "";
305         var configNode = RED.nodes.node(node[property]);
306         if (configNode && node_def.label) {
307             if (typeof node_def.label == "function") {
308                 label = node_def.label.call(configNode);
309             } else {
310                 label = node_def.label;
311             }
312         }
313         input.val(label);
314     }
315
316     /**
317      * Populate the editor dialog input field for this property
318      * @param node - the node being edited
319      * @param property - the name of the field
320      * @param prefix - the prefix to use in the input element ids (node-input|node-config-input)
321      */
322     function preparePropertyEditor(node,property,prefix) {
323         var input = $("#"+prefix+"-"+property);
324         if (input.attr('type') === "checkbox") {
325             input.prop('checked',node[property]);
326         } else {
327             var val = node[property];
328             if (val == null) {
329                 val = "";
330             }
331             input.val(val);
332         }
333     }
334
335     /**
336      * Add an on-change handler to revalidate a node field
337      * @param node - the node being edited
338      * @param definition - the definition of the node
339      * @param property - the name of the field
340      * @param prefix - the prefix to use in the input element ids (node-input|node-config-input)
341      */
342     function attachPropertyChangeHandler(node,definition,property,prefix) {
343         $("#"+prefix+"-"+property).change(function() {
344             if (!validateNodeProperty(node, definition, property,this.value)) {
345                 $(this).addClass("input-error");
346             } else {
347                 $(this).removeClass("input-error");
348             }
349         });
350     }
351
352     /**
353      * Assign the value to each credential field
354      * @param node
355      * @param credDef
356      * @param credData
357      * @param prefix
358      */
359     function populateCredentialsInputs(node, credDef, credData, prefix) {
360         var cred;
361         for (cred in credDef) {
362             if (credDef.hasOwnProperty(cred)) {
363                 if (credDef[cred].type == 'password') {
364                     if (credData[cred]) {
365                         $('#' + prefix + '-' + cred).val(credData[cred]);
366                     } else if (credData['has_' + cred]) {
367                         $('#' + prefix + '-' + cred).val('__PWRD__');
368                     }
369                     else {
370                         $('#' + prefix + '-' + cred).val('');
371                     }
372                 } else {
373                     preparePropertyEditor(credData, cred, prefix);
374                 }
375                 attachPropertyChangeHandler(node, credDef, cred, prefix);
376             }
377         }
378         for (cred in credDef) {
379             if (credDef.hasOwnProperty(cred)) {
380                 $("#" + prefix + "-" + cred).change();
381             }
382         }
383     }
384     
385     /**
386      * Update the node credentials from the edit form
387      * @param node - the node containing the credentials
388      * @param credDefinition - definition of the credentials
389      * @param prefix - prefix of the input fields
390      * @return {boolean} whether anything has changed
391      */
392     function updateNodeCredentials(node, credDefinition, prefix) {
393         var changed = false;
394         if(!node.credentials) {
395             node.credentials = {_:{}};
396         }
397
398         for (var cred in credDefinition) {
399             if (credDefinition.hasOwnProperty(cred)) {
400                 var input = $("#" + prefix + '-' + cred);
401                 var value = input.val();
402                 if (credDefinition[cred].type == 'password') {
403                     node.credentials['has_' + cred] = (value !== "");
404                     if (value == '__PWRD__') {
405                         continue;
406                     }
407                     changed = true;
408                     
409                 }
410                 node.credentials[cred] = value;
411                 if (value != node.credentials._[cred]) {
412                     changed = true;
413                 }
414             }
415         }
416         return changed;
417     }
418
419     /**
420      * Prepare all of the editor dialog fields
421      * @param node - the node being edited
422      * @param definition - the node definition
423      * @param prefix - the prefix to use in the input element ids (node-input|node-config-input)
424      */
425     function prepareEditDialog(node,definition,prefix) {
426         for (var d in definition.defaults) {
427             if (definition.defaults.hasOwnProperty(d)) {
428                 if (definition.defaults[d].type) {
429                     prepareConfigNodeSelect(node,d,definition.defaults[d].type);
430                 } else {
431                     preparePropertyEditor(node,d,prefix);
432                 }
433                 attachPropertyChangeHandler(node,definition.defaults,d,prefix);
434             }
435         }
436         var completePrepare = function() {
437             if (definition.oneditprepare) {
438                 definition.oneditprepare.call(node);
439             }
440             for (var d in definition.defaults) {
441                 if (definition.defaults.hasOwnProperty(d)) {
442                     $("#"+prefix+"-"+d).change();
443                 }
444             }
445         }
446         
447         if (definition.credentials) {
448             if (node.credentials) {
449                 populateCredentialsInputs(node, definition.credentials, node.credentials, prefix);
450                 completePrepare();
451             } else {
452                 $.getJSON(getCredentialsURL(node.type, node.id), function (data) {
453                     node.credentials = data;
454                     node.credentials._ = $.extend(true,{},data);
455                     populateCredentialsInputs(node, definition.credentials, node.credentials, prefix);
456                     completePrepare();
457                 });
458             }
459         } else {
460             completePrepare();
461         }
462     }
463
464     function showEditDialog(node) {
465         editing_node = node;
466         RED.view.state(RED.state.EDITING);
467         $("#dialog-form").html($("script[data-template-name='"+node.type+"']").html());
468         $('<input type="text" style="display: none;" />').appendTo("#dialog-form");
469         prepareEditDialog(node,node._def,"node-input");
470         $( "#dialog" ).dialog("option","title","Edit "+node.type+" node").dialog( "open" );
471     }
472
473     function showEditConfigNodeDialog(name,type,id) {
474         var adding = (id == "_ADD_");
475         var node_def = RED.nodes.getType(type);
476
477         var configNode = RED.nodes.node(id);
478         if (configNode == null) {
479             configNode = {
480                 id: (1+Math.random()*4294967295).toString(16),
481                 _def: node_def,
482                 type: type
483             }
484             for (var d in node_def.defaults) {
485                 if (node_def.defaults[d].value) {
486                     configNode[d] = node_def.defaults[d].value;
487                 }
488             }
489         }
490
491         $("#dialog-config-form").html($("script[data-template-name='"+type+"']").html());
492         prepareEditDialog(configNode,node_def,"node-config-input");
493
494         var buttons = $( "#node-config-dialog" ).dialog("option","buttons");
495         if (adding) {
496             if (buttons.length == 3) {
497                 buttons = buttons.splice(1);
498             }
499             buttons[0].text = "Add";
500             $("#node-config-dialog-user-count").html("").hide();
501         } else {
502             if (buttons.length == 2) {
503                 buttons.unshift({
504                         class: 'leftButton',
505                         text: "Delete",
506                         click: function() {
507                             var configProperty = $(this).dialog('option','node-property');
508                             var configId = $(this).dialog('option','node-id');
509                             var configType = $(this).dialog('option','node-type');
510                             var configNode = RED.nodes.node(configId);
511                             var configTypeDef = RED.nodes.getType(configType);
512
513                             if (configTypeDef.ondelete) {
514                                 configTypeDef.ondelete.call(RED.nodes.node(configId));
515                             }
516                             RED.nodes.remove(configId);
517                             for (var i=0;i<configNode.users.length;i++) {
518                                 var user = configNode.users[i];
519                                 for (var d in user._def.defaults) {
520                                     if (user._def.defaults.hasOwnProperty(d) && user[d] == configId) {
521                                         user[d] = "";
522                                     }
523                                 }
524                                 validateNode(user);
525                             }
526                             updateConfigNodeSelect(configProperty,configType,"");
527                             RED.view.dirty(true);
528                             $( this ).dialog( "close" );
529                             RED.view.redraw();
530                         }
531                 });
532             }
533             buttons[1].text = "Update";
534             $("#node-config-dialog-user-count").html(configNode.users.length+" node"+(configNode.users.length==1?" uses":"s use")+" this config").show();
535         }
536         $( "#node-config-dialog" ).dialog("option","buttons",buttons);
537
538         $( "#node-config-dialog" )
539             .dialog("option","node-adding",adding)
540             .dialog("option","node-property",name)
541             .dialog("option","node-id",configNode.id)
542             .dialog("option","node-type",type)
543             .dialog("option","title",(adding?"Add new ":"Edit ")+type+" config node")
544             .dialog( "open" );
545     }
546
547     function updateConfigNodeSelect(name,type,value) {
548         var select = $("#node-input-"+name);
549         var node_def = RED.nodes.getType(type);
550         select.children().remove();
551         RED.nodes.eachConfig(function(config) {
552             if (config.type == type) {
553                 var label = "";
554                 if (typeof node_def.label == "function") {
555                     label = node_def.label.call(config);
556                 } else {
557                     label = node_def.label;
558                 }
559                 select.append('<option value="'+config.id+'"'+(value==config.id?" selected":"")+'>'+label+'</option>');
560             }
561         });
562
563         select.append('<option value="_ADD_"'+(value===""?" selected":"")+'>Add new '+type+'...</option>');
564         window.setTimeout(function() { select.change();},50);
565     }
566
567     $( "#node-config-dialog" ).dialog({
568             modal: true,
569             autoOpen: false,
570             width: 500,
571             closeOnEscape: false,
572             buttons: [
573                 {
574                     id: "node-config-dialog-ok",
575                     text: "Ok",
576                     click: function() {
577                         var configProperty = $(this).dialog('option','node-property');
578                         var configId = $(this).dialog('option','node-id');
579                         var configType = $(this).dialog('option','node-type');
580                         var configAdding = $(this).dialog('option','node-adding');
581                         var configTypeDef = RED.nodes.getType(configType);
582                         var configNode;
583                         var d;
584                         
585                         if (configAdding) {
586                             configNode = {type:configType,id:configId,users:[]};
587                             for (d in configTypeDef.defaults) {
588                                 if (configTypeDef.defaults.hasOwnProperty(d)) {
589                                     configNode[d] = $("#node-config-input-"+d).val();
590                                 }
591                             }
592                             configNode.label = configTypeDef.label;
593                             configNode._def = configTypeDef;
594                             RED.nodes.add(configNode);
595                             updateConfigNodeSelect(configProperty,configType,configNode.id);
596                         } else {
597                             configNode = RED.nodes.node(configId);
598                             for (d in configTypeDef.defaults) {
599                                 if (configTypeDef.defaults.hasOwnProperty(d)) {
600                                     var input = $("#node-config-input-"+d);
601                                     if (input.attr('type') === "checkbox") {
602                                       configNode[d] = input.prop('checked');
603                                     } else {
604                                       configNode[d] = input.val();
605                                     }
606                                 }
607                             }
608                             updateConfigNodeSelect(configProperty,configType,configId);
609                         }
610                         if (configTypeDef.credentials) {
611                             updateNodeCredentials(configNode,configTypeDef.credentials,"node-config-input");
612                         }
613                         if (configTypeDef.oneditsave) {
614                             configTypeDef.oneditsave.call(RED.nodes.node(configId));
615                         }
616                         validateNode(configNode);
617
618                         RED.view.dirty(true);
619                         $(this).dialog("close");
620
621                     }
622                 },
623                 {
624                     id: "node-config-dialog-cancel",
625                     text: "Cancel",
626                     click: function() {
627                         var configType = $(this).dialog('option','node-type');
628                         var configId = $(this).dialog('option','node-id');
629                         var configAdding = $(this).dialog('option','node-adding');
630                         var configTypeDef = RED.nodes.getType(configType);
631
632                         if (configTypeDef.oneditcancel) {
633                             // TODO: what to pass as this to call
634                             if (configTypeDef.oneditcancel) {
635                                 var cn = RED.nodes.node(configId);
636                                 if (cn) {
637                                     configTypeDef.oneditcancel.call(cn,false);
638                                 } else {
639                                     configTypeDef.oneditcancel.call({id:configId},true);
640                                 }
641                             }
642                         }
643                         $( this ).dialog( "close" );
644                     }
645                 }
646             ],
647             resize: function(e,ui) {
648             },
649             open: function(e) {
650                 if (RED.view.state() != RED.state.EDITING) {
651                     RED.keyboard.disable();
652                 }
653             },
654             close: function(e) {
655                 $("#dialog-config-form").html("");
656                 if (RED.view.state() != RED.state.EDITING) {
657                     RED.keyboard.enable();
658                 }
659                 RED.sidebar.config.refresh();
660             }
661     });
662
663
664     return {
665         edit: showEditDialog,
666         editConfig: showEditConfigNodeDialog,
667         validateNode: validateNode,
668         updateNodeProperties: updateNodeProperties, // TODO: only exposed for edit-undo
669         createEditor: function(options) {
670             var editor = ace.edit(options.id);
671             //editor.setTheme("ace/theme/tomorrow");
672             editor.setTheme("ace/theme/eclipse");
673             if (options.mode) {
674                 editor.getSession().setMode(options.mode);
675             }
676             if (options.foldStyle) {
677                 editor.getSession().setFoldStyle(options.foldStyle);
678             } else {
679                 editor.getSession().setFoldStyle('markbeginend');
680             }
681
682         
683             if (options.options) {
684                 editor.setOptions(options.options);
685             } else {
686                 editor.setOptions({
687                     enableBasicAutocompletion:false ,
688                     enableSnippets:false ,
689                     fontSize: "14pt" ,
690                     showGutter: false
691                 });
692             }
693             editor.$blockScrolling = Infinity;
694                 return editor;
695         }
696     }
697 })();