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