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