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) {
27 aconstruct( project, 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..
72 for (var i=0;i<dsp.length;i++) {
73 this.doubleStringProps.add(dsp[i]);
81 public override void removeFiles() {
82 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
83 if (FileUtils.test(html, FileTest.EXISTS)) {
84 GLib.FileUtils.remove(html);
86 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
87 if (FileUtils.test(js, FileTest.EXISTS)) {
88 GLib.FileUtils.remove(js);
92 public override void loadItems() throws GLib.Error // : function(cb, sync) == original was async.
96 GLib.debug("load Items!");
97 if (this.tree != null) {
100 GLib.debug("load " + this.path);
102 var pa = new Json.Parser();
103 pa.load_from_file(this.path);
104 var node = pa.get_root();
106 if (node.get_node_type () != Json.NodeType.OBJECT) {
107 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
109 var obj = node.get_object ();
112 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
113 this.name = this.jsonHasOrEmpty(obj, "name");
114 this.parent = this.jsonHasOrEmpty(obj, "parent");
115 this.permname = this.jsonHasOrEmpty(obj, "permname");
116 this.title = this.jsonHasOrEmpty(obj, "title");
117 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
119 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
120 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
123 // load items[0] ??? into tree...
124 if (obj.has_member("items")
126 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
128 obj.get_array_member("items").get_length() > 0
130 this.tree = new Node();
131 var ar = obj.get_array_member("items");
132 var tree_base = ar.get_object_element(0);
133 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
136 this.toSource(); // force it to number the lines...
141 public override string targetName()
145 Regex regex = new Regex("\\.(bjs|js)$");
147 js = regex.replace(this.path,this.path.length , 0 , ".js");
149 } catch (RegexError e) {
151 print("count not make filename from path");
152 return this.name + ".js";
156 public override void save()
159 GLib.debug("--- JsRender.Roo.save");
160 GLib.debug("save() - reset transStrings\n");
161 this.transStrings = new Gee.HashMap<string,string>();
162 this.namedStrings = new Gee.HashMap<string,string>();
163 this.findTransStrings(this.tree);
168 if (this.tree == null) {
171 // now write the js file..
172 var js = this.targetName();
176 //var d = new Date();
177 var js_src = this.toSource();
178 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
180 this.writeFile(js, js_src);
181 } catch (GLib.Error e ) {
182 print("Save failed\n");
184 // for bootstrap - we can write the HTML to the templates directory..
186 //var top = this.guessName(this.items[0]);
187 //print ("TOP = " + top)
197 public override void saveHTML ( string html )
199 GLib.debug ("SAVEHTML %s\n", this.project.runhtml);
200 if (this.project.runhtml == "") {
204 var top = this.tree.fqn();
205 GLib.debug ("TOP = " + top + "\n" );
206 if (top.index_of("Roo.bootstrap.") < 0 &&
207 top.index_of("Roo.mailer.") < 0
213 //now write the js file..
216 Regex regex = new Regex("\\.(bjs|js)$");
218 fn = regex.replace(this.path,this.path.length , 0 , ".html");
219 } catch (RegexError e) {
221 print("count not make filename from path");
224 var bn = GLib.Path.get_basename(fn);
225 var dn = GLib.Path.get_dirname(fn);
227 var targetdir = dn + (
228 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
231 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
232 print("Skip save - templates folder does not exist : %s\n", targetdir);
235 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
237 this.writeFile(targetdir + "/" + bn , html);
238 } catch (GLib.Error e ) {
239 print("SaveHtml failed\n");
246 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
249 if (node.props.has_key("* xinclude")) {
250 ret.add(node.props.get("* xinclude").val);
252 for (var i =0; i < node.items.size; i++) {
253 this.findxincludes(node.items.get(i), ret);
261 public override void findTransStrings(Node? node )
263 // iterate properties...
264 // use doubleStringProps
266 // flagging a translatable string..
267 // the code would use string _astring to indicate a translatable string
268 // the to use it it would do String.format(this._message, somedata);
270 // loop through and find string starting with '_'
275 var named = new Gee.HashMap<string,string>();
276 var name_prefix = "";
278 var iter = node.props.map_iterator();
279 while (iter.next()) {
280 // key formats : XXXX
282 // string XXX - with type
283 // $ XXX - with flag (no type)
284 // $ string XXX - with flag
287 var prop = iter.get_value();
288 var kname = prop.name;
289 var ktype = prop.rtype;
292 if (prop.ptype == NodePropType.RAW) {
295 // skip cms-id nodes...
296 if (kname == "html" && node.has("cms-id")) {
300 if (kname == "name") {
304 var chksum = GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip());
306 if (this.doubleStringProps.index_of(kname) > -1) {
307 GLib.debug("flag=%s type=%s name=%s : %s\n", prop.ptype.to_string(),ktype,kname,str);
308 this.transStrings.set(str, chksum);
309 named.set("_" + kname, chksum);
313 if (ktype.down() == "string" && kname[0] == '_') {
314 GLib.debug("flag=%s type=%s name=%s : %s\n", prop.ptype.to_string(),ktype,kname,str);
315 this.transStrings.set(str, chksum);
316 named.set(kname, chksum);
321 if (name_prefix != "") {
322 var niter = named.map_iterator();
323 while (niter.next()) {
324 this.namedStrings.set(name_prefix + niter.get_key(),niter.get_value());
329 // iterate children..
330 for (var i =0; i < node.items.size; i++) {
331 this.findTransStrings(node.items.get(i) );
337 public string transStringsToJs()
340 GLib.debug("Roo.transStringsToJs()\n");
341 if (this.transStrings.size < 1) {
342 GLib.debug("Roo.transStringsToJs() size < 1?\n");
348 var hash = new Gee.HashMap<string,string>();
349 var iter = this.transStrings.map_iterator();
350 while (iter.next()) {
351 hash.set(iter.get_value(), iter.get_key());
352 kvs += (" '" + iter.get_value() + "' :" +
353 this.tree.quoteString(iter.get_key())
357 var ret = " _strings : {\n" + string.joinv(",\n", kvs) + "\n },";
361 var niter = this.namedStrings.map_iterator();
362 while (niter.next()) {
363 var otext = hash.get(niter.get_value());
364 var com = " /* " + (otext.replace("*/", "* - /") + " */ ");
367 ns += (" '" + niter.get_key() + "' : '" + niter.get_value() + "'" + com);
369 if (ns.length > 0 ) {
370 ret += "\n _named_strings : {\n" + string.joinv(",\n", ns) + "\n },";
377 * javascript used in Webkit preview
380 public override string toSourcePreview()
382 print("toSourcePreview() - reset transStrings\n");
383 this.transStrings = new Gee.HashMap<string,string>();
384 this.namedStrings = new Gee.HashMap<string,string>();
386 print("to source preview\n");
387 if (this.tree == null) {
390 this.findTransStrings(this.tree);
391 var top = this.tree.fqn();
392 var xinc = new Gee.ArrayList<string>();
394 this.findxincludes(this.tree, xinc);
395 print("got %d xincludes\n", xinc.size);
396 var prefix_data = "";
397 if (xinc.size > 0 ) {
398 for(var i = 0; i < xinc.size; i++) {
399 print("check xinclude: %s\n", xinc.get(i));
400 var sf = this.project.getByName(xinc.get(i));
402 print("Failed to find file by name?\n");
407 sf.findTransStrings(sf.tree);
408 var xinc_str = sf.toSource();
411 //FileUtils.get_contents(js, out xinc_str);
412 prefix_data += "\n" + xinc_str + "\n";
413 } catch (GLib.Error e) {}
421 //print(JSON.stringify(this.items, null,4));
424 print ("guessname returned false");
429 if (top.contains("Dialog")) {
430 return prefix_data + this.toSourceDialog(true);
433 if (top.contains("Modal")) {
434 return prefix_data + this.toSourceModal(true);
436 if (top.contains("Popover")) {
437 return prefix_data + this.toSourceModal(true);
439 return prefix_data + this.toSourceLayout(true);
444 public override void setSource(string str) {}
446 * This needs to use some options on the project
447 * to determine how the file is output..
449 * At present we are hard coding it..
453 public override string toSourceCode()
455 this.transStrings = new Gee.HashMap<string,string>();
456 this.namedStrings = new Gee.HashMap<string,string>();
457 this.findTransStrings(this.tree);
458 return this.toSource();
461 public override string toSource()
463 // dump the file tree back out to a string.
465 // we have 2 types = dialogs and components
469 if (this.tree == null) {
472 var top = this.tree.fqn();
479 // get the translatable strings.. = we reload them again so calling methods get the right data...
480 this.transStrings = new Gee.HashMap<string,string>();
481 this.namedStrings = new Gee.HashMap<string,string>();
482 this.findTransStrings(this.tree);
485 if (top.contains("Dialog")) {
486 return this.toSourceDialog(false);
489 if (top.contains("Modal")) {
490 return this.toSourceModal(false);
493 if (top.contains("Popover")) {
494 return this.toSourceModal(false);
497 return this.toSourceLayout(false);
500 eventually support 'classes??'
501 return this.toSourceStdClass();
508 * munge JSON tree into Javascript code.
510 * NOTE - needs a deep copy of original tree, before starting..
511 * - so that it does not modify current..
513 * FIXME: + or / prefixes to properties hide it from renderer.
514 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
515 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
517 * @arg {object} obj the object or array to munge..
518 * @arg {boolean} isListener - is the array being sent a listener..
519 * @arg {string} pad - the padding to indent with.
522 public string mungeToStringWrap(string pad, string prefix, string suffix)
524 if (this.tree == null) {
527 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
529 x.cur_line = prefix.split("\n").length;
534 // output both files.. so we can diff them...
535 //this.writeFile("/tmp/old.js", ret);
536 //this.writeFile("/tmp/new.js", nret);
537 return prefix + ret + suffix;
544 public string outputHeader()
547 "//<script type=\"text/javascript\">",
549 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
553 var ret= string.joinv("\n",s);
554 var bits = this.name.split(".");
555 if (bits.length > 1) {
556 ret += "\nRoo.namespace(\'" +
557 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
561 /// genericlly used..
567 // a standard dialog module.
568 // fixme - this could be alot neater..
569 public string toSourceDialog(bool isPreview)
572 //var items = JSON.parse(JSON.stringify(this.items[0]));
577 string[] adda = { " = {",
579 this.transStringsToJs() ,
584 " show : function(data, cb)",
586 " if (!this.dialog) {",
590 " this.callback = cb;",
591 " this.data = data;",
592 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
594 " this.form.reset();",
595 " this.form.setValues(data);",
596 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
601 " create : function()",
603 " var _this = this;",
604 " this.dialog = Roo.factory("
613 return this.mungeToStringWrap(" ",
614 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
615 string.joinv("\n", addb) // footer
623 Bootstrap modal dialog
628 public string toSourceModal(bool isPreview)
632 //var items = JSON.parse(JSON.stringify(this.items[0]));
642 XXXX = function() {};
643 Roo.apply(XXXX.prototype, { .... });
644 Roo.apply(XXXX, XXX.prototype);
648 string[] adda = { "{",
650 this.transStringsToJs() ,
655 " show : function(data, cb)",
657 " if (!this.dialog) {",
661 " this.callback = cb;",
662 " this.data = data;",
663 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
665 " this.form.reset();",
666 " this.form.setValues(data);",
667 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
672 " create : function()",
674 " var _this = this;",
675 " this.dialog = Roo.factory("
682 return this.mungeToStringWrap(" ",
683 this.outputHeader() + "\n" +
684 this.name + "= function() {}\n" +
685 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
686 // body goes here from the function..
687 string.joinv("\n", addb) + ");\n" + // footer
688 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
699 public string pathToPart()
701 var dir = Path.get_basename(Path.get_dirname(this.path));
702 var ar = dir.split(".");
703 var modname = ar[ar.length-1];
705 // now we have the 'module name'..
706 var fbits = Path.get_basename(this.path).split(".");
709 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
710 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
711 npart = npart.substring(modname.length);
713 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
722 public string toSourceLayout(bool isPreview)
727 // topItem.region = 'center';
728 // topItem.background = false;
731 var modkey = this.modOrder + "-" + this.name;
733 var reg = new Regex("[^A-Za-z.]+");
735 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
736 } catch (RegexError e) {
739 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
744 // set to false to ensure this is the top level..
746 var topnode = this.tree.fqn();
747 print("topnode = %s\n", topnode);
748 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
749 topnode != "Roo.bootstrap.Body"
751 parent = "\"#bootstrap-body\"";
758 var pref = this.outputHeader() + "\n" +
760 this.name + " = new Roo.XComponent({\n" +
762 this.transStringsToJs() + "\n" +
764 " part : "+ this.pathToPart() + ",\n" +
765 /// critical used by builder to associate modules/parts/persm
766 " order : '" +modkey+"',\n" +
767 " region : '" + this.region +"',\n" +
768 " parent : "+ parent + ",\n" +
769 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
770 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
771 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
773 // " tree : function() { return this._tree(); },\n" + //BC
774 " _tree : function(_data)\n" +
776 " var _this = this;\n" + // bc
777 " var MODULE = this;\n" + /// this looks like a better name.
780 return this.mungeToStringWrap(" ", pref, ";" +
789 public override string toGlade()
791 return "Roo files do not convert to glade";