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