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