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