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");
336 var hash = new Gee.HashMap<string,string>();
337 var iter = this.transStrings.map_iterator();
338 while (iter.next()) {
339 hash.set(iter.get_value(), iter.get_key());
340 kvs += (" '" + iter.get_value() + "' :" +
341 this.tree.quoteString(iter.get_key())
345 var ret = " _strings : {\n" + string.joinv(",\n", kvs) + "\n },";
349 var niter = this.namedStrings.map_iterator();
350 while (niter.next()) {
351 var otext = hash.get(niter.get_value());
352 var com = " /* " + (otext.replace("*/", "* - /") + " */ ");
355 ns += (" '" + niter.get_key() + "' : '" + niter.get_value() + "'" + com);
357 if (ns.length > 0 ) {
358 ret += "\n _named_strings : {\n" + string.joinv(",\n", ns) + "\n },";
365 * javascript used in Webkit preview
368 public override string toSourcePreview()
370 print("toSourcePreview() - reset transStrings\n");
371 this.transStrings = new Gee.HashMap<string,string>();
372 this.namedStrings = new Gee.HashMap<string,string>();
374 print("to source preview\n");
375 if (this.tree == null) {
378 this.findTransStrings(this.tree);
379 var top = this.tree.fqn();
380 var xinc = new Gee.ArrayList<string>();
382 this.findxincludes(this.tree, xinc);
383 print("got %d xincludes\n", xinc.size);
384 var prefix_data = "";
385 if (xinc.size > 0 ) {
386 for(var i = 0; i < xinc.size; i++) {
387 print("check xinclude: %s\n", xinc.get(i));
388 var sf = this.project.getByName(xinc.get(i));
390 print("Failed to find file by name?\n");
395 sf.findTransStrings(sf.tree);
396 var xinc_str = sf.toSource();
399 //FileUtils.get_contents(js, out xinc_str);
400 prefix_data += "\n" + xinc_str + "\n";
408 //print(JSON.stringify(this.items, null,4));
411 print ("guessname returned false");
416 if (top.contains("Dialog")) {
417 return prefix_data + this.toSourceDialog(true);
420 if (top.contains("Modal")) {
421 return prefix_data + this.toSourceModal(true);
424 return prefix_data + this.toSourceLayout(true);
429 public override void setSource(string str) {}
431 * This needs to use some options on the project
432 * to determine how the file is output..
434 * At present we are hard coding it..
438 public override string toSourceCode()
440 this.transStrings = new Gee.HashMap<string,string>();
441 this.namedStrings = new Gee.HashMap<string,string>();
442 this.findTransStrings(this.tree);
443 return this.toSource();
446 public override string toSource()
448 // dump the file tree back out to a string.
450 // we have 2 types = dialogs and components
454 if (this.tree == null) {
457 var top = this.tree.fqn();
464 // get the translatable strings.. = we reload them again so calling methods get the right data...
465 this.transStrings = new Gee.HashMap<string,string>();
466 this.namedStrings = new Gee.HashMap<string,string>();
467 this.findTransStrings(this.tree);
470 if (top.contains("Dialog")) {
471 return this.toSourceDialog(false);
474 if (top.contains("Modal")) {
475 return this.toSourceModal(false);
477 return this.toSourceLayout(false);
480 eventually support 'classes??'
481 return this.toSourceStdClass();
488 * munge JSON tree into Javascript code.
490 * NOTE - needs a deep copy of original tree, before starting..
491 * - so that it does not modify current..
493 * FIXME: + or / prefixes to properties hide it from renderer.
494 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
495 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
497 * @arg {object} obj the object or array to munge..
498 * @arg {boolean} isListener - is the array being sent a listener..
499 * @arg {string} pad - the padding to indent with.
502 public string mungeToStringWrap(string pad, string prefix, string suffix)
504 if (this.tree == null) {
507 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
509 x.cur_line = prefix.split("\n").length;
514 // output both files.. so we can diff them...
515 //this.writeFile("/tmp/old.js", ret);
516 //this.writeFile("/tmp/new.js", nret);
517 return prefix + ret + suffix;
524 public string outputHeader()
527 "//<script type=\"text/javascript\">",
529 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
533 var ret= string.joinv("\n",s);
534 var bits = this.name.split(".");
535 if (bits.length > 1) {
536 ret += "\nRoo.namespace(\'" +
537 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
541 /// genericlly used..
547 // a standard dialog module.
548 // fixme - this could be alot neater..
549 public string toSourceDialog(bool isPreview)
552 //var items = JSON.parse(JSON.stringify(this.items[0]));
557 string[] adda = { " = {",
559 this.transStringsToJs() ,
564 " show : function(data, cb)",
566 " if (!this.dialog) {",
570 " this.callback = cb;",
571 " this.data = data;",
572 " this.dialog.show(this.data._el);",
574 " this.form.reset();",
575 " this.form.setValues(data);",
576 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
581 " create : function()",
583 " var _this = this;",
584 " this.dialog = Roo.factory("
593 return this.mungeToStringWrap(" ",
594 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
595 string.joinv("\n", addb) // footer
603 Bootstrap modal dialog
608 public string toSourceModal(bool isPreview)
612 //var items = JSON.parse(JSON.stringify(this.items[0]));
622 XXXX = function() {};
623 Roo.apply(XXXX.prototype, { .... });
624 Roo.apply(XXXX, XXX.prototype);
628 string[] adda = { "{",
630 this.transStringsToJs() ,
635 " show : function(data, cb)",
637 " if (!this.dialog) {",
641 " this.callback = cb;",
642 " this.data = data;",
643 " this.dialog.show(this.data._el);",
645 " this.form.reset();",
646 " this.form.setValues(data);",
647 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
652 " create : function()",
654 " var _this = this;",
655 " this.dialog = Roo.factory("
662 return this.mungeToStringWrap(" ",
663 this.outputHeader() + "\n" +
664 this.name + "= function() {}\n" +
665 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
666 // body goes here from the function..
667 string.joinv("\n", addb) + ");\n" + // footer
668 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
679 public string pathToPart()
681 var dir = Path.get_basename(Path.get_dirname(this.path));
682 var ar = dir.split(".");
683 var modname = ar[ar.length-1];
685 // now we have the 'module name'..
686 var fbits = Path.get_basename(this.path).split(".");
689 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
690 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
691 npart = npart.substring(modname.length);
693 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
702 public string toSourceLayout(bool isPreview)
707 // topItem.region = 'center';
708 // topItem.background = false;
711 var modkey = this.modOrder + "-" + this.name;
713 var reg = new Regex("[^A-Za-z.]+");
715 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
716 } catch (RegexError e) {
719 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
724 // set to false to ensure this is the top level..
726 var topnode = this.tree.fqn();
727 print("topnode = %s\n", topnode);
728 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
729 topnode != "Roo.bootstrap.Body"
731 parent = "\"#bootstrap-body\"";
738 var pref = this.outputHeader() + "\n" +
740 this.name + " = new Roo.XComponent({\n" +
742 this.transStringsToJs() + "\n" +
744 " part : "+ this.pathToPart() + ",\n" +
745 /// critical used by builder to associate modules/parts/persm
746 " order : '" +modkey+"',\n" +
747 " region : '" + this.region +"',\n" +
748 " parent : "+ parent + ",\n" +
749 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
750 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
751 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
753 // " tree : function() { return this._tree(); },\n" + //BC
754 " _tree : function(_data)\n" +
756 " var _this = this;\n" + // bc
757 " var MODULE = this;\n" + /// this looks like a better name.
760 return this.mungeToStringWrap(" ", pref, ";" +
768 public new string? guessName (Node? ar) // turns the object into full name.
770 // eg. xns: Roo, xtype: XXX -> Roo.xxx
776 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
779 if ( ar.get("xtype").length < 1) {
783 var xtype = ar.get("xtype");
785 if (xtype[0] == '*') { // prefixes????
786 xtype = xtype.substring(1);
788 if (! Regex.match_simple("^Roo", xtype)) {
790 // already starts with roo...
794 var str = string.joinv(".", ret);
798 //Palete.Palete.factory("Roo").guessName(str);
804 string getHelpUrl(string cls)
806 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";