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)
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.getByRelPath(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) {
537 var x = new NodeToJs( this, this.tree, pad , null, this.doubleStringProps);
538 x.addMultiLine(prefix, false);
547 public string outputHeader()
550 "//<script type=\"text/javascript\">",
552 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
556 var ret= string.joinv("\n",s);
557 var bits = this.name.split(".");
558 if (bits.length > 1) {
559 ret += "\nRoo.namespace(\'" +
560 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
564 /// genericlly used..
570 // a standard dialog module.
571 // fixme - this could be alot neater..
572 public string toSourceDialog(bool isPreview)
575 //var items = JSON.parse(JSON.stringify(this.items[0]));
580 string[] adda = { " = {",
582 this.transStringsToJs() ,
587 " show : function(data, cb)",
589 " if (!this.dialog) {",
593 " this.callback = cb;",
594 " this.data = data;",
595 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
597 " this.form.reset();",
598 " this.form.setValues(data);",
599 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
604 " create : function()",
606 " var _this = this;",
607 " this.dialog = Roo.factory("
616 return this.mungeToStringWrap(" ",
617 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
618 string.joinv("\n", addb) // footer
626 Bootstrap modal dialog
631 public string toSourceModal(bool isPreview)
635 //var items = JSON.parse(JSON.stringify(this.items[0]));
645 XXXX = function() {};
646 Roo.apply(XXXX.prototype, { .... });
647 Roo.apply(XXXX, XXX.prototype);
651 string[] adda = { "{",
653 this.transStringsToJs() ,
658 " show : function(data, cb)",
660 " if (!this.dialog) {",
664 " this.callback = cb;",
665 " this.data = data;",
666 " this.dialog.show.apply(this.dialog, Array.prototype.slice.call(arguments).slice(2));",
668 " this.form.reset();",
669 " this.form.setValues(data);",
670 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
675 " create : function()",
677 " var _this = this;",
678 " this.dialog = Roo.factory("
685 return this.mungeToStringWrap(" ",
686 this.outputHeader() + "\n" +
687 this.name + "= function() {}\n" +
688 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
689 // body goes here from the function..
690 string.joinv("\n", addb) + ");\n" + // footer
691 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
702 public string pathToPart()
704 var dir = Path.get_basename(Path.get_dirname(this.path));
705 var ar = dir.split(".");
706 var modname = ar[ar.length-1];
708 // now we have the 'module name'..
709 var fbits = Path.get_basename(this.path).split(".");
712 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
713 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
714 npart = npart.substring(modname.length);
716 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
725 public string toSourceLayout(bool isPreview)
730 // topItem.region = 'center';
731 // topItem.background = false;
734 var modkey = this.modOrder + "-" + this.name;
736 var reg = new Regex("[^A-Za-z.]+");
738 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
739 } catch (RegexError e) {
742 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
747 // set to false to ensure this is the top level..
749 var topnode = this.tree.fqn();
750 print("topnode = %s\n", topnode);
751 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
752 topnode != "Roo.bootstrap.Body"
754 parent = "\"#bootstrap-body\"";
761 var pref = this.outputHeader() + "\n" +
763 this.name + " = new Roo.XComponent({\n" +
765 this.transStringsToJs() + "\n" +
767 " part : "+ this.pathToPart() + ",\n" +
768 /// critical used by builder to associate modules/parts/persm
769 " order : '" +modkey+"',\n" +
770 " region : '" + this.region +"',\n" +
771 " parent : "+ parent + ",\n" +
772 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
773 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
774 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
776 // " tree : function() { return this._tree(); },\n" + //BC
777 " _tree : function(_data)\n" +
779 " var _this = this;\n" + // bc
780 " var MODULE = this;\n" + /// this looks like a better name.
783 return this.mungeToStringWrap(" ", pref, ";" +
792 public override string toGlade()
794 return "Roo files do not convert to glade";
796 public override string language_id()