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