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
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         Gee.HashMap<string,string> transStrings; // map of md5 -> string..
298
299         public string addTransString(string str)
300         {
301             this.transStrings.set(str,   GLib.Checksum.compute_for_string (ChecksumType.MD5, str));
302         }
303         
304         public Gee.ArrayList<string> transStrings(Node node,   Gee.ArrayList<string> ret)
305         {
306                 // iterate properties...
307                    // use doubleStringProps
308                 
309
310                 
311                 // iterate children..
312                 for (var i =0; i < node.items.size; i++) {
313                         this.transStrings(node.items.get(i), ret);
314                 }
315                 return ret;
316                         
317         }    
318         /**
319          * javascript used in Webkit preview 
320          */
321         
322         public override string  toSourcePreview()
323         {
324                 print("to source preview\n");
325                 if (this.tree == null) {
326                         return "";
327                 }
328                 var top = this.tree.fqn();
329                 var xinc = new Gee.ArrayList<string>(); 
330
331                 this.findxincludes(this.tree, xinc);
332                 print("got %d xincludes\n", xinc.size);
333                 var prefix_data = "";
334                 if (xinc.size > 0 ) {
335                         for(var i = 0; i < xinc.size; i++) {
336                                 print("check xinclude:  %s\n", xinc.get(i));
337                                 var sf = this.project.getByName(xinc.get(i));
338                                 if (sf == null) {
339                                         print("Failed to find file by name?\n");
340                                         continue;
341                                 }
342
343                                 sf.loadItems();
344                                 var xinc_str = sf.toSource();
345                                 
346                                 //string xinc_str;
347                                 //FileUtils.get_contents(js, out xinc_str);
348                                 prefix_data += "\n" + xinc_str + "\n";
349                                 
350                         }
351
352                 }
353
354                 
355                 
356                 //print(JSON.stringify(this.items, null,4));
357                        
358                 if (top == null) {
359                         print ("guessname returned false");
360                         return "";
361                 }
362
363
364                 if (top.contains("Dialog")) {
365                         return prefix_data + this.toSourceDialog(true);
366                 }
367
368                 if (top.contains("Modal")) {
369                         return prefix_data + this.toSourceModal(true);
370                 }
371
372                 return prefix_data + this.toSourceLayout(true);
373             
374             
375             
376         }
377         
378         /**
379          * This needs to use some options on the project
380          * to determine how the file is output..
381          * 
382          * At present we are hard coding it..
383          * 
384          * 
385          */
386         public override string toSource()
387         {
388             // dump the file tree back out to a string.
389             
390             // we have 2 types = dialogs and components
391             // 
392             if (this.tree == null) {
393                     return "";
394             }
395             var top = this.tree.fqn();
396             if (top == null) {
397                 return "";
398             }
399             if (top.contains("Dialog")) {
400                 return this.toSourceDialog(false);
401             }
402             
403             if (top.contains("Modal")) {
404                 return this.toSourceModal(false);
405             }
406             return this.toSourceLayout(false);
407             
408             /*
409             eventually support 'classes??'
410              return this.toSourceStdClass();
411             */
412               
413         }
414        
415         public string outputHeader()
416         {
417                 string[] s = {
418                         "//<script type=\"text/javascript\">",
419                         "",
420                         "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
421                         ""
422                    
423                 };  
424                 var ret=  string.joinv("\n",s);
425                 var bits = this.name.split(".");
426                 if (bits.length > 1) {
427                         ret += "\nRoo.namespace(\'" + 
428                                 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
429                                 "');\n";
430                                 
431                 }
432                 /// genericlly used..
433                   
434                 return ret;
435             
436        
437         }
438         // a standard dialog module.
439         // fixme - this could be alot neater..
440         public string toSourceDialog(bool isPreview) 
441         {
442             
443             //var items = JSON.parse(JSON.stringify(this.items[0]));
444             
445             
446             var o = this.mungeToString("    ");   
447
448  
449             string[] adda = { " = {",
450                 "",
451                 " dialog : false,",
452                 " callback:  false,",
453                 "",   
454                 " show : function(data, cb)",
455                 " {",
456                 "  if (!this.dialog) {",
457                 "   this.create();",
458                 "  }",
459                 "",
460                 "  this.callback = cb;",
461                 "  this.data = data;",
462                 "  this.dialog.show(this.data._el);",
463                 "  if (this.form) {",
464                 "   this.form.reset();",
465                 "   this.form.setValues(data);",
466                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
467                 "  }",
468                 "",   
469                 " },",
470                 "",
471                 " create : function()",
472                 " {",
473                 "   var _this = this;",
474                 "   this.dialog = Roo.factory(" 
475             };
476             string[] addb = {  
477                    ");",
478                 " }",
479                 "};",
480                 ""
481             };
482             return  this.outputHeader() + "\n" +
483                 this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
484             
485              
486              
487              
488         }
489         
490         public string toSourceModal(bool isPreview) 
491         {
492             
493             
494             //var items = JSON.parse(JSON.stringify(this.items[0]));
495             var o = this.mungeToString("    ");   
496             
497             string[] adda = { " = {",
498                 "",
499                 " dialog : false,",
500                 " callback:  false,",
501                 "",   
502                 " show : function(data, cb)",
503                 " {",
504                 "  if (!this.dialog) {",
505                 "   this.create();",
506                 "  }",
507                 "",
508                 "  this.callback = cb;",
509                 "  this.data = data;",
510                 "  this.dialog.show(this.data._el);",
511                 "  if (this.form) {",
512                 "   this.form.reset();",
513                 "   this.form.setValues(data);",
514                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
515                 "  }",
516                 "",   
517                 " },",
518                 "",
519                 " create : function()",
520                 " {",
521                 "  var _this = this;",
522                 "  this.dialog = Roo.factory("
523             };
524             string[] addb =  {
525                 "  );",
526                 " }",
527                 "};",
528                 ""
529             };
530             return this.outputHeader() + "\n" + 
531                 this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
532              
533              
534              
535         }
536         
537         
538         public string   pathToPart()
539         {
540             var dir = Path.get_basename(Path.get_dirname(this.path));
541             var ar = dir.split(".");
542             var modname = ar[ar.length-1];
543             
544             // now we have the 'module name'..
545             var fbits = Path.get_basename(this.path).split(".");
546             
547              
548             var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
549             if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
550                 npart = npart.substring(modname.length);
551             }
552             return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
553             //return ret;
554             
555             
556             
557             
558         }
559         
560         // a layout compoent 
561         public string toSourceLayout(bool isPreview) 
562         {
563           
564             
565                 if (isPreview) {
566                         //       topItem.region = 'center';
567                         //    topItem.background = false;
568                 }
569             
570                 var o = this.mungeToString("   ");   
571                 var reg = new Regex("[^A-Za-z.]+");
572             
573                 string modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
574             
575                 string  parent =   (this.parent.length > 0 ?  "'" + this.parent + "'" :  "false");
576
577                 
578                 
579                 if (isPreview) {
580                         // set to false to ensure this is the top level..
581                         parent = "false";
582                         var topnode = this.tree.fqn();
583                         print("topnode = %s\n", topnode);
584                         if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
585                             topnode != "Roo.bootstrap.Body"
586                         ) {
587                                 parent = "\"#bootstrap-body\"";
588                         }
589                           
590                 }
591             
592           
593                 return 
594                         this.outputHeader() + "\n" +
595                         
596                         this.name  +  " = new Roo.XComponent({\n" +
597                         "  part     :  "+ this.pathToPart() + ",\n" +
598                                 /// critical used by builder to associate modules/parts/persm
599                         "  order    : '" +modkey+"',\n" +
600                         "  region   : '" + this.region   +"',\n" +
601                         "  parent   : "+ parent + ",\n" +
602                         "  name     : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
603                         "  disabled : " + (this.disabled ? "true" : "false") +", \n" +
604                         "  permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
605                             
606                        // "    tree : function() { return this._tree(); },\n" +   //BC
607                         "  _tree : function()\n" +
608                         "  {\n" +
609                         "   var _this = this;\n" + // bc
610                         "   var MODULE = this;\n" + /// this looks like a better name.
611                         "   return " + o + ";" +
612                         "  }\n" +
613                         "});\n";
614                          
615              
616             
617         }
618             
619         public new string? guessName (Node? ar) // turns the object into full name.
620         {
621              // eg. xns: Roo, xtype: XXX -> Roo.xxx
622             if (ar == null) {
623                 return null;
624             }
625             
626             string[] ret = {} ;
627             ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
628              
629             
630             if ( ar.get("xtype").length < 1) {
631                 return null;
632             }
633                     
634             var xtype = ar.get("xtype");
635
636             if (xtype[0] == '*') { // prefixes????
637                 xtype  = xtype.substring(1);
638             }
639             if (! Regex.match_simple("^Roo", xtype)) {
640                 
641                 // already starts with roo...
642                 ret = {};
643             }
644             ret += xtype;
645             var str =  string.joinv(".", ret);
646             
647             return str;
648            // 
649             //Palete.Palete.factory("Roo").guessName(str);
650             
651                             
652                                  
653         }
654         
655         string getHelpUrl(string cls)
656         {
657             return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";
658         }
659                  
660      
661     }
662 }