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