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.Roo project, string path)
28 aconstruct( project, path);
33 this.content_type = "";
37 // var jstr = JSON.parse(cfg.json);
38 // this.items = [ jstr ];
39 // //console.log(cfg.items.length);
40 // delete cfg.json; // not needed!
42 this.modOrder = "001"; /// sequence id that this uses.
43 this.region = "center";
44 this.disabled = false;
47 this.id = "file-roo-%d".printf(rid++);
49 // 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");
118 if (obj.has_member("gen_extended")) { // should check type really..
119 this.gen_extended = obj.get_boolean_member("gen_extended");
121 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
122 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
125 // load items[0] ??? into tree...
126 if (obj.has_member("items")
128 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
130 obj.get_array_member("items").get_length() > 0
132 this.tree = new Node();
133 var ar = obj.get_array_member("items");
134 var tree_base = ar.get_object_element(0);
135 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
138 this.toSource(); // force it to number the lines...
143 public override string targetName()
147 Regex regex = new Regex("\\.(bjs|js)$");
149 js = regex.replace(this.path,this.path.length , 0 , ".js");
151 } catch (RegexError e) {
153 print("count not make filename from path");
154 return this.name + ".js";
158 public override void save()
161 GLib.debug("--- JsRender.Roo.save");
162 GLib.debug("save() - reset transStrings\n");
163 this.transStrings = new Gee.HashMap<string,string>();
164 this.namedStrings = new Gee.HashMap<string,string>();
165 this.findTransStrings(this.tree);
170 if (this.tree == null) {
173 // now write the js file..
174 var js = this.targetName();
178 //var d = new Date();
179 var js_src = this.toSource();
180 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
182 this.writeFile(js, js_src);
183 } catch (GLib.Error e ) {
184 print("Save failed\n");
186 // for bootstrap - we can write the HTML to the templates directory..
188 //var top = this.guessName(this.items[0]);
189 //print ("TOP = " + top)
196 public Project.Roo roo_project {
199 return (Project.Roo) this.project;
205 public override void saveHTML ( string html )
207 GLib.debug ("SAVEHTML %s\n", this.roo_project.runhtml);
208 if (this.roo_project.runhtml == "") {
212 var top = this.tree.fqn();
213 GLib.debug ("TOP = " + top + "\n" );
214 if (top.index_of("Roo.bootstrap.") < 0 &&
215 top.index_of("Roo.mailer.") < 0
221 //now write the js file..
224 Regex regex = new Regex("\\.(bjs|js)$");
226 fn = regex.replace(this.path,this.path.length , 0 , ".html");
227 } catch (RegexError e) {
229 print("count not make filename from path");
232 var bn = GLib.Path.get_basename(fn);
233 var dn = GLib.Path.get_dirname(fn);
235 var targetdir = dn + (
236 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
239 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
240 print("Skip save - templates folder does not exist : %s\n", targetdir);
243 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
245 this.writeFile(targetdir + "/" + bn , html);
246 } catch (GLib.Error e ) {
247 print("SaveHtml failed\n");
254 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
257 if (node.props.has_key("* xinclude")) {
258 ret.add(node.props.get("* xinclude").val);
260 var items = node.readItems();
261 for (var i =0; i < items.size; i++) {
262 this.findxincludes(items.get(i), ret);
270 public override void findTransStrings(Node? node )
272 // iterate properties...
273 // use doubleStringProps
275 // flagging a translatable string..
276 // the code would use string _astring to indicate a translatable string
277 // the to use it it would do String.format(this._message, somedata);
279 // loop through and find string starting with '_'
284 var named = new Gee.HashMap<string,string>();
285 var name_prefix = "";
287 var iter = node.props.map_iterator();
288 while (iter.next()) {
289 // key formats : XXXX
291 // string XXX - with type
292 // $ XXX - with flag (no type)
293 // $ string XXX - with flag
296 var prop = iter.get_value();
297 var kname = prop.name;
298 var ktype = prop.rtype;
301 if (prop.ptype == NodePropType.RAW) {
304 // skip cms-id nodes...
305 if (kname == "html" && node.has("cms-id")) {
309 if (kname == "name") {
313 var chksum = GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip());
315 if (this.doubleStringProps.index_of(kname) > -1) {
316 //GLib.debug("flag=%s type=%s name=%s : %s\n", prop.ptype.to_string(),ktype,kname,str);
317 this.transStrings.set(str, chksum);
318 named.set("_" + kname, chksum);
322 if (ktype.down() == "string" && kname[0] == '_') {
323 GLib.debug("flag=%s type=%s name=%s : %s\n", prop.ptype.to_string(),ktype,kname,str);
324 this.transStrings.set(str, chksum);
325 named.set(kname, chksum);
330 if (name_prefix != "") {
331 var niter = named.map_iterator();
332 while (niter.next()) {
333 this.namedStrings.set(name_prefix + niter.get_key(),niter.get_value());
337 var items = node.readItems();
338 // iterate children..
339 for (var i =0; i < items.size; i++) {
340 this.findTransStrings(items.get(i) );
346 public string transStringsToJs()
349 GLib.debug("Roo.transStringsToJs()\n");
350 if (this.transStrings.size < 1) {
351 GLib.debug("Roo.transStringsToJs() size < 1?\n");
357 var hash = new Gee.HashMap<string,string>();
358 var iter = this.transStrings.map_iterator();
359 while (iter.next()) {
360 hash.set(iter.get_value(), iter.get_key());
361 kvs += (" '" + iter.get_value() + "' :" +
362 this.tree.quoteString(iter.get_key())
366 var ret = " _strings : {\n" + string.joinv(",\n", kvs) + "\n },";
370 var niter = this.namedStrings.map_iterator();
371 while (niter.next()) {
372 var otext = hash.get(niter.get_value());
373 var com = " /* " + (otext.replace("*/", "* - /") + " */ ");
376 ns += (" '" + niter.get_key() + "' : '" + niter.get_value() + "'" + com);
378 if (ns.length > 0 ) {
379 ret += "\n _named_strings : {\n" + string.joinv(",\n", ns) + "\n },";
386 * javascript used in Webkit preview
389 public override string toSourcePreview()
391 print("toSourcePreview() - reset transStrings\n");
392 this.transStrings = new Gee.HashMap<string,string>();
393 this.namedStrings = new Gee.HashMap<string,string>();
395 print("to source preview\n");
396 if (this.tree == null) {
399 this.findTransStrings(this.tree);
400 var top = this.tree.fqn();
401 var xinc = new Gee.ArrayList<string>();
403 this.findxincludes(this.tree, xinc);
404 print("got %d xincludes\n", xinc.size);
405 var prefix_data = "";
406 if (xinc.size > 0 ) {
407 for(var i = 0; i < xinc.size; i++) {
408 print("check xinclude: %s\n", xinc.get(i));
409 var sf = this.project.getByName(xinc.get(i));
411 print("Failed to find file by name?\n");
416 sf.findTransStrings(sf.tree);
417 var xinc_str = sf.toSource();
420 //FileUtils.get_contents(js, out xinc_str);
421 prefix_data += "\n" + xinc_str + "\n";
422 } catch (GLib.Error e) {}
430 //print(JSON.stringify(this.items, null,4));
433 print ("guessname returned false");
438 if (top.contains("Dialog")) {
439 return prefix_data + this.toSourceDialog(true);
442 if (top.contains("Modal")) {
443 return prefix_data + this.toSourceModal(true);
445 if (top.contains("Popover")) {
446 return prefix_data + this.toSourceModal(true);
448 return prefix_data + this.toSourceLayout(true);
453 public override void setSource(string str) {}
455 * This needs to use some options on the project
456 * to determine how the file is output..
458 * At present we are hard coding it..
462 public override string toSourceCode()
464 this.transStrings = new Gee.HashMap<string,string>();
465 this.namedStrings = new Gee.HashMap<string,string>();
466 this.findTransStrings(this.tree);
467 return this.toSource();
470 public override string toSource()
472 // dump the file tree back out to a string.
474 // we have 2 types = dialogs and components
478 if (this.tree == null) {
481 var top = this.tree.fqn();
488 // get the translatable strings.. = we reload them again so calling methods get the right data...
489 this.transStrings = new Gee.HashMap<string,string>();
490 this.namedStrings = new Gee.HashMap<string,string>();
491 this.findTransStrings(this.tree);
494 if (top.contains("Dialog")) {
495 return this.toSourceDialog(false);
498 if (top.contains("Modal")) {
499 return this.toSourceModal(false);
502 if (top.contains("Popover")) {
503 return this.toSourceModal(false);
506 return this.toSourceLayout(false);
509 eventually support 'classes??'
510 return this.toSourceStdClass();
517 * munge JSON tree into Javascript code.
519 * NOTE - needs a deep copy of original tree, before starting..
520 * - so that it does not modify current..
522 * FIXME: + or / prefixes to properties hide it from renderer.
523 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
524 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
526 * @arg {object} obj the object or array to munge..
527 * @arg {boolean} isListener - is the array being sent a listener..
528 * @arg {string} pad - the padding to indent with.
531 public string mungeToStringWrap(string pad, string prefix, string suffix)
533 if (this.tree == null) {
536 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
538 x.cur_line = prefix.split("\n").length;
543 // output both files.. so we can diff them...
544 //this.writeFile("/tmp/old.js", ret);
545 //this.writeFile("/tmp/new.js", nret);
546 return prefix + ret + suffix;
553 public string outputHeader()
556 "//<script type=\"text/javascript\">",
558 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
562 var ret= string.joinv("\n",s);
563 var bits = this.name.split(".");
564 if (bits.length > 1) {
565 ret += "\nRoo.namespace(\'" +
566 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
570 /// genericlly used..
576 // a standard dialog module.
577 // fixme - this could be alot neater..
578 public string toSourceDialog(bool isPreview)
581 //var items = JSON.parse(JSON.stringify(this.items[0]));
586 string[] adda = { " = {",
588 this.transStringsToJs() ,
593 " show : function(data, cb)",
595 " if (!this.dialog) {",
599 " this.callback = cb;",
600 " this.data = data;",
601 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
603 " this.form.reset();",
604 " this.form.setValues(data);",
605 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
610 " create : function()",
612 " var _this = this;",
613 " this.dialog = Roo.factory("
622 return this.mungeToStringWrap(" ",
623 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
624 string.joinv("\n", addb) // footer
632 Bootstrap modal dialog
637 public string toSourceModal(bool isPreview)
641 //var items = JSON.parse(JSON.stringify(this.items[0]));
651 XXXX = function() {};
652 Roo.apply(XXXX.prototype, { .... });
653 Roo.apply(XXXX, XXX.prototype);
657 string[] adda = { "{",
659 this.transStringsToJs() ,
664 " show : function(data, cb)",
666 " if (!this.dialog) {",
670 " this.callback = cb;",
671 " this.data = data;",
672 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
674 " this.form.reset();",
675 " this.form.setValues(data);",
676 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
681 " create : function()",
683 " var _this = this;",
684 " this.dialog = Roo.factory("
691 return this.mungeToStringWrap(" ",
692 this.outputHeader() + "\n" +
693 this.name + "= function() {}\n" +
694 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
695 // body goes here from the function..
696 string.joinv("\n", addb) + ");\n" + // footer
697 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
708 public string pathToPart()
710 var dir = Path.get_basename(Path.get_dirname(this.path));
711 var ar = dir.split(".");
712 var modname = ar[ar.length-1];
714 // now we have the 'module name'..
715 var fbits = Path.get_basename(this.path).split(".");
718 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
719 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
720 npart = npart.substring(modname.length);
722 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
731 public string toSourceLayout(bool isPreview)
736 // topItem.region = 'center';
737 // topItem.background = false;
740 var modkey = this.modOrder + "-" + this.name;
742 var reg = new Regex("[^A-Za-z.]+");
744 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
745 } catch (RegexError e) {
748 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
753 // set to false to ensure this is the top level..
755 var topnode = this.tree.fqn();
756 print("topnode = %s\n", topnode);
757 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
758 topnode != "Roo.bootstrap.Body"
760 parent = "\"#bootstrap-body\"";
767 var pref = this.outputHeader() + "\n" +
769 this.name + " = new Roo.XComponent({\n" +
771 this.transStringsToJs() + "\n" +
773 " part : "+ this.pathToPart() + ",\n" +
774 /// critical used by builder to associate modules/parts/persm
775 " order : '" +modkey+"',\n" +
776 " region : '" + this.region +"',\n" +
777 " parent : "+ parent + ",\n" +
778 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
779 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
780 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
782 // " tree : function() { return this._tree(); },\n" + //BC
783 " _tree : function(_data)\n" +
785 " var _this = this;\n" + // bc
786 " var MODULE = this;\n" + /// this looks like a better name.
789 return this.mungeToStringWrap(" ", pref, ";" +
798 public override string toGlade()
800 return "Roo files do not convert to glade";