resources/RooUsage.txt
[app.Builder.js] / src / JsRender / Roo.vala
index 18a0eab..25f003c 100644 (file)
@@ -1,19 +1,35 @@
+/*
+ * Renderer for Javascript output (roo library based)
+ * 
+ * - translation support
+ * -  doubleStringProps contains elements that are 'translable'
+ *    ** in the old method this our compression tool could extract them
+ *  - the  new idea is to make a list at the top of the javascript file
+ *    and output a map...
+ *    
+ * 
+ * 
+ * 
+ * 
+ */
 namespace JsRender {
 
     static int rid = 0; 
+   
     class Roo : JsRender 
     {
-       string region;
+        string region;
         bool disabled;
+
+
         
         public Roo(Project.Project project, string path) {
             base( project, path);
             this.xtype = "Roo";
              this.language = "js";
             
-            
+           this.content_type = "";
+           
             //this.items = false;
             //if (cfg.json) {
             //    var jstr =  JSON.parse(cfg.json);
@@ -30,7 +46,8 @@ namespace JsRender {
             //console.dump(this);
             // various loader methods..
 
-            string[]  dsp = { "title",
+            string[]  dsp = { 
+                               "title",
                 "legend",
                 "loadingText",
                 "emptyText",
@@ -38,7 +55,14 @@ namespace JsRender {
                 "value",
                 "text",
                 "emptyMsg",
-                "displayMsg" };
+                "displayMsg",
+                "html",
+                "headline",
+                "header",
+                "placeholder",
+                "fieldLabel",
+                
+                };
             for (var i=0;i<dsp.length;i++) {
                 this.doubleStringProps.add(dsp[i]);
             }
@@ -46,155 +70,77 @@ namespace JsRender {
             
         }
     
-    /*    
-        setNSID : function(id)
-        {
-            
-            this.items[0]['|module'] = id;
-       
-            
-        },
-        
-        
-        getType: function() {
-            return 'Roo';
-        },
-
-    */
                
-       public   override void   removeFiles() {
-               var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
-               if (FileUtils.test(html, FileTest.EXISTS)) {
-                       GLib.FileUtils.remove(html);
-               }
-               var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
-               if (FileUtils.test(js, FileTest.EXISTS)) {
-                       GLib.FileUtils.remove(js);
+               public   override void   removeFiles() {
+                       var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
+                       if (FileUtils.test(html, FileTest.EXISTS)) {
+                               GLib.FileUtils.remove(html);
+                       }
+                       var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
+                       if (FileUtils.test(js, FileTest.EXISTS)) {
+                               GLib.FileUtils.remove(js);
+                       }
                }
-       }
                
         public  override void  loadItems() throws GLib.Error // : function(cb, sync) == original was async.
         {
             
-             
-               print("load Items!");
-               if (this.tree != null) {
-                       return;
-               }
-               print("load " + this.path);
-
-               var pa = new Json.Parser();
-               pa.load_from_file(this.path);
-               var node = pa.get_root();
-
-               if (node.get_node_type () != Json.NodeType.OBJECT) {
-                       throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
-               }
-               var obj = node.get_object ();
-       
-       
-               this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
-               this.name = this.jsonHasOrEmpty(obj, "name");
-               this.parent = this.jsonHasOrEmpty(obj, "parent");
-               this.permname = this.jsonHasOrEmpty(obj, "permname");
-               this.title = this.jsonHasOrEmpty(obj, "title");
-               this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
+                                
+                       GLib.debug("load Items!");
+                       if (this.tree != null) {
+                               return;
+                       }
+                       GLib.debug("load " + this.path);
 
-               var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
-               bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
+                       var pa = new Json.Parser();
+                       pa.load_from_file(this.path);
+                       var node = pa.get_root();
 
+                       if (node.get_node_type () != Json.NodeType.OBJECT) {
+                               throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
+                       }
+                       var obj = node.get_object ();
                
-               // load items[0] ??? into tree...
-               if (obj.has_member("items") 
-                       && 
-                       obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
-                       &&
-                       obj.get_array_member("items").get_length() > 0
-               ) {
-                       this.tree = new Node(); 
-                       var ar = obj.get_array_member("items");
-                       var tree_base = ar.get_object_element(0);
-                       this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
-               }
+               
+                       this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
+                       this.name = this.jsonHasOrEmpty(obj, "name");
+                       this.parent = this.jsonHasOrEmpty(obj, "parent");
+                       this.permname = this.jsonHasOrEmpty(obj, "permname");
+                       this.title = this.jsonHasOrEmpty(obj, "title");
+                       this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
 
+                       var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
+                       bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
+
+                       
+                       // load items[0] ??? into tree...
+                       if (obj.has_member("items") 
+                               && 
+                               obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
+                               &&
+                               obj.get_array_member("items").get_length() > 0
+                       ) {
+                               this.tree = new Node(); 
+                               var ar = obj.get_array_member("items");
+                               var tree_base = ar.get_object_element(0);
+                               this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
+                       }
+                       this.loaded = true;
+                       this.toSource(); // force it to number the lines...
 
             
         }
-        /**
-         * old code had broken xtypes and used arrays differently,
-         * this code should try and clean it up..
-         * 
-         * 
-         * /
-        fixItems : function(node, fixthis)
-        {
-            if (fixthis) {
-                // fix xtype.
-                var fn = this.guessName(node);
-                //print("guessname got " + fn);
-                if (fn) {
-                    var bits = fn.split('.');
-                    node.xtype = bits.pop();
-                    node['|xns'] = bits.join('.');
-                    
-                }
-                // fix array???
-                 
-                
-            }
-            if (!node.items || !node.items.length) {
-                return;
-            }
-            var _this = this;
-            var aitems = [];
-            var nitems = [];
-            node.items.forEach(function(i) {
-                
-                
-                
-                _this.fixItems(i, true);
-                if (i.xtype == 'Array') {
-                    aitems.push(i);
-                    return;
-                }    
-                nitems.push(i);
-            });
-            node.items = nitems; 
-            
-            if (!aitems.length) {
-                return;
-            }
-            
-            aitems.forEach(function(i) {
-                
-                if (!i.items || !i.items.length) {
-                    return;
-                }
-                var prop = i['*prop'] + '[]';
-                // colModel to cm?
-                i.items.forEach(function(c) {
-                    c['*prop']  = prop;
-                    node.items.push(c);
-                    
-                });
-                
-                
-            });
-            
-            
-            // array handling.. 
-            
-            
-            
-            
-            
-        },
-    */
+        
         
        public  override  void save()
-        {
+       {
             
-               print("--- JsRender.Roo.save");
+               GLib.debug("--- JsRender.Roo.save");
+               GLib.debug("save() - reset transStrings\n");
+               this.transStrings = new Gee.HashMap<string,string>();
+               this.findTransStrings(this.tree);
+               
                this.saveBJS();
 
                // no tree..
@@ -230,7 +176,7 @@ namespace JsRender {
             
             
             
-        }
+       }
 
         
 
@@ -239,15 +185,15 @@ namespace JsRender {
        {
                 
                var top = this.tree.fqn();
-               print ("TOP = " + top + "\n" );
-               if (top.index_of("Roo.bootstrap.") < 0 &&
-                   top.index_of("Roo.mailer.") < 0
-                       ) {
-                       return;
-               }
+               GLib.debug ("TOP = " + top + "\n" );
+               if (top.index_of("Roo.bootstrap.") < 0 &&
+           top.index_of("Roo.mailer.") < 0
+               ) {
+               return;
+               }
                
                
-// now write the js file..
+               //now write the js file..
                string fn;
                try {
                        Regex regex = new Regex("\\.(bjs|js)$");
@@ -269,7 +215,7 @@ namespace JsRender {
                        print("Skip save - templates folder does not exist : %s\n", targetdir);
                        return;
                }
-               print("SAVE HTML -- %s\n%s\n",targetdir + "/" +  bn, html);
+               //print("SAVE HTML -- %s\n%s\n",targetdir + "/" +  bn, html);
                try {
                        this.writeFile(targetdir + "/" +  bn , html);            
                } catch (FileError e ) {
@@ -280,79 +226,173 @@ namespace JsRender {
             
         }
 
-       public Gee.ArrayList<string> findxincludes(Node node,   Gee.ArrayList<string> ret)
-       {
-               
-               if (node.props.has_key("* xinclude")) {
-                       ret.add(node.props.get("* xinclude"));
-               }
-               for (var i =0; i < node.items.size; i++) {
-                       this.findxincludes(node.items.get(i), ret);
+               public Gee.ArrayList<string> findxincludes(Node node,   Gee.ArrayList<string> ret)
+               {
+                       
+                       if (node.props.has_key("* xinclude")) {
+                               ret.add(node.props.get("* xinclude"));
+                       }
+                       for (var i =0; i < node.items.size; i++) {
+                               this.findxincludes(node.items.get(i), ret);
+                       }
+                       return ret;
+                               
                }
-               return ret;
+                
+
+                
+               public override void  findTransStrings(Node? node )
+               {
+                       // iterate properties...
+                       // use doubleStringProps
                        
-       }
-           
+                       // flagging a translatable string..
+                       // the code would use string _astring to indicate a translatable string
+                       // the to use it it would do String.format(this._message, somedata);
+                       
+                       // loop through and find string starting with '_' 
+                       if (node == null) {
+                               return;
+                       }               
+                       
+                       var iter = node.props.map_iterator();
+                       while (iter.next()) {
+                               // key formats : XXXX
+                               // XXX - plain
+                               // string XXX - with type
+                               // $ XXX - with flag (no type)
+                               // $ string XXX - with flag
+                               string kname;
+                               string ktype;
+                               string kflag;
+                               node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
+                               if (kflag == "$") {
+                                       continue;
+                               }
+                               // skip cms-id nodes...
+                               if (kname == "html" && node.has("cms-id")) { 
+                                       continue;
+                               }
+                               
+                               var str = iter.get_value();
+                               if (this.doubleStringProps.index_of(kname) > -1) {
+                                       GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
+                                       this.transStrings.set(str,  
+                                               GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip())
+                                       );
+                                       continue;
+                               }
+                               
+                               if (ktype.down() == "string" && kname[0] == '_') {
+                                       GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
+                                       this.transStrings.set(str,  
+                                               GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip())
+                                       );
+                                       continue;
+                               }
+                               
+                       }
+                        
+
+                       
+                       // iterate children..
+                       for (var i =0; i < node.items.size; i++) {
+                               this.findTransStrings(node.items.get(i) );
+                       }
+               
+                               
+               }  
+               
+               public string  transStringsToJs()
+               {
+                       
+                       GLib.debug("Roo.transStringsToJs()\n");
+                       if (this.transStrings.size < 1) {
+                               GLib.debug("Roo.transStringsToJs() size < 1?\n");
+                               return "";
+                       }
+                        
+                       string[] kvs = {};
+                       var iter = this.transStrings.map_iterator();
+                       while (iter.next()) {
+                               kvs +=  ("  '" + iter.get_value() + "' :" + 
+                                       this.tree.quoteString(iter.get_key())
+                                       );
+                       }
+                       return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" + 
+                               " },";
+                               
+                
+              
+                       
+               }
+                 
         /**
         * javascript used in Webkit preview 
          */
         
         public override string  toSourcePreview()
         {
-               print("to source preview\n");
-               if (this.tree == null) {
-                       return "";
-               }
-               var top = this.tree.fqn();
-               var xinc = new Gee.ArrayList<string>(); 
+                       print("toSourcePreview() - reset transStrings\n");
+                       this.transStrings = new Gee.HashMap<string,string>();
+                       
+               
+                       print("to source preview\n");
+                       if (this.tree == null) {
+                               return "";
+                       }
+                       this.findTransStrings(this.tree);
+                       var top = this.tree.fqn();
+                       var xinc = new Gee.ArrayList<string>(); 
 
-               this.findxincludes(this.tree, xinc);
-               print("got %d xincludes\n", xinc.size);
-               var prefix_data = "";
-               if (xinc.size > 0 ) {
-                       for(var i = 0; i < xinc.size; i++) {
-                               print("check xinclude:  %s\n", xinc.get(i));
-                               var sf = this.project.getByName(xinc.get(i));
-                               if (sf == null) {
-                                       print("Failed to find file by name?\n");
-                                       continue;
+                       this.findxincludes(this.tree, xinc);
+                       print("got %d xincludes\n", xinc.size);
+                       var prefix_data = "";
+                       if (xinc.size > 0 ) {
+                               for(var i = 0; i < xinc.size; i++) {
+                                       print("check xinclude:  %s\n", xinc.get(i));
+                                       var sf = this.project.getByName(xinc.get(i));
+                                       if (sf == null) {
+                                               print("Failed to find file by name?\n");
+                                               continue;
+                                       }
+
+                                       sf.loadItems();
+                                       sf.findTransStrings(sf.tree);
+                                       var xinc_str = sf.toSource();
+                                       
+                                       //string xinc_str;
+                                       //FileUtils.get_contents(js, out xinc_str);
+                                       prefix_data += "\n" + xinc_str + "\n";
+                                       
                                }
 
-                               sf.loadItems();
-                               var xinc_str = sf.toSource();
-                               
-                               //string xinc_str;
-                               //FileUtils.get_contents(js, out xinc_str);
-                               prefix_data += "\n" + xinc_str + "\n";
-                               
                        }
 
-               }
-
-               
-               
-               //print(JSON.stringify(this.items, null,4));
-                      
-               if (top == null) {
-                       print ("guessname returned false");
-                       return "";
-               }
+                       
+                       
+                       //print(JSON.stringify(this.items, null,4));
+                                  
+                       if (top == null) {
+                               print ("guessname returned false");
+                               return "";
+                       }
 
 
-               if (top.contains("Dialog")) {
-                       return prefix_data + this.toSourceDialog(true);
-               }
+                       if (top.contains("Dialog")) {
+                               return prefix_data + this.toSourceDialog(true);
+                       }
 
-               if (top.contains("Modal")) {
-                       return prefix_data + this.toSourceModal(true);
-               }
+                       if (top.contains("Modal")) {
+                               return prefix_data + this.toSourceModal(true);
+                       }
 
-               return prefix_data + this.toSourceLayout(true);
-            
-            
+                       return prefix_data + this.toSourceLayout(true);
+                               
+                               
             
         }
-        
+        public override void setSource(string str) {}
         /**
          * This needs to use some options on the project
          * to determine how the file is output..
@@ -361,19 +401,36 @@ namespace JsRender {
          * 
          * 
          */
+        public override string toSourceCode() 
+        {
+                       this.transStrings = new Gee.HashMap<string,string>();
+                       this.findTransStrings(this.tree);
+                       return this.toSource();
+               }
+         
         public override string toSource()
         {
             // dump the file tree back out to a string.
             
             // we have 2 types = dialogs and components
             // 
-           if (this.tree == null) {
-                   return "";
-           }
+            
+            
+                       if (this.tree == null) {
+                               return "";
+                       }
             var top = this.tree.fqn();
             if (top == null) {
                 return "";
             }
+            
+            
+            
+            // get the translatable strings.. = we reload them again so calling methods get the right data...
+            this.transStrings = new Gee.HashMap<string,string>();
+                       this.findTransStrings(this.tree);
+            
+            
             if (top.contains("Dialog")) {
                 return this.toSourceDialog(false);
             }
@@ -389,6 +446,44 @@ namespace JsRender {
             */
               
         }
+        
+        /**
+                * 
+                * munge JSON tree into Javascript code.
+                *
+                * NOTE - needs a deep copy of original tree, before starting..
+                *     - so that it does not modify current..
+                * 
+                * FIXME: + or / prefixes to properties hide it from renderer.
+                * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
+                * FIXME: needs to understand what properties might be translatable (eg. double quotes)
+                * 
+                * @arg {object} obj the object or array to munge..
+                * @arg {boolean} isListener - is the array being sent a listener..
+                * @arg {string} pad - the padding to indent with. 
+                */
+               
+               public string mungeToStringWrap(string pad, string prefix, string suffix)
+               {
+                       if (this.tree == null) {
+                               return "";
+                       }
+                       var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
+                       x.renderer = this;
+                       x.cur_line = prefix.split("\n").length;
+                       
+                       var ret = x.munge();
+                       //var nret = x.ret;
+                       
+                       // output both files.. so we can diff them...
+                       //this.writeFile("/tmp/old.js", ret);
+                       //this.writeFile("/tmp/new.js", nret);                  
+                       return prefix +  ret + suffix;
+                       
+                   
+               }
+        
+        
        
         public string outputHeader()
         {
@@ -421,10 +516,11 @@ namespace JsRender {
             //var items = JSON.parse(JSON.stringify(this.items[0]));
             
             
-            var o = this.mungeToString("    ");   
-
+           
  
             string[] adda = { " = {",
+                "",
+                this.transStringsToJs() ,
                 "",
                 " dialog : false,",
                 " callback:  false,",
@@ -457,22 +553,32 @@ namespace JsRender {
                 "};",
                 ""
             };
-            return  this.outputHeader() + "\n" +
-                this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
-            
+             
+            return this.mungeToStringWrap("    ",   
+                       this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
+                       string.joinv("\n", addb) // footer
+               );
+             
              
              
              
         }
+        /**
+         Bootstrap modal dialog 
+         
+        */
+        
         
         public string toSourceModal(bool isPreview) 
         {
             
             
             //var items = JSON.parse(JSON.stringify(this.items[0]));
-            var o = this.mungeToString("    ");   
+             
             
             string[] adda = { " = {",
+                "",
+                this.transStringsToJs() ,
                 "",
                 " dialog : false,",
                 " callback:  false,",
@@ -505,12 +611,17 @@ namespace JsRender {
                 "};",
                 ""
             };
-            return this.outputHeader() + "\n" + 
-                this.name + string.joinv("\n", adda) + o + string.joinv("\n", addb);
+                       return this.mungeToStringWrap("    ",   
+                       this.outputHeader() + "\n" +  this.name + string.joinv("\n", adda), // header
+                       string.joinv("\n", addb) // footer
+               );
              
              
              
         }
+        
+        
+        
         
         
         public string   pathToPart()
@@ -545,11 +656,14 @@ namespace JsRender {
                        //    topItem.background = false;
                }
             
-               var o = this.mungeToString("   ");   
-               var reg = new Regex("[^A-Za-z.]+");
-            
-               string modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
+               var  modkey = this.modOrder + "-" +   this.name;
+               try {
+                       var reg = new Regex("[^A-Za-z.]+");
             
+                        modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
+            } catch (RegexError e) {
+                       //noop..
+            }
                string  parent =   (this.parent.length > 0 ?  "'" + this.parent + "'" :  "false");
 
                
@@ -557,8 +671,8 @@ namespace JsRender {
                if (isPreview) {
                        // set to false to ensure this is the top level..
                        parent = "false";
-                       var topnode = this.tree.fqn();
-                       print("topnode = %s\n", topnode);
+                               var topnode = this.tree.fqn();
+                               print("topnode = %s\n", topnode);
                        if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
                            topnode != "Roo.bootstrap.Body"
                        ) {
@@ -567,11 +681,14 @@ namespace JsRender {
                          
                }
             
-          
-               return 
-                       this.outputHeader() + "\n" +
+            
+            
+            var pref = this.outputHeader() + "\n" +
                        
                        this.name  +  " = new Roo.XComponent({\n" +
+                       "\n" + 
+                       this.transStringsToJs()  +    "\n" +
+                "\n" +
                        "  part     :  "+ this.pathToPart() + ",\n" +
                                /// critical used by builder to associate modules/parts/persm
                        "  order    : '" +modkey+"',\n" +
@@ -586,12 +703,14 @@ namespace JsRender {
                        "  {\n" +
                        "   var _this = this;\n" + // bc
                        "   var MODULE = this;\n" + /// this looks like a better name.
-                       "   return " + o + ";" +
+                       "   return ";
+                       
+                   return this.mungeToStringWrap("   ", pref,  ";" +
                        "  }\n" +
-                       "});\n";
-                        
-             
-            
+                       "});\n"
+               );
+                     
+              
         }
             
         public new string? guessName (Node? ar) // turns the object into full name.
@@ -637,4 +756,4 @@ namespace JsRender {
                 
      
     }
-}
\ No newline at end of file
+}