2 * Renderer for Javascript output (roo library based)
4 * - translation support
5 * - doubleStringProps contains elements that are 'translable'
6 * ** in the old method this our compression tool could extract them
7 * - the new idea is to make a list at the top of the javascript file
24 Gee.HashMap<string,string> namedStrings;
26 public Roo(Project.Project project, string path) {
31 this.content_type = "";
35 // var jstr = JSON.parse(cfg.json);
36 // this.items = [ jstr ];
37 // //console.log(cfg.items.length);
38 // delete cfg.json; // not needed!
40 this.modOrder = "001"; /// sequence id that this uses.
41 this.region = "center";
42 this.disabled = false;
45 this.id = "file-roo-%d".printf(rid++);
47 // various loader methods..
69 for (var i=0;i<dsp.length;i++) {
70 this.doubleStringProps.add(dsp[i]);
78 public override void removeFiles() {
79 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
80 if (FileUtils.test(html, FileTest.EXISTS)) {
81 GLib.FileUtils.remove(html);
83 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
84 if (FileUtils.test(js, FileTest.EXISTS)) {
85 GLib.FileUtils.remove(js);
89 public override void loadItems() throws GLib.Error // : function(cb, sync) == original was async.
93 GLib.debug("load Items!");
94 if (this.tree != null) {
97 GLib.debug("load " + this.path);
99 var pa = new Json.Parser();
100 pa.load_from_file(this.path);
101 var node = pa.get_root();
103 if (node.get_node_type () != Json.NodeType.OBJECT) {
104 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
106 var obj = node.get_object ();
109 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
110 this.name = this.jsonHasOrEmpty(obj, "name");
111 this.parent = this.jsonHasOrEmpty(obj, "parent");
112 this.permname = this.jsonHasOrEmpty(obj, "permname");
113 this.title = this.jsonHasOrEmpty(obj, "title");
114 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
116 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
117 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
120 // load items[0] ??? into tree...
121 if (obj.has_member("items")
123 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
125 obj.get_array_member("items").get_length() > 0
127 this.tree = new Node();
128 var ar = obj.get_array_member("items");
129 var tree_base = ar.get_object_element(0);
130 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
133 this.toSource(); // force it to number the lines...
139 public override void save()
142 GLib.debug("--- JsRender.Roo.save");
143 GLib.debug("save() - reset transStrings\n");
144 this.transStrings = new Gee.HashMap<string,string>();
145 this.namedStrings = new Gee.HashMap<string,string>();
146 this.findTransStrings(this.tree);
151 if (this.tree == null) {
154 // now write the js file..
157 Regex regex = new Regex("\\.(bjs|js)$");
159 js = regex.replace(this.path,this.path.length , 0 , ".js");
160 } catch (RegexError e) {
162 print("count not make filename from path");
167 //var d = new Date();
168 var js_src = this.toSource();
169 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
171 this.writeFile(js, js_src);
172 } catch (FileError e ) {
173 print("Save failed\n");
175 // for bootstrap - we can write the HTML to the templates directory..
177 //var top = this.guessName(this.items[0]);
178 //print ("TOP = " + top)
188 public override void saveHTML ( string html )
190 GLib.debug ("SAVEHTML %s\n", this.project.runhtml);
191 if (this.project.runhtml == "") {
195 var top = this.tree.fqn();
196 GLib.debug ("TOP = " + top + "\n" );
197 if (top.index_of("Roo.bootstrap.") < 0 &&
198 top.index_of("Roo.mailer.") < 0
204 //now write the js file..
207 Regex regex = new Regex("\\.(bjs|js)$");
209 fn = regex.replace(this.path,this.path.length , 0 , ".html");
210 } catch (RegexError e) {
212 print("count not make filename from path");
215 var bn = GLib.Path.get_basename(fn);
216 var dn = GLib.Path.get_dirname(fn);
218 var targetdir = dn + (
219 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
222 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
223 print("Skip save - templates folder does not exist : %s\n", targetdir);
226 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
228 this.writeFile(targetdir + "/" + bn , html);
229 } catch (FileError e ) {
230 print("SaveHtml failed\n");
237 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
240 if (node.props.has_key("* xinclude")) {
241 ret.add(node.props.get("* xinclude"));
243 for (var i =0; i < node.items.size; i++) {
244 this.findxincludes(node.items.get(i), ret);
252 public override void findTransStrings(Node? node )
254 // iterate properties...
255 // use doubleStringProps
257 // flagging a translatable string..
258 // the code would use string _astring to indicate a translatable string
259 // the to use it it would do String.format(this._message, somedata);
261 // loop through and find string starting with '_'
266 var named = new Gee.HashMap<string,string>();
267 var name_prefix = "";
269 var iter = node.props.map_iterator();
270 while (iter.next()) {
271 // key formats : XXXX
273 // string XXX - with type
274 // $ XXX - with flag (no type)
275 // $ string XXX - with flag
279 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
283 // skip cms-id nodes...
284 if (kname == "html" && node.has("cms-id")) {
287 var str = iter.get_value();
288 if (kname == "name") {
292 var chksum = GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip());
294 if (this.doubleStringProps.index_of(kname) > -1) {
295 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
296 this.transStrings.set(str, chksum);
297 named.set("_" + kname, chksum);
301 if (ktype.down() == "string" && kname[0] == '_') {
302 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
303 this.transStrings.set(str, chksum);
304 named.set(kname, chksum);
309 if (name_prefix != "") {
310 var niter = named.map_iterator();
311 while (niter.next()) {
312 this.namedStrings.set(name_prefix + niter.get_key(),niter.get_value());
317 // iterate children..
318 for (var i =0; i < node.items.size; i++) {
319 this.findTransStrings(node.items.get(i) );
325 public string transStringsToJs()
328 GLib.debug("Roo.transStringsToJs()\n");
329 if (this.transStrings.size < 1) {
330 GLib.debug("Roo.transStringsToJs() size < 1?\n");
335 var iter = this.transStrings.map_iterator();
336 while (iter.next()) {
337 kvs += (" '" + iter.get_value() + "' :" +
338 this.tree.quoteString(iter.get_key())
341 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
350 * javascript used in Webkit preview
353 public override string toSourcePreview()
355 print("toSourcePreview() - reset transStrings\n");
356 this.transStrings = new Gee.HashMap<string,string>();
357 this.namedStrings = new Gee.HashMap<string,string>();
359 print("to source preview\n");
360 if (this.tree == null) {
363 this.findTransStrings(this.tree);
364 var top = this.tree.fqn();
365 var xinc = new Gee.ArrayList<string>();
367 this.findxincludes(this.tree, xinc);
368 print("got %d xincludes\n", xinc.size);
369 var prefix_data = "";
370 if (xinc.size > 0 ) {
371 for(var i = 0; i < xinc.size; i++) {
372 print("check xinclude: %s\n", xinc.get(i));
373 var sf = this.project.getByName(xinc.get(i));
375 print("Failed to find file by name?\n");
380 sf.findTransStrings(sf.tree);
381 var xinc_str = sf.toSource();
384 //FileUtils.get_contents(js, out xinc_str);
385 prefix_data += "\n" + xinc_str + "\n";
393 //print(JSON.stringify(this.items, null,4));
396 print ("guessname returned false");
401 if (top.contains("Dialog")) {
402 return prefix_data + this.toSourceDialog(true);
405 if (top.contains("Modal")) {
406 return prefix_data + this.toSourceModal(true);
409 return prefix_data + this.toSourceLayout(true);
414 public override void setSource(string str) {}
416 * This needs to use some options on the project
417 * to determine how the file is output..
419 * At present we are hard coding it..
423 public override string toSourceCode()
425 this.transStrings = new Gee.HashMap<string,string>();
426 this.namedStrings = new Gee.HashMap<string,string>();
427 this.findTransStrings(this.tree);
428 return this.toSource();
431 public override string toSource()
433 // dump the file tree back out to a string.
435 // we have 2 types = dialogs and components
439 if (this.tree == null) {
442 var top = this.tree.fqn();
449 // get the translatable strings.. = we reload them again so calling methods get the right data...
450 this.transStrings = new Gee.HashMap<string,string>();
451 this.namedStrings = new Gee.HashMap<string,string>();
452 this.findTransStrings(this.tree);
455 if (top.contains("Dialog")) {
456 return this.toSourceDialog(false);
459 if (top.contains("Modal")) {
460 return this.toSourceModal(false);
462 return this.toSourceLayout(false);
465 eventually support 'classes??'
466 return this.toSourceStdClass();
473 * munge JSON tree into Javascript code.
475 * NOTE - needs a deep copy of original tree, before starting..
476 * - so that it does not modify current..
478 * FIXME: + or / prefixes to properties hide it from renderer.
479 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
480 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
482 * @arg {object} obj the object or array to munge..
483 * @arg {boolean} isListener - is the array being sent a listener..
484 * @arg {string} pad - the padding to indent with.
487 public string mungeToStringWrap(string pad, string prefix, string suffix)
489 if (this.tree == null) {
492 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
494 x.cur_line = prefix.split("\n").length;
499 // output both files.. so we can diff them...
500 //this.writeFile("/tmp/old.js", ret);
501 //this.writeFile("/tmp/new.js", nret);
502 return prefix + ret + suffix;
509 public string outputHeader()
512 "//<script type=\"text/javascript\">",
514 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
518 var ret= string.joinv("\n",s);
519 var bits = this.name.split(".");
520 if (bits.length > 1) {
521 ret += "\nRoo.namespace(\'" +
522 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
526 /// genericlly used..
532 // a standard dialog module.
533 // fixme - this could be alot neater..
534 public string toSourceDialog(bool isPreview)
537 //var items = JSON.parse(JSON.stringify(this.items[0]));
542 string[] adda = { " = {",
544 this.transStringsToJs() ,
549 " show : function(data, cb)",
551 " if (!this.dialog) {",
555 " this.callback = cb;",
556 " this.data = data;",
557 " this.dialog.show(this.data._el);",
559 " this.form.reset();",
560 " this.form.setValues(data);",
561 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
566 " create : function()",
568 " var _this = this;",
569 " this.dialog = Roo.factory("
578 return this.mungeToStringWrap(" ",
579 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
580 string.joinv("\n", addb) // footer
588 Bootstrap modal dialog
593 public string toSourceModal(bool isPreview)
597 //var items = JSON.parse(JSON.stringify(this.items[0]));
607 XXXX = function() {};
608 Roo.apply(XXXX.prototype, { .... });
609 Roo.apply(XXXX, XXX.prototype);
613 string[] adda = { "{",
615 this.transStringsToJs() ,
620 " show : function(data, cb)",
622 " if (!this.dialog) {",
626 " this.callback = cb;",
627 " this.data = data;",
628 " this.dialog.show(this.data._el);",
630 " this.form.reset();",
631 " this.form.setValues(data);",
632 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
637 " create : function()",
639 " var _this = this;",
640 " this.dialog = Roo.factory("
647 return this.mungeToStringWrap(" ",
648 this.outputHeader() + "\n" +
649 this.name + "= function() {}\n" +
650 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
651 // body goes here from the function..
652 string.joinv("\n", addb) + ");\n" + // footer
653 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
664 public string pathToPart()
666 var dir = Path.get_basename(Path.get_dirname(this.path));
667 var ar = dir.split(".");
668 var modname = ar[ar.length-1];
670 // now we have the 'module name'..
671 var fbits = Path.get_basename(this.path).split(".");
674 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
675 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
676 npart = npart.substring(modname.length);
678 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
687 public string toSourceLayout(bool isPreview)
692 // topItem.region = 'center';
693 // topItem.background = false;
696 var modkey = this.modOrder + "-" + this.name;
698 var reg = new Regex("[^A-Za-z.]+");
700 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
701 } catch (RegexError e) {
704 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
709 // set to false to ensure this is the top level..
711 var topnode = this.tree.fqn();
712 print("topnode = %s\n", topnode);
713 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
714 topnode != "Roo.bootstrap.Body"
716 parent = "\"#bootstrap-body\"";
723 var pref = this.outputHeader() + "\n" +
725 this.name + " = new Roo.XComponent({\n" +
727 this.transStringsToJs() + "\n" +
729 " part : "+ this.pathToPart() + ",\n" +
730 /// critical used by builder to associate modules/parts/persm
731 " order : '" +modkey+"',\n" +
732 " region : '" + this.region +"',\n" +
733 " parent : "+ parent + ",\n" +
734 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
735 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
736 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
738 // " tree : function() { return this._tree(); },\n" + //BC
739 " _tree : function(_data)\n" +
741 " var _this = this;\n" + // bc
742 " var MODULE = this;\n" + /// this looks like a better name.
745 return this.mungeToStringWrap(" ", pref, ";" +
753 public new string? guessName (Node? ar) // turns the object into full name.
755 // eg. xns: Roo, xtype: XXX -> Roo.xxx
761 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
764 if ( ar.get("xtype").length < 1) {
768 var xtype = ar.get("xtype");
770 if (xtype[0] == '*') { // prefixes????
771 xtype = xtype.substring(1);
773 if (! Regex.match_simple("^Roo", xtype)) {
775 // already starts with roo...
779 var str = string.joinv(".", ret);
783 //Palete.Palete.factory("Roo").guessName(str);
789 string getHelpUrl(string cls)
791 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";