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