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