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" || x == "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                         this.node.setLine(this.cur_line, "p","| xns" ); 
200                         
201                         this.node.setLine(this.cur_line, "e", "");
202                         
203                 }
204          
205                 // listeners..
206                 
207                 if (this.out_listeners.size > 0 ) { 
208                          
209                         this.addLine(this.pad + "listeners : {", 0);
210                         iter = this.orderedListenerKeys().list_iterator();
211                          
212                         while(iter.next()) {
213                                 
214                                 var k = iter.get();
215                                 var v = this.out_listeners.get(k);
216                                 this.node.setLine(this.cur_line, "l",k); //listener
217                                 this.addLine(this.pad + indent_str + k + " : " + v , ',');
218                                 this.node.setLine(this.cur_line, "e", "");
219                         }
220                         
221                         this.closeLine();
222                         this.addLine(this.pad + "}" ,',');
223                         
224                 }
225                 
226                 //------- at this point it is the end of the code relating directly to the object..
227                 
228                 if (this.out_props.has_key("xns")) {
229                         var v = this.out_props.get("xns");
230                         this.node.setLine(this.cur_line, "p","xns"); 
231                         this.addLine(this.pad + "xns" + " : " + v + suffix, ',');
232                         this.node.setLine(this.cur_line, "p","| xns"); 
233                         this.addLine(this.pad + "'|xns' : '" + v + "'", ',');
234                 }
235                 
236                 this.node.line_end = this.cur_line;
237                 
238                 // * prop
239
240                 var niter = this.out_nodeprops.map_iterator();
241
242                 while(niter.next()) {
243                         var addstr = this.mungeChildNew(this.pad + indent_str, niter.get_value());
244                         this.node.setLine(this.cur_line, "p",niter.get_key());
245                         this.addLine(this.pad + niter.get_key() + " : " + addstr, ',');
246                         
247                         this.node.setLine(this.cur_line, "e", "");
248                 }                        
249                 // prop arrays...
250                 
251                 var piter = this.out_props_array.map_iterator();
252
253                 while(piter.next()) {
254                         this.node.setLine(this.cur_line, "p",niter.get_key());
255                         this.addLine(this.pad + piter.get_key() + " : [", 0);
256                         
257                         var pliter = piter.get_value().list_iterator();
258                         while (pliter.next()) {
259                                 var addstr = this.mungeChildNew(this.pad + indent_str  + indent_str, pliter.get());
260                                 this.addLine(this.pad + indent_str + addstr, ',');
261                                 this.node.setLine(this.cur_line, "e", "");
262                         }
263                         this.closeLine();
264                         this.addLine(this.pad + "]" , ',');                     
265                 }       
266                 
267                 // children..
268                 if (this.out_children.size > 0) {
269                         this.addLine(this.pad + "items  : [" , 0);
270                         var cniter = this.out_children.list_iterator();
271                         while (cniter.next()) {
272                                 suffix = cniter.has_next()  ? "," : "";
273                                 var addstr = this.mungeChildNew(this.pad + indent_str  + indent_str, cniter.get());
274                                 this.addLine(this.pad + indent_str + addstr, ',');
275                                 this.node.setLine(this.cur_line, "e", "");
276                                 
277                         }
278                         this.closeLine();
279                         this.addLine(this.pad +   "]",',');
280                 }
281                 this.node.setLine(this.cur_line, "e", "");
282                 this.closeLine();
283                 if (this.node.props.has_key("* xinclude")) {
284                         this.addLine(spad + "})",0);
285          
286                 } else {
287                         this.addLine( spad + "}", 0);
288                 }
289                 
290                 this.node.sortLines();
291                 
292                 
293                 
294                 return this.ret;
295         
296         }
297         
298         /**
299         * Line endings
300         *     if we end with a ','
301         *
302         */
303
304         char last_line_end = '!'; 
305         
306         /**
307         * add a line - note we will end up with an extra line break 
308         *     at beginning of nodes doing this..
309         *
310         * @param str = text to add..
311         * @param line_end = 0  (just add a line break)
312         *        line_end = ','  and ","
313         *  
314         */
315         public void addLine(string str, char line_end)
316         {
317                 if (this.last_line_end != '!') {
318                         this.ret += (this.last_line_end == 0 ? "" : this.last_line_end.to_string()) + "\n"; 
319                 }
320                 this.last_line_end = line_end;
321                 this.cur_line += str.split("\n").length;
322                 this.ret += str;
323                 
324                 
325                 //this.ret +=  "/*%d(%d-%d)*/ ".printf(this.cur_line -1, this.node.line_start,this.node.line_end) + str + "\n";
326                 
327                 
328         }
329         public void closeLine() // send this before '}' or ']' to block output of ',' ...
330         {
331                 this.last_line_end = 0;
332         }
333         
334 /*      public void addMultiLine(str= "")
335         {
336                 
337                 //this.ret +=   "/ * %d(%d-%d) * / ".printf(this.cur_line, this.node.line_start,this.node.line_end)+ str + "\n";
338                 this.ret +=   str + "\n";
339                 this.cur_line += str.split("\n").length;
340         }
341  */
342         public string mungeChildNew(string pad ,  Node cnode )
343         {
344                 var x = new  NodeToJs(cnode, this.doubleStringProps, pad, this);
345          
346                 x.munge();
347                 return x.ret;
348         }
349         
350         /**
351         * loop through items[] array see if any of the children have '* prop'
352         * -- which means they are a property of this node.
353         * -- ADD TO : this.opt_props_array  
354         *
355         */
356         
357         public void checkChildren () 
358         {
359                 
360                  
361                 // look throught he chilren == looking for * prop.. -- fixme might not work..
362                 
363                 
364                 if (!this.node.hasChildren()) {
365                         return;
366                 }
367                 // look for '*props'
368            
369                 for (var ii =0; ii< this.node.items.size; ii++) {
370                         var pl = this.node.items.get(ii);
371                         if (!pl.props.has_key("* prop")) {
372                                 //newitems.add(pl);
373                                 continue;
374                         }
375                         
376                         //print(JSON.stringify(pl,null,4));
377                         // we have a prop...
378                         //var prop = pl['*prop'] + '';
379                         //delete pl['*prop'];
380                         var prop = pl.get("* prop");
381                         //print("got prop "+ prop + "\n");
382                         
383                         // name ends in [];
384                         if (! Regex.match_simple("\\[\\]$", prop)) {
385                                 // it's a standard prop..
386                                 
387                                 // munge property..??
388                                 
389                                 this.out_nodeprops.set(prop, pl);
390                                  
391                                 continue;
392                         }
393
394
395
396                         
397                         var sprop  = prop.replace("[]", "");
398                         //print("sprop is : " + sprop + "\n");
399                         
400                         // it's an array type..
401                         //var old = "";
402                         if (!this.out_props_array.has_key(sprop)) {
403                                 this.out_props_array.set(sprop, new Gee.ArrayList<Node>());
404                         }
405                         
406                          
407                         this.out_props_array.get(sprop).add( pl);
408                         //this.ar_props.set(sprop, nstr);
409                          
410                         
411                 }
412                  
413         }
414         /*
415  * Standardize this crap...
416  * 
417  * standard properties (use to set)
418  *          If they are long values show the dialog..
419  *
420  * someprop : ....
421  * bool is_xxx  :: can show a pulldown.. (true/false)
422  * string html  
423  * $ string html  = string with value interpolated eg. baseURL + ".." 
424  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
425  * $ untypedvalue = javascript untyped value...  
426  * _ string html ... = translatable..
427
428  * 
429  * object properties (not part of the GOjbect being wrapped?
430  * # Gee.ArrayList<Xcls_fileitem> fileitems
431  * 
432  * signals
433  * @ void open 
434  * 
435  * methods -- always text editor..
436  * | void clearFiles
437  * | someJSmethod
438  * 
439  * specials
440  * * prop -- string
441  * * args  -- string
442  * * ctor -- string
443  * * init -- big string?
444  * 
445  * event handlers (listeners)
446  *   just shown 
447  * 
448  * -----------------
449  * special ID values
450  *  +XXXX -- indicates it's a instance property / not glob...
451  *  *XXXX -- skip writing glob property (used as classes that can be created...)
452  * 
453  * 
454  */
455         public void readProps()
456         {
457                 string left;
458                 Regex func_regex ;
459  
460                 try {
461                         func_regex = new Regex("^\\s+|\\s+$");
462                 } catch (RegexError e) {
463                         print("failed to build regex");
464                         return;
465                 }
466                 // sort the key's so they always get rendered in the same order..
467                 
468                 var keys = new Gee.ArrayList<string>();
469                 var piter = this.node.props.map_iterator();
470                 while (piter.next() ) {
471                         string k;
472                         string ktype;
473                         string kflag;
474                         this.node.normalize_key(piter.get_key(), out k, out kflag, out ktype);
475                         
476                         keys.add(k);
477                 }
478                 
479                 keys.sort((  a,  b) => {
480                         return ((string)a).collate((string)b);
481                         //if (a == b) return 0;
482                         //return a < b ? -1 : 1;
483                 });
484                 
485                 var has_cms = this.node.has("cms-id");
486                 
487                 for (var i = 0; i< keys.size; i++) {
488                         var key = this.node.get_key(keys.get(i));
489                         //("ADD KEY %s\n", key);
490                         string k;
491                         string ktype;
492                         string kflag;
493                         
494                         this.node.normalize_key(key, out k, out kflag, out ktype);
495                         
496                         
497                         var v = this.node.get(key);
498                          
499                         
500                         //if (this.skip.contains(k) ) {
501                         //      continue;
502                         //}
503                         if (  Regex.match_simple("\\[\\]$", k)) {
504                                 // array .. not supported... here?
505                                 
506
507                         }
508                         
509                         string leftv = k;
510                         // skip builder stuff. prefixed with  '.' .. just like unix fs..
511                         if (kflag == ".") { // |. or . -- do not output..
512                                 continue;
513                         }
514                         if (kflag == "*") {
515                                 // ignore '* prop'; ??? 
516                                 continue;
517                         }
518                         
519                         // handle cms-id // html
520                         if (has_cms && k == "cms-id") {
521                                 continue; // ignore it...
522                         }
523                         // html must not be a dynamic property...
524                         // note - we do not translate this either...
525                         if (has_cms && k == "html" && kflag != "$") {
526                                  
527
528                                 this.out_props.set("html", "Pman.Cms.content(" + 
529                                         this.node.quoteString(this.renderer.name + "::" + this.node.get("cms-id")) +
530                                          ", " +
531                                         this.node.quoteString(v) +
532                                          ")");
533                                          
534                                 continue;        
535                         }
536                         
537                         
538                                 
539                         
540                         if (Lang.isKeyword(leftv) || Lang.isBuiltin(leftv)) {
541                                 left = "'" + leftv + "'";
542                         } else if (Regex.match_simple("[^A-Za-z_]+",leftv)) { // not plain a-z... - quoted.
543                                 var val = this.node.quoteString(leftv);
544                                 
545                                 left = "'" + val.substring(1, val.length-2).replace("'", "\\'") + "'";
546                         } else {
547                                 left = leftv;
548                         }
549                          
550                          
551                         // next.. is it a function.. or a raw string..
552                         if (
553                                 kflag == "|" 
554                                 || 
555                                 kflag == "$" 
556                                 || 
557                                 ktype == "function"
558                                
559                                 // ??? any others that are raw output..
560                                 ) {
561                                 // does not hapepnd with arrays.. 
562                                 if (v.length < 1) {  //if (typeof(el) == 'string' && !obj[i].length) { //skip empty.
563                                         continue;
564                                 }
565                                 /*
566                                 print(v);
567                                 string str = "";
568                                 try {
569                                         str = func_regex.replace(v,v.length, 0, "");
570                                 } catch(Error e) {
571                                         print("regex failed");
572                                         return "";
573                                 }
574                                 */
575                                 var str = v.strip();
576                                   
577                                 var lines = str.split("\n");
578                                 var nstr = "" + str;
579                                 if (lines.length > 0) {
580                                         nstr =  string.joinv("\n" + this.pad, lines);
581                                         //nstr =  string.joinv("\n", lines);
582                                 }
583                                 this.out_props.set(left, nstr);
584                                 
585                                 
586
587                                 
588                                 
589                                 //print("==> " +  str + "\n");
590                                 //this.els.add(left + " : "+  nstr);
591                                 continue;
592                         }
593                         // standard..
594                         
595                         
596                         if (
597                                 Lang.isNumber(v) 
598                                 || 
599                                 Lang.isBoolean(v)
600                                 ||
601                                 ktype.down() == "boolean"
602                                 || 
603                                 ktype.down() == "bool"
604                                 || 
605                                 ktype.down() == "number"
606                                 || 
607                                 ktype.down() == "int"
608                             ) { // boolean or number...?
609                             this.out_props.set(left, v.down());
610                                 //this.els.add(left + " : " + v.down() );
611                                 continue;
612                         }
613                         
614                         // is it a translated string?
615                         
616                         
617                         
618                         
619                         // strings..
620                         //if (this.doubleStringProps.size < 1) {
621                         //      this.els.add(left + this.node.quoteString(v));
622                         //      continue;
623                         //}
624                    
625                         if ((this.doubleStringProps.index_of(k) > -1) || 
626                                 (ktype.down() == "string" && k[0] == '_')
627                         
628                         ) {
629                                 // then use the translated version...
630                                 
631                                 var com = " /* " + 
632                                         (v.split("\n").length > 1 ?
633                                                 ("\n" + this.pad +  string.joinv(this.pad +  "\n", v.split("\n")).replace("*/", "* - /") + "\n" + this.pad + "*/ ") :
634                                                 (v.replace("*/", "* - /") + " */")
635                                         );
636                                 
637                                 //this.els.add(left + " : _this._strings['" + 
638                                 //      GLib.Checksum.compute_for_string (ChecksumType.MD5, v) +
639                                 //      "']"
640                                 //);
641                                 this.out_props.set(left, "_this._strings['" + 
642                                         GLib.Checksum.compute_for_string (ChecksumType.MD5, v.strip()) +
643                                         "']" + com);
644                                 continue;
645                         }
646                  
647                         // otherwise it needs to be encapsulated.. as single quotes..
648                         
649                         var vv = this.node.quoteString(v);
650                         // single quote.. v.substring(1, v.length-1).replace("'", "\\'") + "'";
651                         //this.els.add(left + " : " +  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
652                         this.out_props.set(left,  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
653
654                    
655                    
656                    
657                 }
658         }
659          
660         public void readListeners()
661         {
662                 
663                 if (this.node.listeners.size < 1) {
664                         return;
665                 }
666                 // munge the listeners.
667                 //print("ADDING listeners?");
668         
669  
670         
671         
672                 var keys = new Gee.ArrayList<string>();
673                 var piter = this.node.listeners.map_iterator();
674                 while (piter.next() ) {
675                          
676                         keys.add(piter.get_key());
677                 }
678                 keys.sort((  a,  b) => {
679                         return ((string)a).collate((string)b);
680                         //if (a == b) return 0;
681                         //return a < b ? -1 : 1;
682                 });
683         
684                  
685                 for (var i = 0; i< keys.size; i++) {
686                         var key = keys.get(i);
687                         var val = this.node.listeners.get(key);
688                 
689         
690                          // 
691                         var str = val.strip();
692                         var lines = str.split("\n");
693                         if (lines.length > 0) {
694                                 //str = string.joinv("\n" + this.pad + "           ", lines);
695                                 str = string.joinv("\n" + this.pad + indent_str + indent_str , lines);
696                         }
697                          
698                         this.out_listeners.set(key.replace("|", "") ,str);
699                 
700                         
701                 }
702                  
703                  
704
705         }
706
707         public void iterChildren()
708         {
709                 
710                 
711                 // finally munge the children...
712                 if (this.node.items.size < 1) {
713                         return;
714                 }
715                 var itms = "items : [\n";
716                 //var n = 0;
717                 for(var i = 0; i < this.node.items.size;i++) {
718                         var ele = this.node.items.get(i);
719                         if (ele.props.has_key("* prop")) {
720                                 continue;
721                         }
722                          
723                         this.out_children.add(ele);
724                         
725                 }
726                 itms +=  "\n"+  this.pad + "]"  + "\n";
727                 //this.els.add(itms);
728         }
729
730                 // finally output listeners...
731                 
732         public void xIncludeToString()
733         {
734                 
735
736         }
737
738 }
739         
740          
741         
742