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