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