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.
91 if (this.tree != null) {
94 print("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 print("--- JsRender.Roo.save");
140 print("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 )
187 var top = this.tree.fqn();
188 print ("TOP = " + top + "\n" );
189 if (top.index_of("Roo.bootstrap.") < 0 &&
190 top.index_of("Roo.mailer.") < 0
196 //now write the js file..
199 Regex regex = new Regex("\\.(bjs|js)$");
201 fn = regex.replace(this.path,this.path.length , 0 , ".html");
202 } catch (RegexError e) {
204 print("count not make filename from path");
207 var bn = GLib.Path.get_basename(fn);
208 var dn = GLib.Path.get_dirname(fn);
210 var targetdir = dn + (
211 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
214 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
215 print("Skip save - templates folder does not exist : %s\n", targetdir);
218 print("SAVE HTML -- %s\n%s\n",targetdir + "/" + bn, html);
220 this.writeFile(targetdir + "/" + bn , html);
221 } catch (FileError e ) {
222 print("SaveHtml failed\n");
229 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
232 if (node.props.has_key("* xinclude")) {
233 ret.add(node.props.get("* xinclude"));
235 for (var i =0; i < node.items.size; i++) {
236 this.findxincludes(node.items.get(i), ret);
244 public override void findTransStrings(Node? node )
246 // iterate properties...
247 // use doubleStringProps
249 // flagging a translatable string..
250 // the code would use string _astring to indicate a translatable string
251 // the to use it it would do String.format(this._message, somedata);
253 // loop through and find string starting with '_'
258 var iter = node.props.map_iterator();
259 while (iter.next()) {
260 // key formats : XXXX
262 // string XXX - with type
263 // $ XXX - with flag (no type)
264 // $ string XXX - with flag
268 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
272 // skip cms-id nodes...
273 if (kname == "html" && node.has("cms-id")) {
277 var str = iter.get_value();
278 if (this.doubleStringProps.index_of(kname) > -1) {
279 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
280 this.transStrings.set(str,
281 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
286 if (ktype.down() == "string" && kname[0] == '_') {
287 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
288 this.transStrings.set(str,
289 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
298 // iterate children..
299 for (var i =0; i < node.items.size; i++) {
300 this.findTransStrings(node.items.get(i) );
306 public string transStringsToJs()
309 print("Roo.transStringsToJs()\n");
310 if (this.transStrings.size < 1) {
311 print("Roo.transStringsToJs() size < 1?\n");
316 var iter = this.transStrings.map_iterator();
317 while (iter.next()) {
318 kvs += (" '" + iter.get_value() + "' :" +
319 this.tree.quoteString(iter.get_key())
322 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
331 * javascript used in Webkit preview
334 public override string toSourcePreview()
336 print("toSourcePreview() - reset transStrings\n");
337 this.transStrings = new Gee.HashMap<string,string>();
340 print("to source preview\n");
341 if (this.tree == null) {
344 this.findTransStrings(this.tree);
345 var top = this.tree.fqn();
346 var xinc = new Gee.ArrayList<string>();
348 this.findxincludes(this.tree, xinc);
349 print("got %d xincludes\n", xinc.size);
350 var prefix_data = "";
351 if (xinc.size > 0 ) {
352 for(var i = 0; i < xinc.size; i++) {
353 print("check xinclude: %s\n", xinc.get(i));
354 var sf = this.project.getByName(xinc.get(i));
356 print("Failed to find file by name?\n");
361 sf.findTransStrings(sf.tree);
362 var xinc_str = sf.toSource();
365 //FileUtils.get_contents(js, out xinc_str);
366 prefix_data += "\n" + xinc_str + "\n";
374 //print(JSON.stringify(this.items, null,4));
377 print ("guessname returned false");
382 if (top.contains("Dialog")) {
383 return prefix_data + this.toSourceDialog(true);
386 if (top.contains("Modal")) {
387 return prefix_data + this.toSourceModal(true);
390 return prefix_data + this.toSourceLayout(true);
395 public override void setSource(string str) {}
397 * This needs to use some options on the project
398 * to determine how the file is output..
400 * At present we are hard coding it..
404 public override string toSource()
406 // dump the file tree back out to a string.
408 // we have 2 types = dialogs and components
412 if (this.tree == null) {
415 var top = this.tree.fqn();
422 // get the translatable strings.. = we reload them again so calling methods get the right data...
423 this.transStrings = new Gee.HashMap<string,string>();
424 this.findTransStrings(this.tree);
427 if (top.contains("Dialog")) {
428 return this.toSourceDialog(false);
431 if (top.contains("Modal")) {
432 return this.toSourceModal(false);
434 return this.toSourceLayout(false);
437 eventually support 'classes??'
438 return this.toSourceStdClass();
445 * munge JSON tree into Javascript code.
447 * NOTE - needs a deep copy of original tree, before starting..
448 * - so that it does not modify current..
450 * FIXME: + or / prefixes to properties hide it from renderer.
451 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
452 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
454 * @arg {object} obj the object or array to munge..
455 * @arg {boolean} isListener - is the array being sent a listener..
456 * @arg {string} pad - the padding to indent with.
459 public string mungeToStringWrap(string pad, string prefix, string suffix)
461 if (this.tree == null) {
464 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
466 x.cur_line = prefix.split("\n").length;
471 // output both files.. so we can diff them...
472 //this.writeFile("/tmp/old.js", ret);
473 //this.writeFile("/tmp/new.js", nret);
474 return prefix + ret + suffix;
481 public string outputHeader()
484 "//<script type=\"text/javascript\">",
486 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
490 var ret= string.joinv("\n",s);
491 var bits = this.name.split(".");
492 if (bits.length > 1) {
493 ret += "\nRoo.namespace(\'" +
494 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
498 /// genericlly used..
504 // a standard dialog module.
505 // fixme - this could be alot neater..
506 public string toSourceDialog(bool isPreview)
509 //var items = JSON.parse(JSON.stringify(this.items[0]));
514 string[] adda = { " = {",
516 this.transStringsToJs() ,
521 " show : function(data, cb)",
523 " if (!this.dialog) {",
527 " this.callback = cb;",
528 " this.data = data;",
529 " this.dialog.show(this.data._el);",
531 " this.form.reset();",
532 " this.form.setValues(data);",
533 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
538 " create : function()",
540 " var _this = this;",
541 " this.dialog = Roo.factory("
550 return this.mungeToStringWrap(" ",
551 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
552 string.joinv("\n", addb) // footer
560 Bootstrap modal dialog
565 public string toSourceModal(bool isPreview)
569 //var items = JSON.parse(JSON.stringify(this.items[0]));
572 string[] adda = { " = {",
574 this.transStringsToJs() ,
579 " show : function(data, cb)",
581 " if (!this.dialog) {",
585 " this.callback = cb;",
586 " this.data = data;",
587 " this.dialog.show(this.data._el);",
589 " this.form.reset();",
590 " this.form.setValues(data);",
591 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
596 " create : function()",
598 " var _this = this;",
599 " this.dialog = Roo.factory("
607 return this.mungeToStringWrap(" ",
608 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), // header
609 string.joinv("\n", addb) // footer
620 public string pathToPart()
622 var dir = Path.get_basename(Path.get_dirname(this.path));
623 var ar = dir.split(".");
624 var modname = ar[ar.length-1];
626 // now we have the 'module name'..
627 var fbits = Path.get_basename(this.path).split(".");
630 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
631 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
632 npart = npart.substring(modname.length);
634 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
643 public string toSourceLayout(bool isPreview)
648 // topItem.region = 'center';
649 // topItem.background = false;
652 var modkey = this.modOrder + "-" + this.name;
654 var reg = new Regex("[^A-Za-z.]+");
656 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
657 } catch (RegexError e) {
660 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
665 // set to false to ensure this is the top level..
667 var topnode = this.tree.fqn();
668 print("topnode = %s\n", topnode);
669 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
670 topnode != "Roo.bootstrap.Body"
672 parent = "\"#bootstrap-body\"";
679 var pref = this.outputHeader() + "\n" +
681 this.name + " = new Roo.XComponent({\n" +
683 this.transStringsToJs() + "\n" +
685 " part : "+ this.pathToPart() + ",\n" +
686 /// critical used by builder to associate modules/parts/persm
687 " order : '" +modkey+"',\n" +
688 " region : '" + this.region +"',\n" +
689 " parent : "+ parent + ",\n" +
690 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
691 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
692 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
694 // " tree : function() { return this._tree(); },\n" + //BC
695 " _tree : function()\n" +
697 " var _this = this;\n" + // bc
698 " var MODULE = this;\n" + /// this looks like a better name.
701 return this.mungeToStringWrap(" ", pref, ";" +
709 public new string? guessName (Node? ar) // turns the object into full name.
711 // eg. xns: Roo, xtype: XXX -> Roo.xxx
717 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
720 if ( ar.get("xtype").length < 1) {
724 var xtype = ar.get("xtype");
726 if (xtype[0] == '*') { // prefixes????
727 xtype = xtype.substring(1);
729 if (! Regex.match_simple("^Roo", xtype)) {
731 // already starts with roo...
735 var str = string.joinv(".", ret);
739 //Palete.Palete.factory("Roo").guessName(str);
745 string getHelpUrl(string cls)
747 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";