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                 this.saveBJS();
214
215                 // no tree..
216                 if (this.tree == null) {
217                         return;
218                 }
219                 // now write the js file..
220                 string js;
221                 try {
222                         Regex regex = new Regex("\\.(bjs|js)$");
223
224                         js = regex.replace(this.path,this.path.length , 0 , ".js");
225                 } catch (RegexError e) {
226                         this.name = "???";
227                         print("count not make filename from path");
228                         return;
229                 }
230
231
232                 //var d = new Date();
233                 var js_src = this.toSource();            
234                 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
235                 try {
236                         this.writeFile(js, js_src);            
237                 } catch (FileError e ) {
238                         print("Save failed\n");
239                 }
240                 // for bootstrap - we can write the HTML to the templates directory..
241                  
242             //var top = this.guessName(this.items[0]);
243             //print ("TOP = " + top)
244              
245             
246             
247             
248         }
249
250          
251
252          
253         public override void saveHTML ( string html )
254         {
255                  
256                 var top = this.tree.fqn();
257                 print ("TOP = " + top + "\n" );
258                 if (top.index_of("Roo.bootstrap.") < 0 &&
259                     top.index_of("Roo.mailer.") < 0
260                         ) {
261                         return;
262                 }
263                 
264                 
265 // now write the js file..
266                 string fn;
267                 try {
268                         Regex regex = new Regex("\\.(bjs|js)$");
269
270                         fn = regex.replace(this.path,this.path.length , 0 , ".html");
271                 } catch (RegexError e) {
272                         this.name = "???";
273                         print("count not make filename from path");
274                         return;
275                 }
276                 var bn = GLib.Path.get_basename(fn);
277                 var dn = GLib.Path.get_dirname(fn);
278
279                 var targetdir = dn + (
280                         top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
281                               
282                 
283                 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
284                         print("Skip save - templates folder does not exist : %s\n", targetdir);
285                         return;
286                 }
287                 print("SAVE HTML -- %s\n%s\n",targetdir + "/" +  bn, html);
288                 try {
289                         this.writeFile(targetdir + "/" +  bn , html);            
290                 } catch (FileError e ) {
291                         print("SaveHtml failed\n");
292                 }
293             
294             
295             
296         }
297
298         public Gee.ArrayList<string> findxincludes(Node node,   Gee.ArrayList<string> ret)
299         {
300                 
301                 if (node.props.has_key("* xinclude")) {
302                         ret.add(node.props.get("* xinclude"));
303                 }
304                 for (var i =0; i < node.items.size; i++) {
305                         this.findxincludes(node.items.get(i), ret);
306                 }
307                 return ret;
308                         
309         }
310         .
311
312          
313         public void  findTransStrings(Node node )
314         {
315                 // iterate properties...
316                 // use doubleStringProps
317                 
318                 // flagging a translatable string..
319                 // the code would use string _astring to indicate a translatable string
320                 // the to use it it would do String.format(this._message, somedata);
321                 
322                 // loop through and find string starting with '_' 
323                 if (node == null) {
324                         return;
325                 }               
326                 
327                 var iter = node.props.map_iterator();
328                 while (iter.next()) {
329                         // key formats : XXXX
330                         // XXX - plain
331                         // string XXX - with type
332                         // $ XXX - with flag (no type)
333                         // $ string XXX - with flag
334                         string kname;
335                         string ktype;
336                         string kflag;
337                         node.normalize_key(iter.get_key(), out kname, out ktype, out kflag);
338                         if (kflag == "$") {
339                                 continue;
340                         }
341                         var str = iter.get_value();
342                         if (this.doubleStringProps.index_of(kname) > -1) {
343                                 this.transStrings.set(str,  
344                                         GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
345                                 );
346                                 continue;
347                         }
348                         if (ktype == "string" && kname[0] == '_') {
349                                 this.transStrings.set(str,  
350                                         GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
351                                 );
352                                 continue;
353                         }
354                         
355                 }
356                  
357
358                 
359                 // iterate children..
360                 for (var i =0; i < node.items.size; i++) {
361                         this.findTransStrings(node.items.get(i) );
362                 }
363         
364                         
365         }    
366         /**
367          * javascript used in Webkit preview 
368          */
369         
370         public override string  toSourcePreview()
371         {
372                 print("to source preview\n");
373                 if (this.tree == null) {
374                         return "";
375                 }
376                 var top = this.tree.fqn();
377                 var xinc = new Gee.ArrayList<string>(); 
378
379                 this.findxincludes(this.tree, xinc);
380                 print("got %d xincludes\n", xinc.size);
381                 var prefix_data = "";
382                 if (xinc.size > 0 ) {
383                         for(var i = 0; i < xinc.size; i++) {
384                                 print("check xinclude:  %s\n", xinc.get(i));
385                                 var sf = this.project.getByName(xinc.get(i));
386                                 if (sf == null) {
387                                         print("Failed to find file by name?\n");
388                                         continue;
389                                 }
390
391                                 sf.loadItems();
392                                 var xinc_str = sf.toSource();
393                                 
394                                 //string xinc_str;
395                                 //FileUtils.get_contents(js, out xinc_str);
396                                 prefix_data += "\n" + xinc_str + "\n";
397                                 
398                         }
399
400                 }
401
402                 
403                 
404                 //print(JSON.stringify(this.items, null,4));
405                        
406                 if (top == null) {
407                         print ("guessname returned false");
408                         return "";
409                 }
410
411
412                 if (top.contains("Dialog")) {
413                         return prefix_data + this.toSourceDialog(true);
414                 }
415
416                 if (top.contains("Modal")) {
417                         return prefix_data + this.toSourceModal(true);
418                 }
419
420                 return prefix_data + this.toSourceLayout(true);
421             
422             
423             
424         }
425         
426         /**
427          * This needs to use some options on the project
428          * to determine how the file is output..
429          * 
430          * At present we are hard coding it..
431          * 
432          * 
433          */
434         public override string toSource()
435         {
436             // dump the file tree back out to a string.
437             
438             // we have 2 types = dialogs and components
439             // 
440             
441             
442                         if (this.tree == null) {
443                                 return "";
444                         }
445             var top = this.tree.fqn();
446             if (top == null) {
447                 return "";
448             }
449             // get the translatable strings..
450             
451             
452             
453             if (top.contains("Dialog")) {
454                 return this.toSourceDialog(false);
455             }
456             
457             if (top.contains("Modal")) {
458                 return this.toSourceModal(false);
459             }
460             return this.toSourceLayout(false);
461             
462             /*
463             eventually support 'classes??'
464              return this.toSourceStdClass();
465             */
466               
467         }
468        
469         public string outputHeader()
470         {
471                 string[] s = {
472                         "//<script type=\"text/javascript\">",
473                         "",
474                         "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
475                         ""
476                    
477                 };  
478                 var ret=  string.joinv("\n",s);
479                 var bits = this.name.split(".");
480                 if (bits.length > 1) {
481                         ret += "\nRoo.namespace(\'" + 
482                                 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
483                                 "');\n";
484                                 
485                 }
486                 /// genericlly used..
487                   
488                 return ret;
489             
490        
491         }
492         // a standard dialog module.
493         // fixme - this could be alot neater..
494         public string toSourceDialog(bool isPreview) 
495         {
496             
497             //var items = JSON.parse(JSON.stringify(this.items[0]));
498             
499             
500             var o = this.mungeToString("    ");   
501
502  
503             string[] adda = { " = {",
504                 "",
505                 " dialog : false,",
506                 " callback:  false,",
507                 "",   
508                 " show : function(data, cb)",
509                 " {",
510                 "  if (!this.dialog) {",
511                 "   this.create();",
512                 "  }",
513                 "",
514                 "  this.callback = cb;",
515                 "  this.data = data;",
516                 "  this.dialog.show(this.data._el);",
517                 "  if (this.form) {",
518                 "   this.form.reset();",
519                 "   this.form.setValues(data);",
520                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
521                 "  }",
522                 "",   
523                 " },",
524                 "",
525                 " create : function()",
526                 " {",
527                 "   var _this = this;",
528                 "   this.dialog = Roo.factory(" 
529             };
530             string[] addb = {  
531                    ");",
532                 " }",
533                 "};",
534                 ""
535             };
536             return  this.outputHeader() + "\n" +
537                 this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
538             
539              
540              
541              
542         }
543         
544         public string toSourceModal(bool isPreview) 
545         {
546             
547             
548             //var items = JSON.parse(JSON.stringify(this.items[0]));
549             var o = this.mungeToString("    ");   
550             
551             string[] adda = { " = {",
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   pathToPart()
593         {
594             var dir = Path.get_basename(Path.get_dirname(this.path));
595             var ar = dir.split(".");
596             var modname = ar[ar.length-1];
597             
598             // now we have the 'module name'..
599             var fbits = Path.get_basename(this.path).split(".");
600             
601              
602             var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
603             if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
604                 npart = npart.substring(modname.length);
605             }
606             return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
607             //return ret;
608             
609             
610             
611             
612         }
613         
614         // a layout compoent 
615         public string toSourceLayout(bool isPreview) 
616         {
617           
618             
619                 if (isPreview) {
620                         //       topItem.region = 'center';
621                         //    topItem.background = false;
622                 }
623             
624                 var o = this.mungeToString("   ");   
625                 var reg = new Regex("[^A-Za-z.]+");
626             
627                 string modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
628             
629                 string  parent =   (this.parent.length > 0 ?  "'" + this.parent + "'" :  "false");
630
631                 
632                 
633                 if (isPreview) {
634                         // set to false to ensure this is the top level..
635                         parent = "false";
636                         var topnode = this.tree.fqn();
637                         print("topnode = %s\n", topnode);
638                         if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
639                             topnode != "Roo.bootstrap.Body"
640                         ) {
641                                 parent = "\"#bootstrap-body\"";
642                         }
643                           
644                 }
645             
646           
647                 return 
648                         this.outputHeader() + "\n" +
649                         
650                         this.name  +  " = new Roo.XComponent({\n" +
651                         "  part     :  "+ this.pathToPart() + ",\n" +
652                                 /// critical used by builder to associate modules/parts/persm
653                         "  order    : '" +modkey+"',\n" +
654                         "  region   : '" + this.region   +"',\n" +
655                         "  parent   : "+ parent + ",\n" +
656                         "  name     : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
657                         "  disabled : " + (this.disabled ? "true" : "false") +", \n" +
658                         "  permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
659                             
660                        // "    tree : function() { return this._tree(); },\n" +   //BC
661                         "  _tree : function()\n" +
662                         "  {\n" +
663                         "   var _this = this;\n" + // bc
664                         "   var MODULE = this;\n" + /// this looks like a better name.
665                         "   return " + o + ";" +
666                         "  }\n" +
667                         "});\n";
668                          
669              
670             
671         }
672             
673         public new string? guessName (Node? ar) // turns the object into full name.
674         {
675              // eg. xns: Roo, xtype: XXX -> Roo.xxx
676             if (ar == null) {
677                 return null;
678             }
679             
680             string[] ret = {} ;
681             ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
682              
683             
684             if ( ar.get("xtype").length < 1) {
685                 return null;
686             }
687                     
688             var xtype = ar.get("xtype");
689
690             if (xtype[0] == '*') { // prefixes????
691                 xtype  = xtype.substring(1);
692             }
693             if (! Regex.match_simple("^Roo", xtype)) {
694                 
695                 // already starts with roo...
696                 ret = {};
697             }
698             ret += xtype;
699             var str =  string.joinv(".", ret);
700             
701             return str;
702            // 
703             //Palete.Palete.factory("Roo").guessName(str);
704             
705                             
706                                  
707         }
708         
709         string getHelpUrl(string cls)
710         {
711             return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";
712         }
713                  
714      
715     }
716 }