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