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