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