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