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