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