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