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));
150 public override void save()
153 print("--- JsRender.Roo.save");
154 print("save() - reset transStrings\n");
155 this.transStrings = new Gee.HashMap<string,string>();
156 this.findTransStrings(this.tree);
161 if (this.tree == null) {
164 // now write the js file..
167 Regex regex = new Regex("\\.(bjs|js)$");
169 js = regex.replace(this.path,this.path.length , 0 , ".js");
170 } catch (RegexError e) {
172 print("count not make filename from path");
177 //var d = new Date();
178 var js_src = this.toSource();
179 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
181 this.writeFile(js, js_src);
182 } catch (FileError e ) {
183 print("Save failed\n");
185 // for bootstrap - we can write the HTML to the templates directory..
187 //var top = this.guessName(this.items[0]);
188 //print ("TOP = " + top)
198 public override void saveHTML ( string html )
201 var top = this.tree.fqn();
202 print ("TOP = " + top + "\n" );
203 if (top.index_of("Roo.bootstrap.") < 0 &&
204 top.index_of("Roo.mailer.") < 0
210 //now write the js file..
213 Regex regex = new Regex("\\.(bjs|js)$");
215 fn = regex.replace(this.path,this.path.length , 0 , ".html");
216 } catch (RegexError e) {
218 print("count not make filename from path");
221 var bn = GLib.Path.get_basename(fn);
222 var dn = GLib.Path.get_dirname(fn);
224 var targetdir = dn + (
225 top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
228 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
229 print("Skip save - templates folder does not exist : %s\n", targetdir);
232 print("SAVE HTML -- %s\n%s\n",targetdir + "/" + bn, html);
234 this.writeFile(targetdir + "/" + bn , html);
235 } catch (FileError e ) {
236 print("SaveHtml failed\n");
243 public Gee.ArrayList<string> findxincludes(Node node, Gee.ArrayList<string> ret)
246 if (node.props.has_key("* xinclude")) {
247 ret.add(node.props.get("* xinclude"));
249 for (var i =0; i < node.items.size; i++) {
250 this.findxincludes(node.items.get(i), ret);
258 public override void findTransStrings(Node? node )
260 // iterate properties...
261 // use doubleStringProps
263 // flagging a translatable string..
264 // the code would use string _astring to indicate a translatable string
265 // the to use it it would do String.format(this._message, somedata);
267 // loop through and find string starting with '_'
272 var iter = node.props.map_iterator();
273 while (iter.next()) {
274 // key formats : XXXX
276 // string XXX - with type
277 // $ XXX - with flag (no type)
278 // $ string XXX - with flag
282 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
286 var str = iter.get_value();
287 if (this.doubleStringProps.index_of(kname) > -1) {
288 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
289 this.transStrings.set(str,
290 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
295 if (ktype.down() == "string" && kname[0] == '_') {
296 print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
297 this.transStrings.set(str,
298 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
307 // iterate children..
308 for (var i =0; i < node.items.size; i++) {
309 this.findTransStrings(node.items.get(i) );
315 public string transStringsToJs()
318 print("Roo.transStringsToJs()\n");
319 if (this.transStrings.size < 1) {
320 print("Roo.transStringsToJs() size < 1?\n");
325 var iter = this.transStrings.map_iterator();
326 while (iter.next()) {
327 kvs += (" '" + iter.get_value() + "' :" +
328 this.tree.quoteString(iter.get_key())
331 return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" +
340 * javascript used in Webkit preview
343 public override string toSourcePreview()
345 print("toSourcePreview() - reset transStrings\n");
346 this.transStrings = new Gee.HashMap<string,string>();
349 print("to source preview\n");
350 if (this.tree == null) {
353 this.findTransStrings(this.tree);
354 var top = this.tree.fqn();
355 var xinc = new Gee.ArrayList<string>();
357 this.findxincludes(this.tree, xinc);
358 print("got %d xincludes\n", xinc.size);
359 var prefix_data = "";
360 if (xinc.size > 0 ) {
361 for(var i = 0; i < xinc.size; i++) {
362 print("check xinclude: %s\n", xinc.get(i));
363 var sf = this.project.getByName(xinc.get(i));
365 print("Failed to find file by name?\n");
370 sf.findTransStrings(sf.tree);
371 var xinc_str = sf.toSource();
374 //FileUtils.get_contents(js, out xinc_str);
375 prefix_data += "\n" + xinc_str + "\n";
383 //print(JSON.stringify(this.items, null,4));
386 print ("guessname returned false");
391 if (top.contains("Dialog")) {
392 return prefix_data + this.toSourceDialog(true);
395 if (top.contains("Modal")) {
396 return prefix_data + this.toSourceModal(true);
399 return prefix_data + this.toSourceLayout(true);
404 public override void setSource(string str) {}
406 * This needs to use some options on the project
407 * to determine how the file is output..
409 * At present we are hard coding it..
413 public override string toSource()
415 // dump the file tree back out to a string.
417 // we have 2 types = dialogs and components
421 if (this.tree == null) {
424 var top = this.tree.fqn();
428 // get the translatable strings..
432 if (top.contains("Dialog")) {
433 return this.toSourceDialog(false);
436 if (top.contains("Modal")) {
437 return this.toSourceModal(false);
439 return this.toSourceLayout(false);
442 eventually support 'classes??'
443 return this.toSourceStdClass();
450 * munge JSON tree into Javascript code.
452 * NOTE - needs a deep copy of original tree, before starting..
453 * - so that it does not modify current..
455 * FIXME: + or / prefixes to properties hide it from renderer.
456 * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
457 * FIXME: needs to understand what properties might be translatable (eg. double quotes)
459 * @arg {object} obj the object or array to munge..
460 * @arg {boolean} isListener - is the array being sent a listener..
461 * @arg {string} pad - the padding to indent with.
464 public string mungeToStringWrap(string pad, string prefix, string suffix)
466 if (this.tree == null) {
469 var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
470 x.cur_line = prefix.split("\n").length;
475 // output both files.. so we can diff them...
476 //this.writeFile("/tmp/old.js", ret);
477 //this.writeFile("/tmp/new.js", nret);
478 return prefix + ret + suffix;
485 public string outputHeader()
488 "//<script type=\"text/javascript\">",
490 "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
494 var ret= string.joinv("\n",s);
495 var bits = this.name.split(".");
496 if (bits.length > 1) {
497 ret += "\nRoo.namespace(\'" +
498 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
502 /// genericlly used..
508 // a standard dialog module.
509 // fixme - this could be alot neater..
510 public string toSourceDialog(bool isPreview)
513 //var items = JSON.parse(JSON.stringify(this.items[0]));
518 string[] adda = { " = {",
520 this.transStringsToJs() ,
525 " show : function(data, cb)",
527 " if (!this.dialog) {",
531 " this.callback = cb;",
532 " this.data = data;",
533 " this.dialog.show(this.data._el);",
535 " this.form.reset();",
536 " this.form.setValues(data);",
537 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
542 " create : function()",
544 " var _this = this;",
545 " this.dialog = Roo.factory("
554 return this.mungeToStringWrap(" ",
555 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
556 string.joinv("\n", addb) // footer
564 Bootstrap modal dialog
569 public string toSourceModal(bool isPreview)
573 //var items = JSON.parse(JSON.stringify(this.items[0]));
576 string[] adda = { " = {",
578 this.transStringsToJs() ,
583 " show : function(data, cb)",
585 " if (!this.dialog) {",
589 " this.callback = cb;",
590 " this.data = data;",
591 " this.dialog.show(this.data._el);",
593 " this.form.reset();",
594 " this.form.setValues(data);",
595 " this.form.fireEvent('actioncomplete', this.form, { type: 'setdata', data: data });",
600 " create : function()",
602 " var _this = this;",
603 " this.dialog = Roo.factory("
611 return this.mungeToStringWrap(" ",
612 this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), // header
613 string.joinv("\n", addb) // footer
624 public string pathToPart()
626 var dir = Path.get_basename(Path.get_dirname(this.path));
627 var ar = dir.split(".");
628 var modname = ar[ar.length-1];
630 // now we have the 'module name'..
631 var fbits = Path.get_basename(this.path).split(".");
634 var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
635 if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
636 npart = npart.substring(modname.length);
638 return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
647 public string toSourceLayout(bool isPreview)
652 // topItem.region = 'center';
653 // topItem.background = false;
656 var modkey = this.modOrder + "-" + this.name;
658 var reg = new Regex("[^A-Za-z.]+");
660 modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
661 } catch (RegexError e) {
664 string parent = (this.parent.length > 0 ? "'" + this.parent + "'" : "false");
669 // set to false to ensure this is the top level..
671 var topnode = this.tree.fqn();
672 print("topnode = %s\n", topnode);
673 if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
674 topnode != "Roo.bootstrap.Body"
676 parent = "\"#bootstrap-body\"";
683 var pref = this.outputHeader() + "\n" +
685 this.name + " = new Roo.XComponent({\n" +
687 this.transStringsToJs() + "\n" +
689 " part : "+ this.pathToPart() + ",\n" +
690 /// critical used by builder to associate modules/parts/persm
691 " order : '" +modkey+"',\n" +
692 " region : '" + this.region +"',\n" +
693 " parent : "+ parent + ",\n" +
694 " name : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
695 " disabled : " + (this.disabled ? "true" : "false") +", \n" +
696 " permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
698 // " tree : function() { return this._tree(); },\n" + //BC
699 " _tree : function()\n" +
701 " var _this = this;\n" + // bc
702 " var MODULE = this;\n" + /// this looks like a better name.
705 return this.mungeToStringWrap(" ", pref, ";" +
713 public new string? guessName (Node? ar) // turns the object into full name.
715 // eg. xns: Roo, xtype: XXX -> Roo.xxx
721 ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
724 if ( ar.get("xtype").length < 1) {
728 var xtype = ar.get("xtype");
730 if (xtype[0] == '*') { // prefixes????
731 xtype = xtype.substring(1);
733 if (! Regex.match_simple("^Roo", xtype)) {
735 // already starts with roo...
739 var str = string.joinv(".", ret);
743 //Palete.Palete.factory("Roo").guessName(str);
749 string getHelpUrl(string cls)
751 return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";