[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / public / red / ui / library.js
1 /**
2  * Copyright 2013 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.library = (function() {
17     
18     
19     function loadFlowLibrary() {
20         $.getJSON("library/flows",function(data) {
21             //console.log(data);
22
23             var buildMenu = function(data,root) {
24                 var i;
25                 var li;
26                 var a;
27                 var ul = document.createElement("ul");
28                 ul.id = "btn-import-library-submenu";
29                 ul.className = "dropdown-menu";
30                 if (data.d) {
31                     for (i in data.d) {
32                         if (data.d.hasOwnProperty(i)) {
33                             li = document.createElement("li");
34                             li.className = "dropdown-submenu pull-left";
35                             a = document.createElement("a");
36                             a.href="#";
37                             a.innerHTML = i;
38                             li.appendChild(a);
39                             li.appendChild(buildMenu(data.d[i],root+(root!==""?"/":"")+i));
40                             ul.appendChild(li);
41                         }
42                     }
43                 }
44                 if (data.f) {
45                     for (i in data.f) {
46                         if (data.f.hasOwnProperty(i)) {
47                             li = document.createElement("li");
48                             a = document.createElement("a");
49                             a.href="#";
50                             a.innerHTML = data.f[i];
51                             a.flowName = root+(root!==""?"/":"")+data.f[i];
52                             a.onclick = function() {
53                                 $.get('library/flows/'+this.flowName, function(data) {
54                                         RED.view.importNodes(data);
55                                 });
56                             };
57                             li.appendChild(a);
58                             ul.appendChild(li);
59                         }
60                     }
61                 }
62                 return ul;
63             };
64             var menu = buildMenu(data,"");
65             //TODO: need an api in RED.menu for this
66             $("#btn-import-library-submenu").replaceWith(menu);
67         });
68     }
69     loadFlowLibrary();
70
71
72     
73     function createUI(options) {
74         var libraryData = {};
75         var selectedLibraryItem = null;
76         var libraryEditor = null;
77         
78         function buildFileListItem(item) {
79             var li = document.createElement("li");
80             li.onmouseover = function(e) { $(this).addClass("list-hover"); };
81             li.onmouseout = function(e) { $(this).removeClass("list-hover"); };
82             return li;
83         }
84         
85         function buildFileList(root,data) {
86             var ul = document.createElement("ul");
87             var li;
88             for (var i=0;i<data.length;i++) {
89                 var v = data[i];
90                 if (typeof v === "string") {
91                     // directory
92                     li = buildFileListItem(v);
93                     li.onclick = (function () {
94                         var dirName = v;
95                         return function(e) {
96                             var bcli = $('<li class="active"><span class="divider">/</span> <a href="#">'+dirName+'</a></li>');
97                             $("a",bcli).click(function(e) { 
98                                 $(this).parent().nextAll().remove();
99                                 $.getJSON("library/"+options.url+root+dirName,function(data) {
100                                     $("#node-select-library").children().first().replaceWith(buildFileList(root+dirName+"/",data));
101                                 });
102                                 e.stopPropagation();
103                             });
104                             var bc = $("#node-dialog-library-breadcrumbs");
105                             $(".active",bc).removeClass("active");
106                             bc.append(bcli);
107                             $.getJSON("library/"+options.url+root+dirName,function(data) {
108                                     $("#node-select-library").children().first().replaceWith(buildFileList(root+dirName+"/",data));
109                             });
110                         }
111                     })();
112                     li.innerHTML = '<i class="fa fa-folder"></i> '+v+"</i>";
113                     ul.appendChild(li);
114                 } else {
115                     // file
116                    li = buildFileListItem(v);
117                    li.innerHTML = v.name;
118                    li.onclick = (function() {
119                        var item = v;
120                        return function(e) {
121                            $(".list-selected",ul).removeClass("list-selected");
122                            $(this).addClass("list-selected");
123                            $.get("library/"+options.url+root+item.fn, function(data) {
124                                    selectedLibraryItem = item;
125                                    libraryEditor.setText(data);
126                            });
127                        }
128                    })();
129                    ul.appendChild(li);
130                 }
131             }
132             return ul;
133         }
134     
135 /*
136 //Commented this portion as is not used by the DGBuilder application
137         $('#node-input-name').addClass('input-append-left').css("width","65%").after(
138             '<div class="btn-group" style="margin-left: 0px;">'+
139             '<button id="node-input-'+options.type+'-lookup" class="btn input-append-right" data-toggle="dropdown"><i class="fa fa-book"></i> <i class="fa fa-caret-down"></i></button>'+
140             '<ul class="dropdown-menu pull-right" role="menu">'+
141             '<li><a id="node-input-'+options.type+'-menu-open-library" tabindex="-1" href="#">Open Library...</a></li>'+
142             '<li><a id="node-input-'+options.type+'-menu-save-library" tabindex="-1" href="#">Save to Library...</a></li>'+
143             '</ul></div>'
144         );
145     
146         
147         
148         $('#node-input-'+options.type+'-menu-open-library').click(function(e) {
149             $("#node-select-library").children().remove();
150             var bc = $("#node-dialog-library-breadcrumbs");
151             bc.children().first().nextAll().remove();
152             libraryEditor.setText('');
153             
154             $.getJSON("library/"+options.url,function(data) {
155                 $("#node-select-library").append(buildFileList("/",data));
156                 $("#node-dialog-library-breadcrumbs a").click(function(e) {
157                     $(this).parent().nextAll().remove();
158                     $("#node-select-library").children().first().replaceWith(buildFileList("/",data));
159                     e.stopPropagation();
160                 });
161                 $( "#node-dialog-library-lookup" ).dialog( "open" );
162             });
163             
164             e.preventDefault();
165         });
166     
167         $('#node-input-'+options.type+'-menu-save-library').click(function(e) {
168             //var found = false;
169             var name = $("#node-input-name").val().replace(/(^\s*)|(\s*$)/g,"");
170
171             //var buildPathList = function(data,root) {
172             //    var paths = [];
173             //    if (data.d) {
174             //        for (var i in data.d) {
175             //            var dn = root+(root==""?"":"/")+i;
176             //            var d = {
177             //                label:dn,
178             //                files:[]
179             //            };
180             //            for (var f in data.d[i].f) {
181             //                d.files.push(data.d[i].f[f].fn.split("/").slice(-1)[0]);
182             //            }
183             //            paths.push(d);
184             //            paths = paths.concat(buildPathList(data.d[i],root+(root==""?"":"/")+i));
185             //        }
186             //    }
187             //    return paths;
188             //};
189             $("#node-dialog-library-save-folder").attr("value","");
190
191             var filename = name.replace(/[^\w-]/g,"-");
192             if (filename === "") {
193                 filename = "unnamed-"+options.type;
194             }
195             $("#node-dialog-library-save-filename").attr("value",filename+".js");
196
197             //var paths = buildPathList(libraryData,"");
198             //$("#node-dialog-library-save-folder").autocomplete({
199             //        minLength: 0,
200             //        source: paths,
201             //        select: function( event, ui ) {
202             //            $("#node-dialog-library-save-filename").autocomplete({
203             //                    minLength: 0,
204             //                    source: ui.item.files
205             //            });
206             //        }
207             //});
208
209             $( "#node-dialog-library-save" ).dialog( "open" );
210             e.preventDefault();
211         });
212         require(["orion/editor/edit"], function(edit) {
213             libraryEditor = edit({
214                 parent:document.getElementById('node-select-library-text'),
215                 lang:"js",
216                 readonly: true
217             });
218         });
219     
220         
221         $( "#node-dialog-library-lookup" ).dialog({
222             title: options.type+" library",
223             modal: true,
224             autoOpen: false,
225             width: 800,
226             height: 450,
227             buttons: [
228                 {
229                     text: "Ok",
230                     click: function() {
231                         if (selectedLibraryItem) {
232                             for (var i=0;i<options.fields.length;i++) {
233                                 var field = options.fields[i];
234                                 $("#node-input-"+field).val(selectedLibraryItem[field]);
235                             }
236                             options.editor.setText(libraryEditor.getText());
237                         }
238                         $( this ).dialog( "close" );
239                     }
240                 },
241                 {
242                     text: "Cancel",
243                     click: function() {
244                         $( this ).dialog( "close" );
245                     }
246                 }
247             ],
248             open: function(e) {
249                 var form = $("form",this);
250                 form.height(form.parent().height()-30);
251                 $("#node-select-library-text").height("100%");
252                 $(".form-row:last-child",form).children().height(form.height()-60);
253             },
254             resize: function(e) {
255                 var form = $("form",this);
256                 form.height(form.parent().height()-30);
257                 $(".form-row:last-child",form).children().height(form.height()-60);
258             }
259         });
260         
261    */ 
262         function saveToLibrary(overwrite) {
263             var name = $("#node-input-name").val().replace(/(^\s*)|(\s*$)/g,"");
264             if (name === "") {
265                 name = "Unnamed "+options.type;
266             }
267             var filename = $("#node-dialog-library-save-filename").val().replace(/(^\s*)|(\s*$)/g,"");
268             var pathname = $("#node-dialog-library-save-folder").val().replace(/(^\s*)|(\s*$)/g,"");
269             if (filename === "" || !/.+\.js$/.test(filename)) {
270                 RED.notify("Invalid filename","warning");
271                 return;
272             }
273             var fullpath = pathname+(pathname===""?"":"/")+filename;
274             if (!overwrite) {
275                 //var pathnameParts = pathname.split("/");
276                 //var exists = false;
277                 //var ds = libraryData;
278                 //for (var pnp in pathnameParts) {
279                 //    if (ds.d && pathnameParts[pnp] in ds.d) {
280                 //        ds = ds.d[pathnameParts[pnp]];
281                 //    } else {
282                 //        ds = null;
283                 //        break;
284                 //    }
285                 //}
286                 //if (ds && ds.f) {
287                 //    for (var f in ds.f) {
288                 //        if (ds.f[f].fn == fullpath) {
289                 //            exists = true;
290                 //            break;
291                 //        }
292                 //    }
293                 //}
294                 //if (exists) {
295                 //    $("#node-dialog-library-save-type").html(options.type);
296                 //    $("#node-dialog-library-save-name").html(fullpath);
297                 //    $("#node-dialog-library-save-confirm").dialog( "open" );
298                 //    return;
299                 //}
300             }
301             var queryArgs = [];
302             for (var i=0;i<options.fields.length;i++) {
303                 var field = options.fields[i];
304                 if (field == "name") {
305                     queryArgs.push("name="+encodeURIComponent(name));
306                 } else {
307                     queryArgs.push(encodeURIComponent(field)+"="+encodeURIComponent($("#node-input-"+field).val()));
308                 }
309             }
310             var queryString = queryArgs.join("&");
311             
312             var text = options.editor.getText();
313             $.post("library/"+options.url+'/'+fullpath+"?"+queryString,text,function() {
314                     RED.notify("Saved "+options.type,"success");
315             });
316         }
317         $( "#node-dialog-library-save-confirm" ).dialog({
318             title: "Save to library",
319             modal: true,
320             autoOpen: false,
321             width: 530,
322             height: 230,
323             buttons: [
324                 {
325                     text: "Ok",
326                     click: function() {
327                         saveToLibrary(true);
328                         $( this ).dialog( "close" );
329                     }
330                 },
331                 {
332                     text: "Cancel",
333                     click: function() {
334                         $( this ).dialog( "close" );
335                     }
336                 }
337             ]
338         });
339         $( "#node-dialog-library-save" ).dialog({
340             title: "Save to library",
341             modal: true,
342             autoOpen: false,
343             width: 530,
344             height: 230,
345             buttons: [
346                 {
347                     text: "Ok",
348                     click: function() {
349                         saveToLibrary(false);
350                         $( this ).dialog( "close" );
351                     }
352                 },
353                 {
354                     text: "Cancel",
355                     click: function() {
356                         $( this ).dialog( "close" );
357                     }
358                 }
359             ]
360         });
361
362     }
363     
364     return {
365         create: createUI,
366         loadFlowLibrary: loadFlowLibrary
367     }
368 })();
369
370