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..
70 for (var i=0;i<dsp.length;i++) {
71 this.doubleStringProps.add(dsp[i]);
79 public override void removeFiles() {
80 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
81 if (FileUtils.test(html, FileTest.EXISTS)) {
82 GLib.FileUtils.remove(html);
84 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
85 if (FileUtils.test(js, FileTest.EXISTS)) {
86 GLib.FileUtils.remove(js);
90 public override void loadItems() throws GLib.Error // : function(cb, sync) == original was async.
94 GLib.debug("load Items!");
95 if (this.tree != null) {
98 GLib.debug("load " + this.path);
100 var pa = new Json.Parser();
101 pa.load_from_file(this.path);
102 var node = pa.get_root();
104 if (node.get_node_type () != Json.NodeType.OBJECT) {
105 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
107 var obj = node.get_object ();
110 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
111 this.name = this.jsonHasOrEmpty(obj, "name");
112 this.parent = this.jsonHasOrEmpty(obj, "parent");
113 this.permname = this.jsonHasOrEmpty(obj, "permname");
114 this.title = this.jsonHasOrEmpty(obj, "title");
115 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
117 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
118 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
121 // load items[0] ??? into tree...
122 if (obj.has_member("items")
124 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
126 obj.get_array_member("items").get_length() > 0
128 this.tree = new Node();
129 var ar = obj.get_array_member("items");
130 var tree_base = ar.get_object_element(0);
131 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
134 this.toSource(); // force it to number the lines...
140 public override void save()
143 GLib.debug("--- JsRender.Roo.save");
144 GLib.debug("save() - reset transStrings\n");
145 this.transStrings = new Gee.HashMap<string,string>();
146 this.namedStrings = new Gee.HashMap<string,string>();
147 this.findTransStrings(this.tree);
152 if (this.tree == null) {
155 // now write the js file..
158 Regex regex = new Regex("\\.(bjs|js)$");
160 js = regex.replace(this.path,this.path.length , 0 , ".js");
161 } catch (RegexError e) {
163 print("count not make filename from path");
168 //var d = new Date();
169 var js_src = this.toSource();
170 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
172 this.writeFile(js, js_src);
173 } catch (FileError e ) {
174 print("Save failed\n");
176 // for bootstrap - we can write the HTML to the templates directory..
178 //var top = this.guessName(this.items[0]);
179 //print ("TOP = " + top)
189 public override void saveHTML ( string html )
191 GLib.debug ("SAVEHTML %s\n", this.project.runhtml);
192 if (this.project.runhtml == "") {
196 var top = this.tree.fqn();
197 GLib.debug ("TOP = " + top + "\n" );
198 if (top.index_of("Roo.bootstrap.") < 0 &&
199 top.index_of("Roo.mailer.") < 0
205 //now write the js file..
208 Regex regex = new Regex("\\.(bjs|js)$");
210 fn = regex.replace(this.path,this.path.length , 0 , ".html");
211 } catch (RegexError e) {
213 print("count not make filename from path");
216 var bn = GLib.Path.get_basename(fn);
217 var dn = GLib.Path.get_dirname(fn);
219 var targetdir = dn + (
220 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
223 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
224 print("Skip save - templates folder does not exist : %s\n", targetdir);
227 print("SAVE HTML (%d) -- %s\n",html.length, targetdir + "/" + bn);
229 this.writeFile(targetdir + "/" + bn , html);
230 } catch (FileError e ) {
231 print("SaveHtml failed\n");
238 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
241 if (node.props.has_key("* xinclude")) {
242 ret.add(node.props.get("* xinclude"));
244 for (var i =0; i < node.items.size; i++) {
245 this.findxincludes(node.items.get(i), ret);
253 public override void findTransStrings(Node? node )
255 // iterate properties...
256 // use doubleStringProps
258 // flagging a translatable string..
259 // the code would use string _astring to indicate a translatable string
260 // the to use it it would do String.format(this._message, somedata);
262 // loop through and find string starting with '_'
267 var named = new Gee.HashMap<string,string>();
268 var name_prefix = "";
270 var iter = node.props.map_iterator();
271 while (iter.next()) {
272 // key formats : XXXX
274 // string XXX - with type
275 // $ XXX - with flag (no type)
276 // $ string XXX - with flag
280 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
284 // skip cms-id nodes...
285 if (kname == "html" && node.has("cms-id")) {
288 var str = iter.get_value();
289 if (kname == "name") {
293 var chksum = GLib.Checksum.compute_for_string (ChecksumType.MD5, str.strip());
295 if (this.doubleStringProps.index_of(kname) > -1) {
296 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
297 this.transStrings.set(str, chksum);
298 named.set("_" + kname, chksum);
302 if (ktype.down() == "string" && kname[0] == '_') {
303 GLib.debug("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
304 this.transStrings.set(str, chksum);
305 named.set(kname, chksum);
310 if (name_prefix != "") {
311 var niter = named.map_iterator();
312 while (niter.next()) {
313 this.namedStrings.set(name_prefix + niter.get_key(),niter.get_value());
318 // iterate children..
319 for (var i =0; i < node.items.size; i++) {
320 this.findTransStrings(node.items.get(i) );
326 public string transStringsToJs()
329 GLib.debug("Roo.transStringsToJs()\n");
330 if (this.transStrings.size < 1) {
331 GLib.debug("Roo.transStringsToJs() size < 1?\n");
337 var hash = new Gee.HashMap<string,string>();
338 var iter = this.transStrings.map_iterator();
339 while (iter.next()) {
340 hash.set(iter.get_value(), iter.get_key());
341 kvs += (" '" + iter.get_value() + "' :" +
342 this.tree.quoteString(iter.get_key())
346 var ret = " _strings : {\n" + string.joinv(",\n", kvs) + "\n },";
350 var niter = this.namedStrings.map_iterator();
351 while (niter.next()) {
352 var otext = hash.get(niter.get_value());
353 var com = " /* " + (otext.replace("*/", "* - /") + " */ ");
356 ns += (" '" + niter.get_key() + "' : '" + niter.get_value() + "'" + com);
358 if (ns.length > 0 ) {
359 ret += "\n _named_strings : {\n" + string.joinv(",\n", ns) + "\n },";
366 * javascript used in Webkit preview
369 public override string toSourcePreview()
371 print("toSourcePreview() - reset transStrings\n");
372 this.transStrings = new Gee.HashMap<string,string>();
373 this.namedStrings = new Gee.HashMap<string,string>();
375 print("to source preview\n");
376 if (this.tree == null) {
379 this.findTransStrings(this.tree);
380 var top = this.tree.fqn();
381 var xinc = new Gee.ArrayList<string>();
383 this.findxincludes(this.tree, xinc);
384 print("got %d xincludes\n", xinc.size);
385 var prefix_data = "";
386 if (xinc.size > 0 ) {
387 for(var i = 0; i < xinc.size; i++) {
388 print("check xinclude: %s\n", xinc.get(i));
389 var sf = this.project.getByName(xinc.get(i));
391 print("Failed to find file by name?\n");
396 sf.findTransStrings(sf.tree);
397 var xinc_str = sf.toSource();
400 //FileUtils.get_contents(js, out xinc_str);
401 prefix_data += "\n" + xinc_str + "\n";
409 //print(JSON.stringify(this.items, null,4));
412 print ("guessname returned false");
417 if (top.contains("Dialog")) {
418 return prefix_data + this.toSourceDialog(true);
421 if (top.contains("Modal")) {
422 return prefix_data + this.toSourceModal(true);
424 if (top.contains("Popover")) {
425 return prefix_data + this.toSourceModal(true);
427 return prefix_data + this.toSourceLayout(true);
432 public override void setSource(string str) {}
434 * This needs to use some options on the project
435 * to determine how the file is output..
437 * At present we are hard coding it..
441 public override string toSourceCode()
443 this.transStrings = new Gee.HashMap<string,string>();
444 this.namedStrings = new Gee.HashMap<string,string>();
445 this.findTransStrings(this.tree);
446 return this.toSource();
449 public override string toSource()
451 // dump the file tree back out to a string.
453 // we have 2 types = dialogs and components
457 if (this.tree == null) {
460 var top = this.tree.fqn();
467 // get the translatable strings.. = we reload them again so calling methods get the right data...
468 this.transStrings = new Gee.HashMap<string,string>();
469 this.namedStrings = new Gee.HashMap<string,string>();
470 this.findTransStrings(this.tree);
473 if (top.contains("Dialog")) {
474 return this.toSourceDialog(false);
477 if (top.contains("Modal")) {
478 return this.toSourceModal(false);
480 return this.toSourceLayout(false);
483 eventually support 'classes??'
484 return this.toSourceStdClass();
491 * munge JSON tree into Javascript code.
493 * NOTE - needs a deep copy of original tree, before starting..
494 * - so that it does not modify current..
496 * FIXME: + or / prefixes to properties hide it from renderer.
497 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
498 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
500 * @arg {object} obj the object or array to munge..
501 * @arg {boolean} isListener - is the array being sent a listener..
502 * @arg {string} pad - the padding to indent with.
505 public string mungeToStringWrap(string pad, string prefix, string suffix)
507 if (this.tree == null) {
510 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
512 x.cur_line = prefix.split("\n").length;
517 // output both files.. so we can diff them...
518 //this.writeFile("/tmp/old.js", ret);
519 //this.writeFile("/tmp/new.js", nret);
520 return prefix + ret + suffix;
527 public string outputHeader()
530 "//<script type=\"text/javascript\">",
532 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
536 var ret= string.joinv("\n",s);
537 var bits = this.name.split(".");
538 if (bits.length > 1) {
539 ret += "\nRoo.namespace(\'" +
540 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
544 /// genericlly used..
550 // a standard dialog module.
551 // fixme - this could be alot neater..
552 public string toSourceDialog(bool isPreview)
555 //var items = JSON.parse(JSON.stringify(this.items[0]));
560 string[] adda = { " = {",
562 this.transStringsToJs() ,
567 " show : function(data, cb)",
569 " if (!this.dialog) {",
573 " this.callback = cb;",
574 " this.data = data;",
575 " this.dialog.show(this.data._el);",
577 " this.form.reset();",
578 " this.form.setValues(data);",
579 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
584 " create : function()",
586 " var _this = this;",
587 " this.dialog = Roo.factory("
596 return this.mungeToStringWrap(" ",
597 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
598 string.joinv("\n", addb) // footer
606 Bootstrap modal dialog
611 public string toSourceModal(bool isPreview)
615 //var items = JSON.parse(JSON.stringify(this.items[0]));
625 XXXX = function() {};
626 Roo.apply(XXXX.prototype, { .... });
627 Roo.apply(XXXX, XXX.prototype);
631 string[] adda = { "{",
633 this.transStringsToJs() ,
638 " show : function(data, cb)",
640 " if (!this.dialog) {",
644 " this.callback = cb;",
645 " this.data = data;",
646 " this.dialog.show(this.data._el);",
648 " this.form.reset();",
649 " this.form.setValues(data);",
650 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
655 " create : function()",
657 " var _this = this;",
658 " this.dialog = Roo.factory("
665 return this.mungeToStringWrap(" ",
666 this.outputHeader() + "\n" +
667 this.name + "= function() {}\n" +
668 "Roo.apply("+this.name + ".prototype, " + string.joinv("\n", adda), // header
669 // body goes here from the function..
670 string.joinv("\n", addb) + ");\n" + // footer
671 "Roo.apply("+this.name +", " + this.name + ".prototype);\n"
682 public string pathToPart()
684 var dir = Path.get_basename(Path.get_dirname(this.path));
685 var ar = dir.split(".");
686 var modname = ar[ar.length-1];
688 // now we have the 'module name'..
689 var fbits = Path.get_basename(this.path).split(".");
692 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
693 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
694 npart = npart.substring(modname.length);
696 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
705 public string toSourceLayout(bool isPreview)
710 // topItem.region = 'center';
711 // topItem.background = false;
714 var modkey = this.modOrder + "-" + this.name;
716 var reg = new Regex("[^A-Za-z.]+");
718 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
719 } catch (RegexError e) {
722 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
727 // set to false to ensure this is the top level..
729 var topnode = this.tree.fqn();
730 print("topnode = %s\n", topnode);
731 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
732 topnode != "Roo.bootstrap.Body"
734 parent = "\"#bootstrap-body\"";
741 var pref = this.outputHeader() + "\n" +
743 this.name + " = new Roo.XComponent({\n" +
745 this.transStringsToJs() + "\n" +
747 " part : "+ this.pathToPart() + ",\n" +
748 /// critical used by builder to associate modules/parts/persm
749 " order : '" +modkey+"',\n" +
750 " region : '" + this.region +"',\n" +
751 " parent : "+ parent + ",\n" +
752 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
753 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
754 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
756 // " tree : function() { return this._tree(); },\n" + //BC
757 " _tree : function(_data)\n" +
759 " var _this = this;\n" + // bc
760 " var MODULE = this;\n" + /// this looks like a better name.
763 return this.mungeToStringWrap(" ", pref, ";" +
771 public new string? guessName (Node? ar) // turns the object into full name.
773 // eg. xns: Roo, xtype: XXX -> Roo.xxx
779 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
782 if ( ar.get("xtype").length < 1) {
786 var xtype = ar.get("xtype");
788 if (xtype[0] == '*') { // prefixes????
789 xtype = xtype.substring(1);
791 if (! Regex.match_simple("^Roo", xtype)) {
793 // already starts with roo...
797 var str = string.joinv(".", ret);
801 //Palete.Palete.factory("Roo").guessName(str);
807 string getHelpUrl(string cls)
809 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";