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