src/JsRender/Roo.vala
[app.Builder.js] / src / JsRender / Roo.vala
1  
2 namespace JsRender {
3
4     static int rid = 0; 
5    
6     class Roo : JsRender 
7     {
8         string region;
9         bool disabled;
10
11         Gee.HashMap<string,string> transStrings; // map of md5 -> string..
12         
13         public Roo(Project.Project project, string path) {
14             base( project, path);
15             this.xtype = "Roo";
16              this.language = "js";
17             
18             
19             //this.items = false;
20             //if (cfg.json) {
21             //    var jstr =  JSON.parse(cfg.json);
22             //    this.items = [ jstr ];
23             //    //console.log(cfg.items.length);
24             //    delete cfg.json; // not needed!
25             // }
26             this.modOrder = "001"; /// sequence id that this uses.
27             this.region = "center";
28             this.disabled = false;
29             
30             // super?!?!
31             this.id = "file-roo-%d".printf(rid++);
32             //console.dump(this);
33             // various loader methods..
34
35             string[]  dsp = { "title",
36                 "legend",
37                 "loadingText",
38                 "emptyText",
39                 "qtip",
40                 "value",
41                 "text",
42                 "emptyMsg",
43                 "displayMsg" };
44             for (var i=0;i<dsp.length;i++) {
45                 this.doubleStringProps.add(dsp[i]);
46             }
47
48             
49         }
50     
51     /*    
52         setNSID : function(id)
53         {
54             
55             this.items[0]['|module'] = id;
56        
57             
58         },
59         
60         
61         getType: function() {
62             return 'Roo';
63         },
64
65     */
66                 
67         public   override void   removeFiles() {
68                 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
69                 if (FileUtils.test(html, FileTest.EXISTS)) {
70                         GLib.FileUtils.remove(html);
71                 }
72                 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
73                 if (FileUtils.test(js, FileTest.EXISTS)) {
74                         GLib.FileUtils.remove(js);
75                 }
76         }
77                 
78         public  override void  loadItems() throws GLib.Error // : function(cb, sync) == original was async.
79         {
80             
81              
82                 print("load Items!");
83                 if (this.tree != null) {
84                         return;
85                 }
86                 print("load " + this.path);
87
88                 var pa = new Json.Parser();
89                 pa.load_from_file(this.path);
90                 var node = pa.get_root();
91
92                 if (node.get_node_type () != Json.NodeType.OBJECT) {
93                         throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
94                 }
95                 var obj = node.get_object ();
96         
97         
98                 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
99                 this.name = this.jsonHasOrEmpty(obj, "name");
100                 this.parent = this.jsonHasOrEmpty(obj, "parent");
101                 this.permname = this.jsonHasOrEmpty(obj, "permname");
102                 this.title = this.jsonHasOrEmpty(obj, "title");
103                 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
104
105                 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
106                 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
107
108                 
109                 // load items[0] ??? into tree...
110                 if (obj.has_member("items") 
111                         && 
112                         obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
113                         &&
114                         obj.get_array_member("items").get_length() > 0
115                 ) {
116                         this.tree = new Node(); 
117                         var ar = obj.get_array_member("items");
118                         var tree_base = ar.get_object_element(0);
119                         this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
120                 }
121
122
123             
124         }
125         /**
126          * old code had broken xtypes and used arrays differently,
127          * this code should try and clean it up..
128          * 
129          * 
130          * /
131         fixItems : function(node, fixthis)
132         {
133             if (fixthis) {
134                 // fix xtype.
135                 var fn = this.guessName(node);
136                 //print("guessname got " + fn);
137                 if (fn) {
138                     var bits = fn.split('.');
139                     node.xtype = bits.pop();
140                     node['|xns'] = bits.join('.');
141                     
142                 }
143                 // fix array???
144                  
145                 
146             }
147             if (!node.items || !node.items.length) {
148                 return;
149             }
150             var _this = this;
151             var aitems = [];
152             var nitems = [];
153             node.items.forEach(function(i) {
154                 
155                 
156                 
157                 _this.fixItems(i, true);
158                 if (i.xtype == 'Array') {
159                     aitems.push(i);
160                     return;
161                 }    
162                 nitems.push(i);
163             });
164             node.items = nitems; 
165             
166             if (!aitems.length) {
167                 return;
168             }
169             
170             aitems.forEach(function(i) {
171                 
172                 if (!i.items || !i.items.length) {
173                     return;
174                 }
175                 var prop = i['*prop'] + '[]';
176                 // colModel to cm?
177                 i.items.forEach(function(c) {
178                     c['*prop']  = prop;
179                     node.items.push(c);
180                     
181                 });
182                 
183                 
184             });
185             
186             
187             // array handling.. 
188             
189             
190             
191             
192             
193         },
194     */
195         
196         public  override  void save()
197         {
198             
199                 print("--- JsRender.Roo.save");
200                 this.saveBJS();
201
202                 // no tree..
203                 if (this.tree == null) {
204                         return;
205                 }
206                 // now write the js file..
207                 string js;
208                 try {
209                         Regex regex = new Regex("\\.(bjs|js)$");
210
211                         js = regex.replace(this.path,this.path.length , 0 , ".js");
212                 } catch (RegexError e) {
213                         this.name = "???";
214                         print("count not make filename from path");
215                         return;
216                 }
217
218
219                 //var d = new Date();
220                 var js_src = this.toSource();            
221                 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
222                 try {
223                         this.writeFile(js, js_src);            
224                 } catch (FileError e ) {
225                         print("Save failed\n");
226                 }
227                 // for bootstrap - we can write the HTML to the templates directory..
228                  
229             //var top = this.guessName(this.items[0]);
230             //print ("TOP = " + top)
231              
232             
233             
234             
235         }
236
237          
238
239          
240         public override void saveHTML ( string html )
241         {
242                  
243                 var top = this.tree.fqn();
244                 print ("TOP = " + top + "\n" );
245                 if (top.index_of("Roo.bootstrap.") < 0 &&
246                     top.index_of("Roo.mailer.") < 0
247                         ) {
248                         return;
249                 }
250                 
251                 
252 // now write the js file..
253                 string fn;
254                 try {
255                         Regex regex = new Regex("\\.(bjs|js)$");
256
257                         fn = regex.replace(this.path,this.path.length , 0 , ".html");
258                 } catch (RegexError e) {
259                         this.name = "???";
260                         print("count not make filename from path");
261                         return;
262                 }
263                 var bn = GLib.Path.get_basename(fn);
264                 var dn = GLib.Path.get_dirname(fn);
265
266                 var targetdir = dn + (
267                         top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
268                               
269                 
270                 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
271                         print("Skip save - templates folder does not exist : %s\n", targetdir);
272                         return;
273                 }
274                 print("SAVE HTML -- %s\n%s\n",targetdir + "/" +  bn, html);
275                 try {
276                         this.writeFile(targetdir + "/" +  bn , html);            
277                 } catch (FileError e ) {
278                         print("SaveHtml failed\n");
279                 }
280             
281             
282             
283         }
284
285         public Gee.ArrayList<string> findxincludes(Node node,   Gee.ArrayList<string> ret)
286         {
287                 
288                 if (node.props.has_key("* xinclude")) {
289                         ret.add(node.props.get("* xinclude"));
290                 }
291                 for (var i =0; i < node.items.size; i++) {
292                         this.findxincludes(node.items.get(i), ret);
293                 }
294                 return ret;
295                         
296         }
297         public Gee.ArrayList<string> transStrings(Node node,   Gee.ArrayList<string> ret)
298         {
299                 // iterate properties...
300                 
301
302                 
303                 // iterate children..
304                 for (var i =0; i < node.items.size; i++) {
305                         this.transStrings(node.items.get(i), ret);
306                 }
307                 return ret;
308                         
309         }    
310         /**
311          * javascript used in Webkit preview 
312          */
313         
314         public override string  toSourcePreview()
315         {
316                 print("to source preview\n");
317                 if (this.tree == null) {
318                         return "";
319                 }
320                 var top = this.tree.fqn();
321                 var xinc = new Gee.ArrayList<string>(); 
322
323                 this.findxincludes(this.tree, xinc);
324                 print("got %d xincludes\n", xinc.size);
325                 var prefix_data = "";
326                 if (xinc.size > 0 ) {
327                         for(var i = 0; i < xinc.size; i++) {
328                                 print("check xinclude:  %s\n", xinc.get(i));
329                                 var sf = this.project.getByName(xinc.get(i));
330                                 if (sf == null) {
331                                         print("Failed to find file by name?\n");
332                                         continue;
333                                 }
334
335                                 sf.loadItems();
336                                 var xinc_str = sf.toSource();
337                                 
338                                 //string xinc_str;
339                                 //FileUtils.get_contents(js, out xinc_str);
340                                 prefix_data += "\n" + xinc_str + "\n";
341                                 
342                         }
343
344                 }
345
346                 
347                 
348                 //print(JSON.stringify(this.items, null,4));
349                        
350                 if (top == null) {
351                         print ("guessname returned false");
352                         return "";
353                 }
354
355
356                 if (top.contains("Dialog")) {
357                         return prefix_data + this.toSourceDialog(true);
358                 }
359
360                 if (top.contains("Modal")) {
361                         return prefix_data + this.toSourceModal(true);
362                 }
363
364                 return prefix_data + this.toSourceLayout(true);
365             
366             
367             
368         }
369         
370         /**
371          * This needs to use some options on the project
372          * to determine how the file is output..
373          * 
374          * At present we are hard coding it..
375          * 
376          * 
377          */
378         public override string toSource()
379         {
380             // dump the file tree back out to a string.
381             
382             // we have 2 types = dialogs and components
383             // 
384             if (this.tree == null) {
385                     return "";
386             }
387             var top = this.tree.fqn();
388             if (top == null) {
389                 return "";
390             }
391             if (top.contains("Dialog")) {
392                 return this.toSourceDialog(false);
393             }
394             
395             if (top.contains("Modal")) {
396                 return this.toSourceModal(false);
397             }
398             return this.toSourceLayout(false);
399             
400             /*
401             eventually support 'classes??'
402              return this.toSourceStdClass();
403             */
404               
405         }
406        
407         public string outputHeader()
408         {
409                 string[] s = {
410                         "//<script type=\"text/javascript\">",
411                         "",
412                         "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
413                         ""
414                    
415                 };  
416                 var ret=  string.joinv("\n",s);
417                 var bits = this.name.split(".");
418                 if (bits.length > 1) {
419                         ret += "\nRoo.namespace(\'" + 
420                                 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
421                                 "');\n";
422                                 
423                 }
424                 /// genericlly used..
425                   
426                 return ret;
427             
428        
429         }
430         // a standard dialog module.
431         // fixme - this could be alot neater..
432         public string toSourceDialog(bool isPreview) 
433         {
434             
435             //var items = JSON.parse(JSON.stringify(this.items[0]));
436             
437             
438             var o = this.mungeToString("    ");   
439
440  
441             string[] adda = { " = {",
442                 "",
443                 " dialog : false,",
444                 " callback:  false,",
445                 "",   
446                 " show : function(data, cb)",
447                 " {",
448                 "  if (!this.dialog) {",
449                 "   this.create();",
450                 "  }",
451                 "",
452                 "  this.callback = cb;",
453                 "  this.data = data;",
454                 "  this.dialog.show(this.data._el);",
455                 "  if (this.form) {",
456                 "   this.form.reset();",
457                 "   this.form.setValues(data);",
458                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
459                 "  }",
460                 "",   
461                 " },",
462                 "",
463                 " create : function()",
464                 " {",
465                 "   var _this = this;",
466                 "   this.dialog = Roo.factory(" 
467             };
468             string[] addb = {  
469                    ");",
470                 " }",
471                 "};",
472                 ""
473             };
474             return  this.outputHeader() + "\n" +
475                 this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
476             
477              
478              
479              
480         }
481         
482         public string toSourceModal(bool isPreview) 
483         {
484             
485             
486             //var items = JSON.parse(JSON.stringify(this.items[0]));
487             var o = this.mungeToString("    ");   
488             
489             string[] adda = { " = {",
490                 "",
491                 " dialog : false,",
492                 " callback:  false,",
493                 "",   
494                 " show : function(data, cb)",
495                 " {",
496                 "  if (!this.dialog) {",
497                 "   this.create();",
498                 "  }",
499                 "",
500                 "  this.callback = cb;",
501                 "  this.data = data;",
502                 "  this.dialog.show(this.data._el);",
503                 "  if (this.form) {",
504                 "   this.form.reset();",
505                 "   this.form.setValues(data);",
506                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
507                 "  }",
508                 "",   
509                 " },",
510                 "",
511                 " create : function()",
512                 " {",
513                 "  var _this = this;",
514                 "  this.dialog = Roo.factory("
515             };
516             string[] addb =  {
517                 "  );",
518                 " }",
519                 "};",
520                 ""
521             };
522             return this.outputHeader() + "\n" + 
523                 this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
524              
525              
526              
527         }
528         
529         
530         public string   pathToPart()
531         {
532             var dir = Path.get_basename(Path.get_dirname(this.path));
533             var ar = dir.split(".");
534             var modname = ar[ar.length-1];
535             
536             // now we have the 'module name'..
537             var fbits = Path.get_basename(this.path).split(".");
538             
539              
540             var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
541             if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
542                 npart = npart.substring(modname.length);
543             }
544             return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
545             //return ret;
546             
547             
548             
549             
550         }
551         
552         // a layout compoent 
553         public string toSourceLayout(bool isPreview) 
554         {
555           
556             
557                 if (isPreview) {
558                         //       topItem.region = 'center';
559                         //    topItem.background = false;
560                 }
561             
562                 var o = this.mungeToString("   ");   
563                 var reg = new Regex("[^A-Za-z.]+");
564             
565                 string modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
566             
567                 string  parent =   (this.parent.length > 0 ?  "'" + this.parent + "'" :  "false");
568
569                 
570                 
571                 if (isPreview) {
572                         // set to false to ensure this is the top level..
573                         parent = "false";
574                         var topnode = this.tree.fqn();
575                         print("topnode = %s\n", topnode);
576                         if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
577                             topnode != "Roo.bootstrap.Body"
578                         ) {
579                                 parent = "\"#bootstrap-body\"";
580                         }
581                           
582                 }
583             
584           
585                 return 
586                         this.outputHeader() + "\n" +
587                         
588                         this.name  +  " = new Roo.XComponent({\n" +
589                         "  part     :  "+ this.pathToPart() + ",\n" +
590                                 /// critical used by builder to associate modules/parts/persm
591                         "  order    : '" +modkey+"',\n" +
592                         "  region   : '" + this.region   +"',\n" +
593                         "  parent   : "+ parent + ",\n" +
594                         "  name     : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
595                         "  disabled : " + (this.disabled ? "true" : "false") +", \n" +
596                         "  permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
597                             
598                        // "    tree : function() { return this._tree(); },\n" +   //BC
599                         "  _tree : function()\n" +
600                         "  {\n" +
601                         "   var _this = this;\n" + // bc
602                         "   var MODULE = this;\n" + /// this looks like a better name.
603                         "   return " + o + ";" +
604                         "  }\n" +
605                         "});\n";
606                          
607              
608             
609         }
610             
611         public new string? guessName (Node? ar) // turns the object into full name.
612         {
613              // eg. xns: Roo, xtype: XXX -> Roo.xxx
614             if (ar == null) {
615                 return null;
616             }
617             
618             string[] ret = {} ;
619             ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
620              
621             
622             if ( ar.get("xtype").length < 1) {
623                 return null;
624             }
625                     
626             var xtype = ar.get("xtype");
627
628             if (xtype[0] == '*') { // prefixes????
629                 xtype  = xtype.substring(1);
630             }
631             if (! Regex.match_simple("^Roo", xtype)) {
632                 
633                 // already starts with roo...
634                 ret = {};
635             }
636             ret += xtype;
637             var str =  string.joinv(".", ret);
638             
639             return str;
640            // 
641             //Palete.Palete.factory("Roo").guessName(str);
642             
643                             
644                                  
645         }
646         
647         string getHelpUrl(string cls)
648         {
649             return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";
650         }
651                  
652      
653     }
654 }