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