src/JsRender/NodeToJs.vala
[app.Builder.js] / src / JsRender / NodeToJs.vala
1 /**
2  * 
3  * Code to convert node tree to Javascript...
4  * 
5  * usage : x = (new JsRender.NodeToJs(node)).munge();
6  * 
7  *
8  *  We are changing this to output as we go.
9  *   However... since line-endings on properties have ',' (not ;) like vala.
10  *           we have to be a bit smarter about how to output.
11  *
12  *   
13  *
14 */
15
16
17
18
19 public class JsRender.NodeToJs : Object {
20
21         static uint indent = 1;
22         static string indent_str = " ";
23         
24         
25         
26         Node node;
27         Gee.ArrayList<string>  doubleStringProps;  // need to think if this is a good idea like this
28         string pad;
29         public JsRender renderer;
30           
31         Gee.HashMap<string,string> out_props;
32         Gee.HashMap<string,string> out_listeners;       
33         Gee.HashMap<string,Node> out_nodeprops;
34         Gee.ArrayList<Node> out_children;
35         Gee.HashMap<string,Gee.ArrayList<Node>> out_props_array;
36         Gee.HashMap<string,Gee.ArrayList<string>> out_props_array_plain;        
37         
38         NodeToJs top;
39         public string ret;
40         
41         public int cur_line;
42
43         
44         public NodeToJs( Node node, Gee.ArrayList<string> doubleStringProps, string pad, NodeToJs? parent) 
45         {
46                 this.node = node;
47                 this.doubleStringProps = doubleStringProps;
48                 this.pad = pad;
49                 
50                 //this.els = new Gee.ArrayList<string>(); 
51                 //this.ar_props = new Gee.HashMap<string,string>();
52                 
53                 
54                 
55                 // this is the bit that causes issues - we have to output as we go, otherwise we 
56                 // can not work out which line is which...
57                 
58                 this.out_props = new Gee.HashMap<string,string>();
59                 this.out_listeners = new Gee.HashMap<string,string>();  
60                 
61                 
62                 this.out_nodeprops = new Gee.HashMap<string,Node>() ;
63                 this.out_children = new Gee.ArrayList<Node> ();
64                 
65                 this.out_props_array = new Gee.HashMap<string,Gee.ArrayList<Node>>(); // filled in by 'checkChildren'
66                 this.out_props_array_plain = new Gee.HashMap<string,Gee.ArrayList<string>>() ;
67         
68                 
69                 
70                 this.cur_line = parent == null ? 0 : parent.cur_line  ; //-1 as we usuall concat onto the existin gline?
71                 if (parent != null) {
72                         this.renderer = parent.renderer;
73                 }
74                 this.ret = "";
75                 this.top = parent == null ? this : parent.top;
76                 // reset the maps...
77                 if (parent == null) {
78                         node.node_lines = new Gee.ArrayList<int>();
79                         node.node_lines_map = new Gee.HashMap<int,Node>();
80                  }
81         }
82         
83         
84         
85         
86         
87         
88         public string munge ( )
89         {
90                 //return this.mungeToString(this.node);
91
92                 
93                 this.checkChildren();
94                 this.readProps();
95                 //this.readArrayProps();
96                 this.readListeners();
97
98                 if (!this.node.props.has_key("* xinclude")) {
99                         this.iterChildren();
100                 }
101                 
102                 
103                 
104                 // no properties to output...
105                 //if (this.els.size < 1) {
106                 //      return "";
107                 //}
108
109                 this.mungeOut();
110                 return this.ret;
111                  
112         } 
113                 /**
114         
115         This currently works by creating a key/value array of this.els, which is just an array of properties..
116         this is so that join() works...
117         
118         how this could work:
119         a) output header
120         b) output plan properties.
121         c) output listeners..
122         c) output *prop
123         g) output prop_arrays..
124         d) output children
125         e) 
126         
127         
128         
129         */
130         
131         public Gee.ArrayList<string> orderedPropKeys() {
132         
133                 var ret = new Gee.ArrayList<string> ();
134                 var niter = this.out_props.map_iterator();
135                 while(niter.next()) {
136                         ret.add(niter.get_key());
137                 }
138                 
139                 ret.sort((  a,  b) => {
140                         return ((string)a).collate((string)b);
141                         //if (a == b) return 0;
142                         //return a < b ? -1 : 1;
143                 });
144                 return ret;
145         }
146         public Gee.ArrayList<string> orderedListenerKeys() {
147         
148                 var ret = new Gee.ArrayList<string> ();
149                 var niter = this.out_listeners.map_iterator();
150                 while(niter.next()) {
151                         ret.add(niter.get_key());
152                 }
153                 
154                 ret.sort((  a,  b) => {
155                         return ((string)a).collate((string)b);
156                         //if (a == b) return 0;
157                         //return a < b ? -1 : 1;
158                 });
159                 return ret;
160         }
161         
162
163         public string mungeOut()
164         {
165                 this.node.line_start = this.cur_line;
166                 this.top.node.setNodeLine(this.cur_line, this.node);
167                 var spad = this.pad.substring(0, this.pad.length-indent);
168                 
169                 if (this.node.props.has_key("* xinclude")) {
170                         this.addLine("Roo.apply(" + this.node.props.get("* xinclude") + "._tree(), {",0 );
171          
172                 } else {
173                         this.addLine("{", 0);
174                 }
175                 var suffix = "";
176                 // output the items...
177                 // work out remaining items...
178          
179                 // output xns / xtype first..
180                 if (this.out_props.has_key("xtype")) {
181                         var v = this.out_props.get("xtype");
182                         this.node.setLine(this.cur_line, "p","xtype"); 
183                         this.addLine(this.pad + "xtype" + " : " + v + suffix, ',');
184                 }
185                 
186                 // plain properties.
187                 var iter = this.orderedPropKeys().list_iterator();
188                 while(iter.next()) {
189  
190                          
191                         var k = iter.get();
192                         if (k == "xns" || k == "xtype") {
193                                 continue;
194                         }
195
196                         var v = this.out_props.get(k);
197                         this.node.setLine(this.cur_line, "p",k); 
198                         this.addLine(this.pad + k + " : " + v + suffix, ',');
199                          
200                         this.node.setLine(this.cur_line, "e", "");
201                         
202                 }
203          
204                 // listeners..
205                 
206                 if (this.out_listeners.size > 0 ) { 
207                          
208                         this.addLine(this.pad + "listeners : {", 0);
209                         iter = this.orderedListenerKeys().list_iterator();
210                          
211                         while(iter.next()) {
212                                 
213                                 var k = iter.get();
214                                 var v = this.out_listeners.get(k);
215                                 this.node.setLine(this.cur_line, "l",k); //listener
216                                 this.addLine(this.pad + indent_str + k + " : " + v , ',');
217                                 this.node.setLine(this.cur_line, "e", "");
218                         }
219                         
220                         this.closeLine();
221                         this.addLine(this.pad + "}" ,',');
222                         
223                 }
224                 
225                 //------- at this point it is the end of the code relating directly to the object..
226                 
227                 if (this.out_props.has_key("xns")) {
228                         var v = this.out_props.get("xns");
229                         this.node.setLine(this.cur_line, "p","xns"); 
230                         this.addLine(this.pad + "xns" + " : " + v + suffix, ',');
231                         this.node.setLine(this.cur_line, "p","| xns"); 
232                         this.addLine(this.pad + "'|xns' : '" + v + "'", ',');
233                 }
234                 
235                 this.node.line_end = this.cur_line;
236                 
237                 // * prop
238
239                 var niter = this.out_nodeprops.map_iterator();
240
241                 while(niter.next()) {
242                         var addstr = this.mungeChildNew(this.pad + indent_str, niter.get_value());
243                         this.node.setLine(this.cur_line, "p",niter.get_key());
244                         this.addLine(this.pad + niter.get_key() + " : " + addstr, ',');
245                         
246                         this.node.setLine(this.cur_line, "e", "");
247                 }                        
248                 // prop arrays...
249                 
250                 var piter = this.out_props_array.map_iterator();
251
252                 while(piter.next()) {
253                         this.node.setLine(this.cur_line, "p",niter.get_key());
254                         this.addLine(this.pad + piter.get_key() + " : [", 0);
255                         
256                         var pliter = piter.get_value().list_iterator();
257                         while (pliter.next()) {
258                                 var addstr = this.mungeChildNew(this.pad + indent_str  + indent_str, pliter.get());
259                                 this.addLine(this.pad + indent_str + addstr, ',');
260                                 this.node.setLine(this.cur_line, "e", "");
261                         }
262                         this.closeLine();
263                         this.addLine(this.pad + "]" , ',');                     
264                 }       
265                 
266                 // children..
267                 if (this.out_children.size > 0) {
268                         this.addLine(this.pad + "items  : [" , 0);
269                         var cniter = this.out_children.list_iterator();
270                         while (cniter.next()) {
271                                 suffix = cniter.has_next()  ? "," : "";
272                                 var addstr = this.mungeChildNew(this.pad + indent_str  + indent_str, cniter.get());
273                                 this.addLine(this.pad + indent_str + addstr, ',');
274                                 this.node.setLine(this.cur_line, "e", "");
275                                 
276                         }
277                         this.closeLine();
278                         this.addLine(this.pad +   "]",',');
279                 }
280                 this.node.setLine(this.cur_line, "e", "");
281                 this.closeLine();
282                 if (this.node.props.has_key("* xinclude")) {
283                         this.addLine(spad + "})",0);
284          
285                 } else {
286                         this.addLine( spad + "}", 0);
287                 }
288                 
289                 this.node.sortLines();
290                 
291                 
292                 
293                 return this.ret;
294         
295         }
296         
297         /**
298         * Line endings
299         *     if we end with a ','
300         *
301         */
302
303         char last_line_end = '!'; 
304         
305         /**
306         * add a line - note we will end up with an extra line break 
307         *     at beginning of nodes doing this..
308         *
309         * @param str = text to add..
310         * @param line_end = 0  (just add a line break)
311         *        line_end = ','  and ","
312         *  
313         */
314         public void addLine(string str, char line_end)
315         {
316                 if (this.last_line_end != '!') {
317                         this.ret += (this.last_line_end == 0 ? "" : this.last_line_end.to_string()) + "\n"; 
318                 }
319                 this.last_line_end = line_end;
320                 this.cur_line += str.split("\n").length;
321                 this.ret += str;
322                 
323                 
324                 //this.ret +=  "/*%d(%d-%d)*/ ".printf(this.cur_line -1, this.node.line_start,this.node.line_end) + str + "\n";
325                 
326                 
327         }
328         public void closeLine() // send this before '}' or ']' to block output of ',' ...
329         {
330                 this.last_line_end = 0;
331         }
332         
333 /*      public void addMultiLine(str= "")
334         {
335                 
336                 //this.ret +=   "/ * %d(%d-%d) * / ".printf(this.cur_line, this.node.line_start,this.node.line_end)+ str + "\n";
337                 this.ret +=   str + "\n";
338                 this.cur_line += str.split("\n").length;
339         }
340  */
341         public string mungeChildNew(string pad ,  Node cnode )
342         {
343                 var x = new  NodeToJs(cnode, this.doubleStringProps, pad, this);
344          
345                 x.munge();
346                 return x.ret;
347         }
348         
349         /**
350         * loop through items[] array see if any of the children have '* prop'
351         * -- which means they are a property of this node.
352         * -- ADD TO : this.opt_props_array  
353         *
354         */
355         
356         public void checkChildren () 
357         {
358                 
359                  
360                 // look throught he chilren == looking for * prop.. -- fixme might not work..
361                 
362                 
363                 if (!this.node.hasChildren()) {
364                         return;
365                 }
366                 // look for '*props'
367            
368                 for (var ii =0; ii< this.node.items.size; ii++) {
369                         var pl = this.node.items.get(ii);
370                         if (!pl.props.has_key("* prop")) {
371                                 //newitems.add(pl);
372                                 continue;
373                         }
374                         
375                         //print(JSON.stringify(pl,null,4));
376                         // we have a prop...
377                         //var prop = pl['*prop'] + '';
378                         //delete pl['*prop'];
379                         var prop = pl.get("* prop");
380                         //print("got prop "+ prop + "\n");
381                         
382                         // name ends in [];
383                         if (! Regex.match_simple("\\[\\]$", prop)) {
384                                 // it's a standard prop..
385                                 
386                                 // munge property..??
387                                 
388                                 this.out_nodeprops.set(prop, pl);
389                                  
390                                 continue;
391                         }
392
393
394
395                         
396                         var sprop  = prop.replace("[]", "");
397                         //print("sprop is : " + sprop + "\n");
398                         
399                         // it's an array type..
400                         //var old = "";
401                         if (!this.out_props_array.has_key(sprop)) {
402                                 this.out_props_array.set(sprop, new Gee.ArrayList<Node>());
403                         }
404                         
405                          
406                         this.out_props_array.get(sprop).add( pl);
407                         //this.ar_props.set(sprop, nstr);
408                          
409                         
410                 }
411                  
412         }
413         /*
414  * Standardize this crap...
415  * 
416  * standard properties (use to set)
417  *          If they are long values show the dialog..
418  *
419  * someprop : ....
420  * bool is_xxx  :: can show a pulldown.. (true/false)
421  * string html  
422  * $ string html  = string with value interpolated eg. baseURL + ".." 
423  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
424  * $ untypedvalue = javascript untyped value...  
425  * _ string html ... = translatable..
426
427  * 
428  * object properties (not part of the GOjbect being wrapped?
429  * # Gee.ArrayList<Xcls_fileitem> fileitems
430  * 
431  * signals
432  * @ void open 
433  * 
434  * methods -- always text editor..
435  * | void clearFiles
436  * | someJSmethod
437  * 
438  * specials
439  * * prop -- string
440  * * args  -- string
441  * * ctor -- string
442  * * init -- big string?
443  * 
444  * event handlers (listeners)
445  *   just shown 
446  * 
447  * -----------------
448  * special ID values
449  *  +XXXX -- indicates it's a instance property / not glob...
450  *  *XXXX -- skip writing glob property (used as classes that can be created...)
451  * 
452  * 
453  */
454         public void readProps()
455         {
456                 string left;
457                 Regex func_regex ;
458  
459                 try {
460                         func_regex = new Regex("^\\s+|\\s+$");
461                 } catch (RegexError e) {
462                         print("failed to build regex");
463                         return;
464                 }
465                 // sort the key's so they always get rendered in the same order..
466                 
467                 var keys = new Gee.ArrayList<string>();
468                 var piter = this.node.props.map_iterator();
469                 while (piter.next() ) {
470                         string k;
471                         string ktype;
472                         string kflag;
473                         this.node.normalize_key(piter.get_key(), out k, out kflag, out ktype);
474                         
475                         keys.add(k);
476                 }
477                 
478                 keys.sort((  a,  b) => {
479                         return ((string)a).collate((string)b);
480                         //if (a == b) return 0;
481                         //return a < b ? -1 : 1;
482                 });
483                 
484                 var has_cms = this.node.has("cms-id");
485                 
486                 for (var i = 0; i< keys.size; i++) {
487                         var key = this.node.get_key(keys.get(i));
488                         //("ADD KEY %s\n", key);
489                         string k;
490                         string ktype;
491                         string kflag;
492                         
493                         this.node.normalize_key(key, out k, out kflag, out ktype);
494                         
495                         
496                         var v = this.node.get(key);
497                          
498                         
499                         //if (this.skip.contains(k) ) {
500                         //      continue;
501                         //}
502                         if (  Regex.match_simple("\\[\\]$", k)) {
503                                 // array .. not supported... here?
504                                 
505
506                         }
507                         
508                         string leftv = k;
509                         // skip builder stuff. prefixed with  '.' .. just like unix fs..
510                         if (kflag == ".") { // |. or . -- do not output..
511                                 continue;
512                         }
513                         if (kflag == "*") {
514                                 // ignore '* prop'; ??? 
515                                 continue;
516                         }
517                         
518                         // handle cms-id // html
519                         if (has_cms && k == "cms-id") {
520                                 continue; // ignore it...
521                         }
522                         // html must not be a dynamic property...
523                         // note - we do not translate this either...
524                         if (has_cms && k == "html" && kflag != "$") {
525                                  
526
527                                 this.out_props.set("html", "Pman.Cms.content(" + 
528                                         this.node.quoteString(this.renderer.name + "::" + this.node.get("cms-id")) +
529                                          ", " +
530                                         this.node.quoteString(v) +
531                                          ")");
532                                          
533                                 continue;        
534                         }
535                         
536                         
537                                 
538                         
539                         if (Lang.isKeyword(leftv) || Lang.isBuiltin(leftv)) {
540                                 left = "'" + leftv + "'";
541                         } else if (Regex.match_simple("[^A-Za-z_]+",leftv)) { // not plain a-z... - quoted.
542                                 var val = this.node.quoteString(leftv);
543                                 
544                                 left = "'" + val.substring(1, val.length-2).replace("'", "\\'") + "'";
545                         } else {
546                                 left = leftv;
547                         }
548                          
549                          
550                         // next.. is it a function.. or a raw string..
551                         if (
552                                 kflag == "|" 
553                                 || 
554                                 kflag == "$" 
555                                 || 
556                                 ktype == "function"
557                                
558                                 // ??? any others that are raw output..
559                                 ) {
560                                 // does not hapepnd with arrays.. 
561                                 if (v.length < 1) {  //if (typeof(el) == 'string' && !obj[i].length) { //skip empty.
562                                         continue;
563                                 }
564                                 /*
565                                 print(v);
566                                 string str = "";
567                                 try {
568                                         str = func_regex.replace(v,v.length, 0, "");
569                                 } catch(Error e) {
570                                         print("regex failed");
571                                         return "";
572                                 }
573                                 */
574                                 var str = v.strip();
575                                   
576                                 var lines = str.split("\n");
577                                 var nstr = "" + str;
578                                 if (lines.length > 0) {
579                                         nstr =  string.joinv("\n" + this.pad, lines);
580                                         //nstr =  string.joinv("\n", lines);
581                                 }
582                                 this.out_props.set(left, nstr);
583                                 
584                                 
585
586                                 
587                                 
588                                 //print("==> " +  str + "\n");
589                                 //this.els.add(left + " : "+  nstr);
590                                 continue;
591                         }
592                         // standard..
593                         
594                         
595                         if (
596                                 Lang.isNumber(v) 
597                                 || 
598                                 Lang.isBoolean(v)
599                                 ||
600                                 ktype.down() == "boolean"
601                                 || 
602                                 ktype.down() == "bool"
603                                 || 
604                                 ktype.down() == "number"
605                                 || 
606                                 ktype.down() == "int"
607                             ) { // boolean or number...?
608                             this.out_props.set(left, v.down());
609                                 //this.els.add(left + " : " + v.down() );
610                                 continue;
611                         }
612                         
613                         // is it a translated string?
614                         
615                         
616                         
617                         
618                         // strings..
619                         //if (this.doubleStringProps.size < 1) {
620                         //      this.els.add(left + this.node.quoteString(v));
621                         //      continue;
622                         //}
623                    
624                         if ((this.doubleStringProps.index_of(k) > -1) || 
625                                 (ktype.down() == "string" && k[0] == '_')
626                         
627                         ) {
628                                 // then use the translated version...
629                                 
630                                 var com = " /* " + 
631                                         (v.split("\n").length > 1 ?
632                                                 ("\n" + this.pad +  string.joinv(this.pad +  "\n", v.split("\n")).replace("*/", "* - /") + "\n" + this.pad + "*/ ") :
633                                                 (v.replace("*/", "* - /") + " */")
634                                         );
635                                 
636                                 //this.els.add(left + " : _this._strings['" + 
637                                 //      GLib.Checksum.compute_for_string (ChecksumType.MD5, v) +
638                                 //      "']"
639                                 //);
640                                 this.out_props.set(left, "_this._strings['" + 
641                                         GLib.Checksum.compute_for_string (ChecksumType.MD5, v.strip()) +
642                                         "']" + com);
643                                 continue;
644                         }
645                  
646                         // otherwise it needs to be encapsulated.. as single quotes..
647                         
648                         var vv = this.node.quoteString(v);
649                         // single quote.. v.substring(1, v.length-1).replace("'", "\\'") + "'";
650                         //this.els.add(left + " : " +  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
651                         this.out_props.set(left,  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
652
653                    
654                    
655                    
656                 }
657         }
658          
659         public void readListeners()
660         {
661                 
662                 if (this.node.listeners.size < 1) {
663                         return;
664                 }
665                 // munge the listeners.
666                 //print("ADDING listeners?");
667         
668  
669         
670         
671                 var keys = new Gee.ArrayList<string>();
672                 var piter = this.node.listeners.map_iterator();
673                 while (piter.next() ) {
674                          
675                         keys.add(piter.get_key());
676                 }
677                 keys.sort((  a,  b) => {
678                         return ((string)a).collate((string)b);
679                         //if (a == b) return 0;
680                         //return a < b ? -1 : 1;
681                 });
682         
683                  
684                 for (var i = 0; i< keys.size; i++) {
685                         var key = keys.get(i);
686                         var val = this.node.listeners.get(key);
687                 
688         
689                          // 
690                         var str = val.strip();
691                         var lines = str.split("\n");
692                         if (lines.length > 0) {
693                                 //str = string.joinv("\n" + this.pad + "           ", lines);
694                                 str = string.joinv("\n" + this.pad + indent_str + indent_str , lines);
695                         }
696                          
697                         this.out_listeners.set(key.replace("|", "") ,str);
698                 
699                         
700                 }
701                  
702                  
703
704         }
705
706         public void iterChildren()
707         {
708                 
709                 
710                 // finally munge the children...
711                 if (this.node.items.size < 1) {
712                         return;
713                 }
714                 var itms = "items : [\n";
715                 //var n = 0;
716                 for(var i = 0; i < this.node.items.size;i++) {
717                         var ele = this.node.items.get(i);
718                         if (ele.props.has_key("* prop")) {
719                                 continue;
720                         }
721                          
722                         this.out_children.add(ele);
723                         
724                 }
725                 itms +=  "\n"+  this.pad + "]"  + "\n";
726                 //this.els.add(itms);
727         }
728
729                 // finally output listeners...
730                 
731         public void xIncludeToString()
732         {
733                 
734
735         }
736
737 }
738         
739          
740         
741