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