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