Roo/XComponent.js
[roojs1] / Roo / XComponent.js
1 /*
2  * Original code for Roojs - LGPL
3  * <script type="text/javascript">
4  */
5  
6 /**
7  * @class Roo.XComponent
8  * A delayed Element creator...
9  * Or a way to group chunks of interface together.
10  * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
11  *  used in conjunction with XComponent.build() it will create an instance of each element,
12  *  then call addxtype() to build the User interface.
13  * 
14  * Mypart.xyx = new Roo.XComponent({
15
16     parent : 'Mypart.xyz', // empty == document.element.!!
17     order : '001',
18     name : 'xxxx'
19     region : 'xxxx'
20     disabled : function() {} 
21      
22     tree : function() { // return an tree of xtype declared components
23         var MODULE = this;
24         return 
25         {
26             xtype : 'NestedLayoutPanel',
27             // technicall
28         }
29      ]
30  *})
31  *
32  *
33  * It can be used to build a big heiracy, with parent etc.
34  * or you can just use this to render a single compoent to a dom element
35  * MYPART.render(Roo.Element | String(id) | dom_element )
36  *
37  *
38  * Usage patterns.
39  *
40  * Classic Roo
41  *
42  * Roo is designed primarily as a single page application, so the UI build for a standard interface will
43  * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
44  *
45  * Each sub module is expected to have a parent pointing to the class name of it's parent module.
46  *
47  * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
48  * - if mulitple topModules exist, the last one is defined as the top module.
49  *
50  * Embeded Roo
51  * 
52  * When the top level or multiple modules are to embedded into a existing HTML page,
53  * the parent element can container '#id' of the element where the module will be drawn.
54  *
55  * Bootstrap Roo
56  *
57  * Unlike classic Roo, the bootstrap tends not to be used as a single page.
58  * it relies more on a include mechanism, where sub modules are included into an outer page.
59  * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
60  * 
61  * Bootstrap Roo Included elements
62  *
63  * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
64  * hence confusing the component builder as it thinks there are multiple top level elements. 
65  *
66  * 
67  * 
68  * @extends Roo.util.Observable
69  * @constructor
70  * @param cfg {Object} configuration of component
71  * 
72  */
73 Roo.XComponent = function(cfg) {
74     Roo.apply(this, cfg);
75     this.addEvents({ 
76         /**
77              * @event built
78              * Fires when this the componnt is built
79              * @param {Roo.XComponent} c the component
80              */
81         'built' : true
82         
83     });
84     this.region = this.region || 'center'; // default..
85     Roo.XComponent.register(this);
86     this.modules = false;
87     this.el = false; // where the layout goes..
88     
89     
90 }
91 Roo.extend(Roo.XComponent, Roo.util.Observable, {
92     /**
93      * @property el
94      * The created element (with Roo.factory())
95      * @type {Roo.Layout}
96      */
97     el  : false,
98     
99     /**
100      * @property el
101      * for BC  - use el in new code
102      * @type {Roo.Layout}
103      */
104     panel : false,
105     
106     /**
107      * @property layout
108      * for BC  - use el in new code
109      * @type {Roo.Layout}
110      */
111     layout : false,
112     
113      /**
114      * @cfg {Function|boolean} disabled
115      * If this module is disabled by some rule, return true from the funtion
116      */
117     disabled : false,
118     
119     /**
120      * @cfg {String} parent 
121      * Name of parent element which it get xtype added to..
122      */
123     parent: false,
124     
125     /**
126      * @cfg {String} order
127      * Used to set the order in which elements are created (usefull for multiple tabs)
128      */
129     
130     order : false,
131     /**
132      * @cfg {String} name
133      * String to display while loading.
134      */
135     name : false,
136     /**
137      * @cfg {String} region
138      * Region to render component to (defaults to center)
139      */
140     region : 'center',
141     
142     /**
143      * @cfg {Array} items
144      * A single item array - the first element is the root of the tree..
145      * It's done this way to stay compatible with the Xtype system...
146      */
147     items : false,
148     
149     /**
150      * @property _tree
151      * The method that retuns the tree of parts that make up this compoennt 
152      * @type {function}
153      */
154     _tree  : false,
155     
156      /**
157      * render
158      * render element to dom or tree
159      * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
160      */
161     
162     render : function(el)
163     {
164         
165         el = el || false;
166         var hp = this.parent ? 1 : 0;
167         Roo.debug &&  Roo.log(this);
168         
169         if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
170             // if parent is a '#.....' string, then let's use that..
171             var ename = this.parent.substr(1);
172             this.parent = false;
173             Roo.debug && Roo.log(ename);
174             switch (ename) {
175                 case 'bootstrap-body' :
176                     if (typeof(Roo.bootstrap.Body) != 'undefined') {
177                         this.parent = { el :  new  Roo.bootstrap.Body() };
178                         Roo.debug && Roo.log("setting el to doc body");
179                          
180                     } else {
181                         throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
182                     }
183                     break;
184                 case 'bootstrap':
185                     this.parent = { el : true};
186                     // fall through
187                 default:
188                     el = Roo.get(ename);
189                     break;
190             }
191                 
192             
193             if (!el && !this.parent) {
194                 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
195                 return;
196             }
197         }
198         Roo.debug && Roo.log("EL:");
199         Roo.debug && Roo.log(el);
200         Roo.debug && Roo.log("this.parent.el:");
201         Roo.debug && Roo.log(this.parent.el);
202         
203         var tree = this._tree ? this._tree() : this.tree();
204
205         // altertive root elements ??? - we need a better way to indicate these.
206         var is_alt = Roo.XComponent.is_alt ||
207                     (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
208                     (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
209                     (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
210         
211         
212         
213         if (!this.parent && is_alt) {
214             //el = Roo.get(document.body);
215             this.parent = { el : true };
216         }
217             
218             
219         
220         if (!this.parent) {
221             
222             Roo.debug && Roo.log("no parent - creating one");
223             
224             el = el ? Roo.get(el) : false;      
225             
226             // it's a top level one..
227             this.parent =  {
228                 el : new Roo.BorderLayout(el || document.body, {
229                 
230                      center: {
231                          titlebar: false,
232                          autoScroll:false,
233                          closeOnTab: true,
234                          tabPosition: 'top',
235                           //resizeTabs: true,
236                          alwaysShowTabs: el && hp? false :  true,
237                          hideTabs: el || !hp ? true :  false,
238                          minTabWidth: 140
239                      }
240                  })
241             };
242         }
243         
244         if (!this.parent.el) {
245                 // probably an old style ctor, which has been disabled.
246                 return;
247
248         }
249                 // The 'tree' method is  '_tree now' 
250             
251         tree.region = tree.region || this.region;
252         var is_body = false;
253         if (this.parent.el === true) {
254             // bootstrap... - body..
255             this.parent.el = Roo.factory(tree);
256             is_body = true;
257         }
258         
259         this.el = this.parent.el.addxtype(tree, undefined, is_body);
260         this.fireEvent('built', this);
261         
262         this.panel = this.el;
263         this.layout = this.panel.layout;
264         this.parentLayout = this.parent.layout  || false;  
265          
266     }
267     
268 });
269
270 Roo.apply(Roo.XComponent, {
271     /**
272      * @property  hideProgress
273      * true to disable the building progress bar.. usefull on single page renders.
274      * @type Boolean
275      */
276     hideProgress : false,
277     /**
278      * @property  buildCompleted
279      * True when the builder has completed building the interface.
280      * @type Boolean
281      */
282     buildCompleted : false,
283      
284     /**
285      * @property  topModule
286      * the upper most module - uses document.element as it's constructor.
287      * @type Object
288      */
289      
290     topModule  : false,
291       
292     /**
293      * @property  modules
294      * array of modules to be created by registration system.
295      * @type {Array} of Roo.XComponent
296      */
297     
298     modules : [],
299     /**
300      * @property  elmodules
301      * array of modules to be created by which use #ID 
302      * @type {Array} of Roo.XComponent
303      */
304      
305     elmodules : [],
306
307      /**
308      * @property  is_alt
309      * Is an alternative Root - normally used by bootstrap or other systems,
310      *    where the top element in the tree can wrap 'body' 
311      * @type {boolean}  (default false)
312      */
313      
314     is_alt : false,
315     /**
316      * @property  build_from_html
317      * Build elements from html - used by bootstrap HTML stuff 
318      *    - this is cleared after build is completed
319      * @type {boolean}    (default false)
320      */
321      
322     build_from_html : false,
323     /**
324      * Register components to be built later.
325      *
326      * This solves the following issues
327      * - Building is not done on page load, but after an authentication process has occured.
328      * - Interface elements are registered on page load
329      * - Parent Interface elements may not be loaded before child, so this handles that..
330      * 
331      *
332      * example:
333      * 
334      * MyApp.register({
335           order : '000001',
336           module : 'Pman.Tab.projectMgr',
337           region : 'center',
338           parent : 'Pman.layout',
339           disabled : false,  // or use a function..
340         })
341      
342      * * @param {Object} details about module
343      */
344     register : function(obj) {
345                 
346         Roo.XComponent.event.fireEvent('register', obj);
347         switch(typeof(obj.disabled) ) {
348                 
349             case 'undefined':
350                 break;
351             
352             case 'function':
353                 if ( obj.disabled() ) {
354                         return;
355                 }
356                 break;
357             
358             default:
359                 if (obj.disabled) {
360                         return;
361                 }
362                 break;
363         }
364                 
365         this.modules.push(obj);
366          
367     },
368     /**
369      * convert a string to an object..
370      * eg. 'AAA.BBB' -> finds AAA.BBB
371
372      */
373     
374     toObject : function(str)
375     {
376         if (!str || typeof(str) == 'object') {
377             return str;
378         }
379         if (str.substring(0,1) == '#') {
380             return str;
381         }
382
383         var ar = str.split('.');
384         var rt, o;
385         rt = ar.shift();
386             /** eval:var:o */
387         try {
388             eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
389         } catch (e) {
390             throw "Module not found : " + str;
391         }
392         
393         if (o === false) {
394             throw "Module not found : " + str;
395         }
396         Roo.each(ar, function(e) {
397             if (typeof(o[e]) == 'undefined') {
398                 throw "Module not found : " + str;
399             }
400             o = o[e];
401         });
402         
403         return o;
404         
405     },
406     
407     
408     /**
409      * move modules into their correct place in the tree..
410      * 
411      */
412     preBuild : function ()
413     {
414         var _t = this;
415         Roo.each(this.modules , function (obj)
416         {
417             Roo.XComponent.event.fireEvent('beforebuild', obj);
418             
419             var opar = obj.parent;
420             try { 
421                 obj.parent = this.toObject(opar);
422             } catch(e) {
423                 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
424                 return;
425             }
426             
427             if (!obj.parent) {
428                 Roo.debug && Roo.log("GOT top level module");
429                 Roo.debug && Roo.log(obj);
430                 obj.modules = new Roo.util.MixedCollection(false, 
431                     function(o) { return o.order + '' }
432                 );
433                 this.topModule = obj;
434                 return;
435             }
436                         // parent is a string (usually a dom element name..)
437             if (typeof(obj.parent) == 'string') {
438                 this.elmodules.push(obj);
439                 return;
440             }
441             if (obj.parent.constructor != Roo.XComponent) {
442                 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
443             }
444             if (!obj.parent.modules) {
445                 obj.parent.modules = new Roo.util.MixedCollection(false, 
446                     function(o) { return o.order + '' }
447                 );
448             }
449             if (obj.parent.disabled) {
450                 obj.disabled = true;
451             }
452             obj.parent.modules.add(obj);
453         }, this);
454     },
455     
456      /**
457      * make a list of modules to build.
458      * @return {Array} list of modules. 
459      */ 
460     
461     buildOrder : function()
462     {
463         var _this = this;
464         var cmp = function(a,b) {   
465             return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
466         };
467         if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
468             throw "No top level modules to build";
469         }
470         
471         // make a flat list in order of modules to build.
472         var mods = this.topModule ? [ this.topModule ] : [];
473                 
474         
475         // elmodules (is a list of DOM based modules )
476         Roo.each(this.elmodules, function(e) {
477             mods.push(e);
478             if (!this.topModule &&
479                 typeof(e.parent) == 'string' &&
480                 e.parent.substring(0,1) == '#' &&
481                 Roo.get(e.parent.substr(1))
482                ) {
483                 
484                 _this.topModule = e;
485             }
486             
487         });
488
489         
490         // add modules to their parents..
491         var addMod = function(m) {
492             Roo.debug && Roo.log("build Order: add: " + m.name);
493                 
494             mods.push(m);
495             if (m.modules && !m.disabled) {
496                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
497                 m.modules.keySort('ASC',  cmp );
498                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
499     
500                 m.modules.each(addMod);
501             } else {
502                 Roo.debug && Roo.log("build Order: no child modules");
503             }
504             // not sure if this is used any more..
505             if (m.finalize) {
506                 m.finalize.name = m.name + " (clean up) ";
507                 mods.push(m.finalize);
508             }
509             
510         }
511         if (this.topModule && this.topModule.modules) { 
512             this.topModule.modules.keySort('ASC',  cmp );
513             this.topModule.modules.each(addMod);
514         } 
515         return mods;
516     },
517     
518      /**
519      * Build the registered modules.
520      * @param {Object} parent element.
521      * @param {Function} optional method to call after module has been added.
522      * 
523      */ 
524    
525     build : function(opts) 
526     {
527         
528         if (typeof(opts) != 'undefined') {
529             Roo.apply(this,opts);
530         }
531         
532         this.preBuild();
533         var mods = this.buildOrder();
534       
535         //this.allmods = mods;
536         //Roo.debug && Roo.log(mods);
537         //return;
538         if (!mods.length) { // should not happen
539             throw "NO modules!!!";
540         }
541         
542         
543         var msg = "Building Interface...";
544         // flash it up as modal - so we store the mask!?
545         if (!this.hideProgress && Roo.MessageBox) {
546             Roo.MessageBox.show({ title: 'loading' });
547             Roo.MessageBox.show({
548                title: "Please wait...",
549                msg: msg,
550                width:450,
551                progress:true,
552                closable:false,
553                modal: false
554               
555             });
556         }
557         var total = mods.length;
558         
559         var _this = this;
560         var progressRun = function() {
561             if (!mods.length) {
562                 Roo.debug && Roo.log('hide?');
563                 if (!this.hideProgress && Roo.MessageBox) {
564                     Roo.MessageBox.hide();
565                 }
566                 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
567                 
568                 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
569                 
570                 // THE END...
571                 return false;   
572             }
573             
574             var m = mods.shift();
575             
576             
577             Roo.debug && Roo.log(m);
578             // not sure if this is supported any more.. - modules that are are just function
579             if (typeof(m) == 'function') { 
580                 m.call(this);
581                 return progressRun.defer(10, _this);
582             } 
583             
584             
585             msg = "Building Interface " + (total  - mods.length) + 
586                     " of " + total + 
587                     (m.name ? (' - ' + m.name) : '');
588                         Roo.debug && Roo.log(msg);
589             if (!this.hideProgress &&  Roo.MessageBox) { 
590                 Roo.MessageBox.updateProgress(  (total  - mods.length)/total, msg  );
591             }
592             
593          
594             // is the module disabled?
595             var disabled = (typeof(m.disabled) == 'function') ?
596                 m.disabled.call(m.module.disabled) : m.disabled;    
597             
598             
599             if (disabled) {
600                 return progressRun(); // we do not update the display!
601             }
602             
603             // now build 
604             
605                         
606                         
607             m.render();
608             // it's 10 on top level, and 1 on others??? why...
609             return progressRun.defer(10, _this);
610              
611         }
612         progressRun.defer(1, _this);
613      
614         
615         
616     },
617         
618         
619         /**
620          * Event Object.
621          *
622          *
623          */
624         event: false, 
625     /**
626          * wrapper for event.on - aliased later..  
627          * Typically use to register a event handler for register:
628          *
629          * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
630          *
631          */
632     on : false
633    
634     
635     
636 });
637
638 Roo.XComponent.event = new Roo.util.Observable({
639                 events : { 
640                         /**
641                          * @event register
642                          * Fires when an Component is registered,
643                          * set the disable property on the Component to stop registration.
644                          * @param {Roo.XComponent} c the component being registerd.
645                          * 
646                          */
647                         'register' : true,
648             /**
649                          * @event beforebuild
650                          * Fires before each Component is built
651                          * can be used to apply permissions.
652                          * @param {Roo.XComponent} c the component being registerd.
653                          * 
654                          */
655                         'beforebuild' : true,
656                         /**
657                          * @event buildcomplete
658                          * Fires on the top level element when all elements have been built
659                          * @param {Roo.XComponent} the top level component.
660                          */
661                         'buildcomplete' : true
662                         
663                 }
664 });
665
666 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event); 
667