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