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]);
74 setNSID : function(id)
77 this.items[0]['|module'] = id;
89 public override void removeFiles() {
90 var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
91 if (FileUtils.test(html, FileTest.EXISTS)) {
92 GLib.FileUtils.remove(html);
94 var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
95 if (FileUtils.test(js, FileTest.EXISTS)) {
96 GLib.FileUtils.remove(js);
100 public override void loadItems() throws GLib.Error // : function(cb, sync) == original was async.
104 print("load Items!");
105 if (this.tree != null) {
108 print("load " + this.path);
110 var pa = new Json.Parser();
111 pa.load_from_file(this.path);
112 var node = pa.get_root();
114 if (node.get_node_type () != Json.NodeType.OBJECT) {
115 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
117 var obj = node.get_object ();
120 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
121 this.name = this.jsonHasOrEmpty(obj, "name");
122 this.parent = this.jsonHasOrEmpty(obj, "parent");
123 this.permname = this.jsonHasOrEmpty(obj, "permname");
124 this.title = this.jsonHasOrEmpty(obj, "title");
125 this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
127 var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
128 bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
131 // load items[0] ??? into tree...
132 if (obj.has_member("items")
134 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
136 obj.get_array_member("items").get_length() > 0
138 this.tree = new Node();
139 var ar = obj.get_array_member("items");
140 var tree_base = ar.get_object_element(0);
141 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
149 * old code had broken xtypes and used arrays differently,
150 * this code should try and clean it up..
154 fixItems : function(node, fixthis)
158 var fn = this.guessName(node);
159 //print("guessname got " + fn);
161 var bits = fn.split('.');
162 node.xtype = bits.pop();
163 node['|xns'] = bits.join('.');
170 if (!node.items || !node.items.length) {
176 node.items.forEach(function(i) {
180 _this.fixItems(i, true);
181 if (i.xtype == 'Array') {
189 if (!aitems.length) {
193 aitems.forEach(function(i) {
195 if (!i.items || !i.items.length) {
198 var prop = i['*prop'] + '[]';
200 i.items.forEach(function(c) {
219 public override void save()
222 print("--- JsRender.Roo.save");
223 print("save() - reset transStrings\n");
224 this.transStrings = new Gee.HashMap<string,string>();
225 this.findTransStrings(this.tree);
230 if (this.tree == null) {
233 // now write the js file..
236 Regex regex = new Regex("\\.(bjs|js)$");
238 js = regex.replace(this.path,this.path.length , 0 , ".js");
239 } catch (RegexError e) {
241 print("count not make filename from path");
246 //var d = new Date();
247 var js_src = this.toSource();
248 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
250 this.writeFile(js, js_src);
251 } catch (FileError e ) {
252 print("Save failed\n");
254 // for bootstrap - we can write the HTML to the templates directory..
256 //var top = this.guessName(this.items[0]);
257 //print ("TOP = " + top)
267 public override void saveHTML ( string html )
270 var top = this.tree.fqn();
271 print ("TOP = " + top + "\n" );
272 if (top.index_of("Roo.bootstrap.") < 0 &&
273 top.index_of("Roo.mailer.") < 0
279 //now write the js file..
282 Regex regex = new Regex("\\.(bjs|js)$");
284 fn = regex.replace(this.path,this.path.length , 0 , ".html");
285 } catch (RegexError e) {
287 print("count not make filename from path");
290 var bn = GLib.Path.get_basename(fn);
291 var dn = GLib.Path.get_dirname(fn);
293 var targetdir = dn + (
294 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
297 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
298 print("Skip save - templates folder does not exist : %s\n", targetdir);
301 print("SAVE HTML -- %s\n%s\n",targetdir + "/" + bn, html);
303 this.writeFile(targetdir + "/" + bn , html);
304 } catch (FileError e ) {
305 print("SaveHtml failed\n");
312 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
315 if (node.props.has_key("* xinclude")) {
316 ret.add(node.props.get("* xinclude"));
318 for (var i =0; i < node.items.size; i++) {
319 this.findxincludes(node.items.get(i), ret);
327 public override void findTransStrings(Node? node )
329 // iterate properties...
330 // use doubleStringProps
332 // flagging a translatable string..
333 // the code would use string _astring to indicate a translatable string
334 // the to use it it would do String.format(this._message, somedata);
336 // loop through and find string starting with '_'
341 var iter = node.props.map_iterator();
342 while (iter.next()) {
343 // key formats : XXXX
345 // string XXX - with type
346 // $ XXX - with flag (no type)
347 // $ string XXX - with flag
351 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
355 var str = iter.get_value();
356 if (this.doubleStringProps.index_of(kname) > -1) {
357 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
358 this.transStrings.set(str,
359 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
364 if (ktype.down() == "string" && kname[0] == '_') {
365 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
366 this.transStrings.set(str,
367 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
376 // iterate children..
377 for (var i =0; i < node.items.size; i++) {
378 this.findTransStrings(node.items.get(i) );
384 public string transStringsToJs()
387 print("Roo.transStringsToJs()\n");
388 if (this.transStrings.size < 1) {
389 print("Roo.transStringsToJs() size < 1?\n");
394 var iter = this.transStrings.map_iterator();
395 while (iter.next()) {
396 kvs += (" '" + iter.get_value() + "' :" +
397 this.tree.quoteString(iter.get_key())
400 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
409 * javascript used in Webkit preview
412 public override string toSourcePreview()
414 print("toSourcePreview() - reset transStrings\n");
415 this.transStrings = new Gee.HashMap<string,string>();
418 print("to source preview\n");
419 if (this.tree == null) {
422 this.findTransStrings(this.tree);
423 var top = this.tree.fqn();
424 var xinc = new Gee.ArrayList<string>();
426 this.findxincludes(this.tree, xinc);
427 print("got %d xincludes\n", xinc.size);
428 var prefix_data = "";
429 if (xinc.size > 0 ) {
430 for(var i = 0; i < xinc.size; i++) {
431 print("check xinclude: %s\n", xinc.get(i));
432 var sf = this.project.getByName(xinc.get(i));
434 print("Failed to find file by name?\n");
439 sf.findTransStrings(sf.tree);
440 var xinc_str = sf.toSource();
443 //FileUtils.get_contents(js, out xinc_str);
444 prefix_data += "\n" + xinc_str + "\n";
452 //print(JSON.stringify(this.items, null,4));
455 print ("guessname returned false");
460 if (top.contains("Dialog")) {
461 return prefix_data + this.toSourceDialog(true);
464 if (top.contains("Modal")) {
465 return prefix_data + this.toSourceModal(true);
468 return prefix_data + this.toSourceLayout(true);
473 public override void setSource(string str) {}
475 * This needs to use some options on the project
476 * to determine how the file is output..
478 * At present we are hard coding it..
482 public override string toSource()
484 // dump the file tree back out to a string.
486 // we have 2 types = dialogs and components
490 if (this.tree == null) {
493 var top = this.tree.fqn();
497 // get the translatable strings..
501 if (top.contains("Dialog")) {
502 return this.toSourceDialog(false);
505 if (top.contains("Modal")) {
506 return this.toSourceModal(false);
508 return this.toSourceLayout(false);
511 eventually support 'classes??'
512 return this.toSourceStdClass();
519 * munge JSON tree into Javascript code.
521 * NOTE - needs a deep copy of original tree, before starting..
522 * - so that it does not modify current..
524 * FIXME: + or / prefixes to properties hide it from renderer.
525 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
526 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
528 * @arg {object} obj the object or array to munge..
529 * @arg {boolean} isListener - is the array being sent a listener..
530 * @arg {string} pad - the padding to indent with.
533 public string mungeToStringWrap(string pad, string prefix, string suffix)
535 if (this.tree == null) {
538 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
539 x.cur_line = prefix.split("\n").length;
544 // output both files.. so we can diff them...
545 //this.writeFile("/tmp/old.js", ret);
546 //this.writeFile("/tmp/new.js", nret);
547 return prefix + ret + suffix;
554 public string outputHeader()
557 "//<script type=\"text/javascript\">",
559 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
563 var ret= string.joinv("\n",s);
564 var bits = this.name.split(".");
565 if (bits.length > 1) {
566 ret += "\nRoo.namespace(\'" +
567 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
571 /// genericlly used..
577 // a standard dialog module.
578 // fixme - this could be alot neater..
579 public string toSourceDialog(bool isPreview)
582 //var items = JSON.parse(JSON.stringify(this.items[0]));
587 string[] adda = { " = {",
589 this.transStringsToJs() ,
594 " show : function(data, cb)",
596 " if (!this.dialog) {",
600 " this.callback = cb;",
601 " this.data = data;",
602 " this.dialog.show(this.data._el);",
604 " this.form.reset();",
605 " this.form.setValues(data);",
606 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
611 " create : function()",
613 " var _this = this;",
614 " this.dialog = Roo.factory("
623 var o = this.mungeToString(" ");
625 return this.mungeToStringWrap(" ",
626 this.outputHeader() + "\n" + .name + string.joinv("\n", adda), //header
627 string.joinv("\n", addb) // footer
635 Bootstrap modal dialog
640 public string toSourceModal(bool isPreview)
644 //var items = JSON.parse(JSON.stringify(this.items[0]));
645 var o = this.mungeToString(" ");
647 string[] adda = { " = {",
649 this.transStringsToJs() ,
654 " show : function(data, cb)",
656 " if (!this.dialog) {",
660 " this.callback = cb;",
661 " this.data = data;",
662 " this.dialog.show(this.data._el);",
664 " this.form.reset();",
665 " this.form.setValues(data);",
666 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
671 " create : function()",
673 " var _this = this;",
674 " this.dialog = Roo.factory("
682 return this.mungeToStringWrap(" ",
683 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), // header
684 string.joinv("\n", addb) // footer
695 public string pathToPart()
697 var dir = Path.get_basename(Path.get_dirname(this.path));
698 var ar = dir.split(".");
699 var modname = ar[ar.length-1];
701 // now we have the 'module name'..
702 var fbits = Path.get_basename(this.path).split(".");
705 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
706 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
707 npart = npart.substring(modname.length);
709 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
718 public string toSourceLayout(bool isPreview)
723 // topItem.region = 'center';
724 // topItem.background = false;
727 var o = this.mungeToString(" ");
728 var reg = new Regex("[^A-Za-z.]+");
730 string modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
732 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
737 // set to false to ensure this is the top level..
739 var topnode = this.tree.fqn();
740 print("topnode = %s\n", topnode);
741 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
742 topnode != "Roo.bootstrap.Body"
744 parent = "\"#bootstrap-body\"";
751 this.outputHeader() + "\n" +
753 this.name + " = new Roo.XComponent({\n" +
755 this.transStringsToJs() + "\n" +
757 " part : "+ this.pathToPart() + ",\n" +
758 /// critical used by builder to associate modules/parts/persm
759 " order : '" +modkey+"',\n" +
760 " region : '" + this.region +"',\n" +
761 " parent : "+ parent + ",\n" +
762 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
763 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
764 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
766 // " tree : function() { return this._tree(); },\n" + //BC
767 " _tree : function()\n" +
769 " var _this = this;\n" + // bc
770 " var MODULE = this;\n" + /// this looks like a better name.
771 " return " + o + ";" +
778 public new string? guessName (Node? ar) // turns the object into full name.
780 // eg. xns: Roo, xtype: XXX -> Roo.xxx
786 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
789 if ( ar.get("xtype").length < 1) {
793 var xtype = ar.get("xtype");
795 if (xtype[0] == '*') { // prefixes????
796 xtype = xtype.substring(1);
798 if (! Regex.match_simple("^Roo", xtype)) {
800 // already starts with roo...
804 var str = string.joinv(".", ret);
808 //Palete.Palete.factory("Roo").guessName(str);
814 string getHelpUrl(string cls)
816 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";