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..
66 for (var i=0;i<dsp.length;i++) {
67 this.doubleStringProps.add(dsp[i]);
75 public override void removeFiles() {
76 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
77 if (FileUtils.test(html, FileTest.EXISTS)) {
78 GLib.FileUtils.remove(html);
80 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
81 if (FileUtils.test(js, FileTest.EXISTS)) {
82 GLib.FileUtils.remove(js);
86 public override void loadItems() throws GLib.Error // : function(cb, sync) == original was async.
90 GLib.debug("load Items!");
91 if (this.tree != null) {
94 GLib.debug("load " + this.path);
96 var pa = new Json.Parser();
97 pa.load_from_file(this.path);
98 var node = pa.get_root();
100 if (node.get_node_type () != Json.NodeType.OBJECT) {
101 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
103 var obj = node.get_object ();
106 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
107 this.name = this.jsonHasOrEmpty(obj, "name");
108 this.parent = this.jsonHasOrEmpty(obj, "parent");
109 this.permname = this.jsonHasOrEmpty(obj, "permname");
110 this.title = this.jsonHasOrEmpty(obj, "title");
111 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
113 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
114 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
117 // load items[0] ??? into tree...
118 if (obj.has_member("items")
120 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
122 obj.get_array_member("items").get_length() > 0
124 this.tree = new Node();
125 var ar = obj.get_array_member("items");
126 var tree_base = ar.get_object_element(0);
127 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
130 this.toSource(); // force it to number the lines...
136 public override void save()
139 GLib.debug("--- JsRender.Roo.save");
140 GLib.debug("save() - reset transStrings\n");
141 this.transStrings = new Gee.HashMap<string,string>();
142 this.findTransStrings(this.tree);
147 if (this.tree == null) {
150 // now write the js file..
153 Regex regex = new Regex("\\.(bjs|js)$");
155 js = regex.replace(this.path,this.path.length , 0 , ".js");
156 } catch (RegexError e) {
158 print("count not make filename from path");
163 //var d = new Date();
164 var js_src = this.toSource();
165 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
167 this.writeFile(js, js_src);
168 } catch (FileError e ) {
169 print("Save failed\n");
171 // for bootstrap - we can write the HTML to the templates directory..
173 //var top = this.guessName(this.items[0]);
174 //print ("TOP = " + top)
184 public override void saveHTML ( string html )
186 GLib.debug ("SAVEHTML %s\n", this.project.runhtml);
187 if (this.project.runhtml == "") {
191 var top = this.tree.fqn();
192 GLib.debug ("TOP = " + top + "\n" );
193 if (top.index_of("Roo.bootstrap.") < 0 &&
194 top.index_of("Roo.mailer.") < 0
200 //now write the js file..
203 Regex regex = new Regex("\\.(bjs|js)$");
205 fn = regex.replace(this.path,this.path.length , 0 , ".html");
206 } catch (RegexError e) {
208 print("count not make filename from path");
211 var bn = GLib.Path.get_basename(fn);
212 var dn = GLib.Path.get_dirname(fn);
214 var targetdir = dn + (
215 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
218 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
219 print("Skip save - templates folder does not exist : %s\n", targetdir);
222 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
224 this.writeFile(targetdir + "/" + bn , html);
225 } catch (FileError e ) {
226 print("SaveHtml failed\n");
233 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
236 if (node.props.has_key("* xinclude")) {
237 ret.add(node.props.get("* xinclude"));
239 for (var i =0; i < node.items.size; i++) {
240 this.findxincludes(node.items.get(i), ret);
248 public override void findTransStrings(Node? node )
250 // iterate properties...
251 // use doubleStringProps
253 // flagging a translatable string..
254 // the code would use string _astring to indicate a translatable string
255 // the to use it it would do String.format(this._message, somedata);
257 // loop through and find string starting with '_'
262 var iter = node.props.map_iterator();
263 while (iter.next()) {
264 // key formats : XXXX
266 // string XXX - with type
267 // $ XXX - with flag (no type)
268 // $ string XXX - with flag
272 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
276 // skip cms-id nodes...
277 if (kname == "html" && node.has("cms-id")) {
281 var str = iter.get_value();
282 if (this.doubleStringProps.index_of(kname) > -1) {
283 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
284 this.transStrings.set(str,
285 GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip())
290 if (ktype.down() == "string" && kname[0] == '_') {
291 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
292 this.transStrings.set(str,
293 GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip())
302 // iterate children..
303 for (var i =0; i < node.items.size; i++) {
304 this.findTransStrings(node.items.get(i) );
310 public string transStringsToJs()
313 GLib.debug("Roo.transStringsToJs()\n");
314 if (this.transStrings.size < 1) {
315 GLib.debug("Roo.transStringsToJs() size < 1?\n");
320 var iter = this.transStrings.map_iterator();
321 while (iter.next()) {
322 kvs += (" '" + iter.get_value() + "' :" +
323 this.tree.quoteString(iter.get_key())
326 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
335 * javascript used in Webkit preview
338 public override string toSourcePreview()
340 print("toSourcePreview() - reset transStrings\n");
341 this.transStrings = new Gee.HashMap<string,string>();
344 print("to source preview\n");
345 if (this.tree == null) {
348 this.findTransStrings(this.tree);
349 var top = this.tree.fqn();
350 var xinc = new Gee.ArrayList<string>();
352 this.findxincludes(this.tree, xinc);
353 print("got %d xincludes\n", xinc.size);
354 var prefix_data = "";
355 if (xinc.size > 0 ) {
356 for(var i = 0; i < xinc.size; i++) {
357 print("check xinclude: %s\n", xinc.get(i));
358 var sf = this.project.getByName(xinc.get(i));
360 print("Failed to find file by name?\n");
365 sf.findTransStrings(sf.tree);
366 var xinc_str = sf.toSource();
369 //FileUtils.get_contents(js, out xinc_str);
370 prefix_data += "\n" + xinc_str + "\n";
378 //print(JSON.stringify(this.items, null,4));
381 print ("guessname returned false");
386 if (top.contains("Dialog")) {
387 return prefix_data + this.toSourceDialog(true);
390 if (top.contains("Modal")) {
391 return prefix_data + this.toSourceModal(true);
394 return prefix_data + this.toSourceLayout(true);
399 public override void setSource(string str) {}
401 * This needs to use some options on the project
402 * to determine how the file is output..
404 * At present we are hard coding it..
408 public override string toSourceCode()
410 this.transStrings = new Gee.HashMap<string,string>();
411 this.findTransStrings(this.tree);
412 return this.toSource();
415 public override string toSource()
417 // dump the file tree back out to a string.
419 // we have 2 types = dialogs and components
423 if (this.tree == null) {
426 var top = this.tree.fqn();
433 // get the translatable strings.. = we reload them again so calling methods get the right data...
434 this.transStrings = new Gee.HashMap<string,string>();
435 this.findTransStrings(this.tree);
438 if (top.contains("Dialog")) {
439 return this.toSourceDialog(false);
442 if (top.contains("Modal")) {
443 return this.toSourceModal(false);
445 return this.toSourceLayout(false);
448 eventually support 'classes??'
449 return this.toSourceStdClass();
456 * munge JSON tree into Javascript code.
458 * NOTE - needs a deep copy of original tree, before starting..
459 * - so that it does not modify current..
461 * FIXME: + or / prefixes to properties hide it from renderer.
462 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
463 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
465 * @arg {object} obj the object or array to munge..
466 * @arg {boolean} isListener - is the array being sent a listener..
467 * @arg {string} pad - the padding to indent with.
470 public string mungeToStringWrap(string pad, string prefix, string suffix)
472 if (this.tree == null) {
475 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
477 x.cur_line = prefix.split("\n").length;
482 // output both files.. so we can diff them...
483 //this.writeFile("/tmp/old.js", ret);
484 //this.writeFile("/tmp/new.js", nret);
485 return prefix + ret + suffix;
492 public string outputHeader()
495 "//<script type=\"text/javascript\">",
497 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
501 var ret= string.joinv("\n",s);
502 var bits = this.name.split(".");
503 if (bits.length > 1) {
504 ret += "\nRoo.namespace(\'" +
505 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
509 /// genericlly used..
515 // a standard dialog module.
516 // fixme - this could be alot neater..
517 public string toSourceDialog(bool isPreview)
520 //var items = JSON.parse(JSON.stringify(this.items[0]));
525 string[] adda = { " = {",
527 this.transStringsToJs() ,
532 " show : function(data, cb)",
534 " if (!this.dialog) {",
538 " this.callback = cb;",
539 " this.data = data;",
540 " this.dialog.show(this.data._el);",
542 " this.form.reset();",
543 " this.form.setValues(data);",
544 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
549 " create : function()",
551 " var _this = this;",
552 " this.dialog = Roo.factory("
561 return this.mungeToStringWrap(" ",
562 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
563 string.joinv("\n", addb) // footer
571 Bootstrap modal dialog
576 public string toSourceModal(bool isPreview)
580 //var items = JSON.parse(JSON.stringify(this.items[0]));
590 XXXX = function() {};
591 Roo.apply(XXXX.prototype, { .... });
592 Roo.apply(XXXX, XXX.prototype);
596 string[] adda = { "{",
598 this.transStringsToJs() ,
603 " show : function(data, cb)",
605 " if (!this.dialog) {",
609 " this.callback = cb;",
610 " this.data = data;",
611 " this.dialog.show(this.data._el);",
613 " this.form.reset();",
614 " this.form.setValues(data);",
615 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
620 " create : function()",
622 " var _this = this;",
623 " this.dialog = Roo.factory("
630 return this.mungeToStringWrap(" ",
631 this.outputHeader() + "\n" +
632 this.name + "= function() {}\n" +
633 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
634 // body goes here from the function..
635 string.joinv("\n", addb) + ");\n" + // footer
636 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
647 public string pathToPart()
649 var dir = Path.get_basename(Path.get_dirname(this.path));
650 var ar = dir.split(".");
651 var modname = ar[ar.length-1];
653 // now we have the 'module name'..
654 var fbits = Path.get_basename(this.path).split(".");
657 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
658 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
659 npart = npart.substring(modname.length);
661 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
670 public string toSourceLayout(bool isPreview)
675 // topItem.region = 'center';
676 // topItem.background = false;
679 var modkey = this.modOrder + "-" + this.name;
681 var reg = new Regex("[^A-Za-z.]+");
683 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
684 } catch (RegexError e) {
687 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
692 // set to false to ensure this is the top level..
694 var topnode = this.tree.fqn();
695 print("topnode = %s\n", topnode);
696 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
697 topnode != "Roo.bootstrap.Body"
699 parent = "\"#bootstrap-body\"";
706 var pref = this.outputHeader() + "\n" +
708 this.name + " = new Roo.XComponent({\n" +
710 this.transStringsToJs() + "\n" +
712 " part : "+ this.pathToPart() + ",\n" +
713 /// critical used by builder to associate modules/parts/persm
714 " order : '" +modkey+"',\n" +
715 " region : '" + this.region +"',\n" +
716 " parent : "+ parent + ",\n" +
717 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
718 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
719 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
721 // " tree : function() { return this._tree(); },\n" + //BC
722 " _tree : function(_data)\n" +
724 " var _this = this;\n" + // bc
725 " var MODULE = this;\n" + /// this looks like a better name.
728 return this.mungeToStringWrap(" ", pref, ";" +
736 public new string? guessName (Node? ar) // turns the object into full name.
738 // eg. xns: Roo, xtype: XXX -> Roo.xxx
744 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
747 if ( ar.get("xtype").length < 1) {
751 var xtype = ar.get("xtype");
753 if (xtype[0] == '*') { // prefixes????
754 xtype = xtype.substring(1);
756 if (! Regex.match_simple("^Roo", xtype)) {
758 // already starts with roo...
762 var str = string.joinv(".", ret);
766 //Palete.Palete.factory("Roo").guessName(str);
772 string getHelpUrl(string cls)
774 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";