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