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
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.findTransStrings(this.tree);
150 if (this.tree == null) {
153 // now write the js file..
156 Regex regex = new Regex("\\.(bjs|js)$");
158 js = regex.replace(this.path,this.path.length , 0 , ".js");
159 } catch (RegexError e) {
161 print("count not make filename from path");
166 //var d = new Date();
167 var js_src = this.toSource();
168 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
170 this.writeFile(js, js_src);
171 } catch (FileError e ) {
172 print("Save failed\n");
174 // for bootstrap - we can write the HTML to the templates directory..
176 //var top = this.guessName(this.items[0]);
177 //print ("TOP = " + top)
187 public override void saveHTML ( string html )
189 GLib.debug ("SAVEHTML %s\n", this.project.runhtml);
190 if (this.project.runhtml == "") {
194 var top = this.tree.fqn();
195 GLib.debug ("TOP = " + top + "\n" );
196 if (top.index_of("Roo.bootstrap.") < 0 &&
197 top.index_of("Roo.mailer.") < 0
203 //now write the js file..
206 Regex regex = new Regex("\\.(bjs|js)$");
208 fn = regex.replace(this.path,this.path.length , 0 , ".html");
209 } catch (RegexError e) {
211 print("count not make filename from path");
214 var bn = GLib.Path.get_basename(fn);
215 var dn = GLib.Path.get_dirname(fn);
217 var targetdir = dn + (
218 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
221 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
222 print("Skip save - templates folder does not exist : %s\n", targetdir);
225 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
227 this.writeFile(targetdir + "/" + bn , html);
228 } catch (FileError e ) {
229 print("SaveHtml failed\n");
236 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
239 if (node.props.has_key("* xinclude")) {
240 ret.add(node.props.get("* xinclude"));
242 for (var i =0; i < node.items.size; i++) {
243 this.findxincludes(node.items.get(i), ret);
251 public override void findTransStrings(Node? node )
253 // iterate properties...
254 // use doubleStringProps
256 // flagging a translatable string..
257 // the code would use string _astring to indicate a translatable string
258 // the to use it it would do String.format(this._message, somedata);
260 // loop through and find string starting with '_'
265 var named = new Gee.HashMap<string,string>();
266 var name_prefix = "";
268 var iter = node.props.map_iterator();
269 while (iter.next()) {
270 // key formats : XXXX
272 // string XXX - with type
273 // $ XXX - with flag (no type)
274 // $ string XXX - with flag
278 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
282 // skip cms-id nodes...
283 if (kname == "html" && node.has("cms-id")) {
286 var str = iter.get_value();
287 if (kname == "name") {
291 var chksum = GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip());
293 if (this.doubleStringProps.index_of(kname) > -1) {
294 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
295 this.transStrings.set(str, chksum);
296 named.set("_" + kname, chksum);
300 if (ktype.down() == "string" && kname[0] == '_') {
301 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
302 this.transStrings.set(str, chksum);
303 named.set(kname, chksum);
308 if (name_prefix != "") {
309 var niter = named.map_iterator();
310 while (niter.next()) {
311 this.namedStrings.set(name_prefix + niter.get_key(),niter.get_value());
316 // iterate children..
317 for (var i =0; i < node.items.size; i++) {
318 this.findTransStrings(node.items.get(i) );
324 public string transStringsToJs()
327 GLib.debug("Roo.transStringsToJs()\n");
328 if (this.transStrings.size < 1) {
329 GLib.debug("Roo.transStringsToJs() size < 1?\n");
334 var iter = this.transStrings.map_iterator();
335 while (iter.next()) {
336 kvs += (" '" + iter.get_value() + "' :" +
337 this.tree.quoteString(iter.get_key())
340 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
349 * javascript used in Webkit preview
352 public override string toSourcePreview()
354 print("toSourcePreview() - reset transStrings\n");
355 this.transStrings = new Gee.HashMap<string,string>();
358 print("to source preview\n");
359 if (this.tree == null) {
362 this.findTransStrings(this.tree);
363 var top = this.tree.fqn();
364 var xinc = new Gee.ArrayList<string>();
366 this.findxincludes(this.tree, xinc);
367 print("got %d xincludes\n", xinc.size);
368 var prefix_data = "";
369 if (xinc.size > 0 ) {
370 for(var i = 0; i < xinc.size; i++) {
371 print("check xinclude: %s\n", xinc.get(i));
372 var sf = this.project.getByName(xinc.get(i));
374 print("Failed to find file by name?\n");
379 sf.findTransStrings(sf.tree);
380 var xinc_str = sf.toSource();
383 //FileUtils.get_contents(js, out xinc_str);
384 prefix_data += "\n" + xinc_str + "\n";
392 //print(JSON.stringify(this.items, null,4));
395 print ("guessname returned false");
400 if (top.contains("Dialog")) {
401 return prefix_data + this.toSourceDialog(true);
404 if (top.contains("Modal")) {
405 return prefix_data + this.toSourceModal(true);
408 return prefix_data + this.toSourceLayout(true);
413 public override void setSource(string str) {}
415 * This needs to use some options on the project
416 * to determine how the file is output..
418 * At present we are hard coding it..
422 public override string toSourceCode()
424 this.transStrings = new Gee.HashMap<string,string>();
425 this.findTransStrings(this.tree);
426 return this.toSource();
429 public override string toSource()
431 // dump the file tree back out to a string.
433 // we have 2 types = dialogs and components
437 if (this.tree == null) {
440 var top = this.tree.fqn();
447 // get the translatable strings.. = we reload them again so calling methods get the right data...
448 this.transStrings = new Gee.HashMap<string,string>();
449 this.findTransStrings(this.tree);
452 if (top.contains("Dialog")) {
453 return this.toSourceDialog(false);
456 if (top.contains("Modal")) {
457 return this.toSourceModal(false);
459 return this.toSourceLayout(false);
462 eventually support 'classes??'
463 return this.toSourceStdClass();
470 * munge JSON tree into Javascript code.
472 * NOTE - needs a deep copy of original tree, before starting..
473 * - so that it does not modify current..
475 * FIXME: + or / prefixes to properties hide it from renderer.
476 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
477 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
479 * @arg {object} obj the object or array to munge..
480 * @arg {boolean} isListener - is the array being sent a listener..
481 * @arg {string} pad - the padding to indent with.
484 public string mungeToStringWrap(string pad, string prefix, string suffix)
486 if (this.tree == null) {
489 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
491 x.cur_line = prefix.split("\n").length;
496 // output both files.. so we can diff them...
497 //this.writeFile("/tmp/old.js", ret);
498 //this.writeFile("/tmp/new.js", nret);
499 return prefix + ret + suffix;
506 public string outputHeader()
509 "//<script type=\"text/javascript\">",
511 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
515 var ret= string.joinv("\n",s);
516 var bits = this.name.split(".");
517 if (bits.length > 1) {
518 ret += "\nRoo.namespace(\'" +
519 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
523 /// genericlly used..
529 // a standard dialog module.
530 // fixme - this could be alot neater..
531 public string toSourceDialog(bool isPreview)
534 //var items = JSON.parse(JSON.stringify(this.items[0]));
539 string[] adda = { " = {",
541 this.transStringsToJs() ,
546 " show : function(data, cb)",
548 " if (!this.dialog) {",
552 " this.callback = cb;",
553 " this.data = data;",
554 " this.dialog.show(this.data._el);",
556 " this.form.reset();",
557 " this.form.setValues(data);",
558 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
563 " create : function()",
565 " var _this = this;",
566 " this.dialog = Roo.factory("
575 return this.mungeToStringWrap(" ",
576 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
577 string.joinv("\n", addb) // footer
585 Bootstrap modal dialog
590 public string toSourceModal(bool isPreview)
594 //var items = JSON.parse(JSON.stringify(this.items[0]));
604 XXXX = function() {};
605 Roo.apply(XXXX.prototype, { .... });
606 Roo.apply(XXXX, XXX.prototype);
610 string[] adda = { "{",
612 this.transStringsToJs() ,
617 " show : function(data, cb)",
619 " if (!this.dialog) {",
623 " this.callback = cb;",
624 " this.data = data;",
625 " this.dialog.show(this.data._el);",
627 " this.form.reset();",
628 " this.form.setValues(data);",
629 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
634 " create : function()",
636 " var _this = this;",
637 " this.dialog = Roo.factory("
644 return this.mungeToStringWrap(" ",
645 this.outputHeader() + "\n" +
646 this.name + "= function() {}\n" +
647 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
648 // body goes here from the function..
649 string.joinv("\n", addb) + ");\n" + // footer
650 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
661 public string pathToPart()
663 var dir = Path.get_basename(Path.get_dirname(this.path));
664 var ar = dir.split(".");
665 var modname = ar[ar.length-1];
667 // now we have the 'module name'..
668 var fbits = Path.get_basename(this.path).split(".");
671 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
672 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
673 npart = npart.substring(modname.length);
675 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
684 public string toSourceLayout(bool isPreview)
689 // topItem.region = 'center';
690 // topItem.background = false;
693 var modkey = this.modOrder + "-" + this.name;
695 var reg = new Regex("[^A-Za-z.]+");
697 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
698 } catch (RegexError e) {
701 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
706 // set to false to ensure this is the top level..
708 var topnode = this.tree.fqn();
709 print("topnode = %s\n", topnode);
710 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
711 topnode != "Roo.bootstrap.Body"
713 parent = "\"#bootstrap-body\"";
720 var pref = this.outputHeader() + "\n" +
722 this.name + " = new Roo.XComponent({\n" +
724 this.transStringsToJs() + "\n" +
726 " part : "+ this.pathToPart() + ",\n" +
727 /// critical used by builder to associate modules/parts/persm
728 " order : '" +modkey+"',\n" +
729 " region : '" + this.region +"',\n" +
730 " parent : "+ parent + ",\n" +
731 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
732 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
733 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
735 // " tree : function() { return this._tree(); },\n" + //BC
736 " _tree : function(_data)\n" +
738 " var _this = this;\n" + // bc
739 " var MODULE = this;\n" + /// this looks like a better name.
742 return this.mungeToStringWrap(" ", pref, ";" +
750 public new string? guessName (Node? ar) // turns the object into full name.
752 // eg. xns: Roo, xtype: XXX -> Roo.xxx
758 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
761 if ( ar.get("xtype").length < 1) {
765 var xtype = ar.get("xtype");
767 if (xtype[0] == '*') { // prefixes????
768 xtype = xtype.substring(1);
770 if (! Regex.match_simple("^Roo", xtype)) {
772 // already starts with roo...
776 var str = string.joinv(".", ret);
780 //Palete.Palete.factory("Roo").guessName(str);
786 string getHelpUrl(string cls)
788 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";