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         if (this.parent.el === true) {
178             // bootstrap... - body..
179             this.parent.el = Roo.factory(tree);
180         }
181         this.el = this.parent.el.addxtype(tree);
182         this.fireEvent('built', this);
183         
184         this.panel = this.el;
185         this.layout = this.panel.layout;
186                 this.parentLayout = this.parent.layout  || false;  
187          
188     }
189     
190 });
191
192 Roo.apply(Roo.XComponent, {
193     /**
194      * @property  hideProgress
195      * true to disable the building progress bar.. usefull on single page renders.
196      * @type Boolean
197      */
198     hideProgress : false,
199     /**
200      * @property  buildCompleted
201      * True when the builder has completed building the interface.
202      * @type Boolean
203      */
204     buildCompleted : false,
205      
206     /**
207      * @property  topModule
208      * the upper most module - uses document.element as it's constructor.
209      * @type Object
210      */
211      
212     topModule  : false,
213       
214     /**
215      * @property  modules
216      * array of modules to be created by registration system.
217      * @type {Array} of Roo.XComponent
218      */
219     
220     modules : [],
221     /**
222      * @property  elmodules
223      * array of modules to be created by which use #ID 
224      * @type {Array} of Roo.XComponent
225      */
226      
227     elmodules : [],
228
229     
230     /**
231      * Register components to be built later.
232      *
233      * This solves the following issues
234      * - Building is not done on page load, but after an authentication process has occured.
235      * - Interface elements are registered on page load
236      * - Parent Interface elements may not be loaded before child, so this handles that..
237      * 
238      *
239      * example:
240      * 
241      * MyApp.register({
242           order : '000001',
243           module : 'Pman.Tab.projectMgr',
244           region : 'center',
245           parent : 'Pman.layout',
246           disabled : false,  // or use a function..
247         })
248      
249      * * @param {Object} details about module
250      */
251     register : function(obj) {
252                 
253         Roo.XComponent.event.fireEvent('register', obj);
254         switch(typeof(obj.disabled) ) {
255                 
256             case 'undefined':
257                 break;
258             
259             case 'function':
260                 if ( obj.disabled() ) {
261                         return;
262                 }
263                 break;
264             
265             default:
266                 if (obj.disabled) {
267                         return;
268                 }
269                 break;
270         }
271                 
272         this.modules.push(obj);
273          
274     },
275     /**
276      * convert a string to an object..
277      * eg. 'AAA.BBB' -> finds AAA.BBB
278
279      */
280     
281     toObject : function(str)
282     {
283         if (!str || typeof(str) == 'object') {
284             return str;
285         }
286         if (str.substring(0,1) == '#') {
287             return str;
288         }
289
290         var ar = str.split('.');
291         var rt, o;
292         rt = ar.shift();
293             /** eval:var:o */
294         try {
295             eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
296         } catch (e) {
297             throw "Module not found : " + str;
298         }
299         
300         if (o === false) {
301             throw "Module not found : " + str;
302         }
303         Roo.each(ar, function(e) {
304             if (typeof(o[e]) == 'undefined') {
305                 throw "Module not found : " + str;
306             }
307             o = o[e];
308         });
309         
310         return o;
311         
312     },
313     
314     
315     /**
316      * move modules into their correct place in the tree..
317      * 
318      */
319     preBuild : function ()
320     {
321         var _t = this;
322         Roo.each(this.modules , function (obj)
323         {
324             Roo.XComponent.event.fireEvent('beforebuild', obj);
325             
326             var opar = obj.parent;
327             try { 
328                 obj.parent = this.toObject(opar);
329             } catch(e) {
330                 Roo.log("parent:toObject failed: " + e.toString());
331                 return;
332             }
333             
334             if (!obj.parent) {
335                 Roo.debug && Roo.log("GOT top level module");
336                 Roo.debug && Roo.log(obj);
337                 obj.modules = new Roo.util.MixedCollection(false, 
338                     function(o) { return o.order + '' }
339                 );
340                 this.topModule = obj;
341                 return;
342             }
343                         // parent is a string (usually a dom element name..)
344             if (typeof(obj.parent) == 'string') {
345                 this.elmodules.push(obj);
346                 return;
347             }
348             if (obj.parent.constructor != Roo.XComponent) {
349                 Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
350             }
351             if (!obj.parent.modules) {
352                 obj.parent.modules = new Roo.util.MixedCollection(false, 
353                     function(o) { return o.order + '' }
354                 );
355             }
356             if (obj.parent.disabled) {
357                 obj.disabled = true;
358             }
359             obj.parent.modules.add(obj);
360         }, this);
361     },
362     
363      /**
364      * make a list of modules to build.
365      * @return {Array} list of modules. 
366      */ 
367     
368     buildOrder : function()
369     {
370         var _this = this;
371         var cmp = function(a,b) {   
372             return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
373         };
374         if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
375             throw "No top level modules to build";
376         }
377         
378         // make a flat list in order of modules to build.
379         var mods = this.topModule ? [ this.topModule ] : [];
380                 
381         
382         // elmodules (is a list of DOM based modules )
383         Roo.each(this.elmodules, function(e) {
384             mods.push(e);
385             if (!this.topModule &&
386                 typeof(e.parent) == 'string' &&
387                 e.parent.substring(0,1) == '#' &&
388                 Roo.get(e.parent.substr(1))
389                ) {
390                 
391                 _this.topModule = e;
392             }
393             
394         });
395
396         
397         // add modules to their parents..
398         var addMod = function(m) {
399             Roo.debug && Roo.log("build Order: add: " + m.name);
400                 
401             mods.push(m);
402             if (m.modules && !m.disabled) {
403                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
404                 m.modules.keySort('ASC',  cmp );
405                 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
406     
407                 m.modules.each(addMod);
408             } else {
409                 Roo.debug && Roo.log("build Order: no child modules");
410             }
411             // not sure if this is used any more..
412             if (m.finalize) {
413                 m.finalize.name = m.name + " (clean up) ";
414                 mods.push(m.finalize);
415             }
416             
417         }
418         if (this.topModule && this.topModule.modules) { 
419             this.topModule.modules.keySort('ASC',  cmp );
420             this.topModule.modules.each(addMod);
421         } 
422         return mods;
423     },
424     
425      /**
426      * Build the registered modules.
427      * @param {Object} parent element.
428      * @param {Function} optional method to call after module has been added.
429      * 
430      */ 
431    
432     build : function() 
433     {
434         
435         this.preBuild();
436         var mods = this.buildOrder();
437       
438         //this.allmods = mods;
439         //Roo.debug && Roo.log(mods);
440         //return;
441         if (!mods.length) { // should not happen
442             throw "NO modules!!!";
443         }
444         
445         
446         var msg = "Building Interface...";
447         // flash it up as modal - so we store the mask!?
448         if (!this.hideProgress && Roo.MessageBox) {
449             Roo.MessageBox.show({ title: 'loading' });
450             Roo.MessageBox.show({
451                title: "Please wait...",
452                msg: msg,
453                width:450,
454                progress:true,
455                closable:false,
456                modal: false
457               
458             });
459         }
460         var total = mods.length;
461         
462         var _this = this;
463         var progressRun = function() {
464             if (!mods.length) {
465                 Roo.debug && Roo.log('hide?');
466                 if (!this.hideProgress && Roo.MessageBox) {
467                     Roo.MessageBox.hide();
468                 }
469                 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
470                 
471                 // THE END...
472                 return false;   
473             }
474             
475             var m = mods.shift();
476             
477             
478             Roo.debug && Roo.log(m);
479             // not sure if this is supported any more.. - modules that are are just function
480             if (typeof(m) == 'function') { 
481                 m.call(this);
482                 return progressRun.defer(10, _this);
483             } 
484             
485             
486             msg = "Building Interface " + (total  - mods.length) + 
487                     " of " + total + 
488                     (m.name ? (' - ' + m.name) : '');
489                         Roo.debug && Roo.log(msg);
490             if (!this.hideProgress &&  Roo.MessageBox) { 
491                 Roo.MessageBox.updateProgress(  (total  - mods.length)/total, msg  );
492             }
493             
494          
495             // is the module disabled?
496             var disabled = (typeof(m.disabled) == 'function') ?
497                 m.disabled.call(m.module.disabled) : m.disabled;    
498             
499             
500             if (disabled) {
501                 return progressRun(); // we do not update the display!
502             }
503             
504             // now build 
505             
506                         
507                         
508             m.render();
509             // it's 10 on top level, and 1 on others??? why...
510             return progressRun.defer(10, _this);
511              
512         }
513         progressRun.defer(1, _this);
514      
515         
516         
517     },
518         
519         
520         /**
521          * Event Object.
522          *
523          *
524          */
525         event: false, 
526     /**
527          * wrapper for event.on - aliased later..  
528          * Typically use to register a event handler for register:
529          *
530          * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
531          *
532          */
533     on : false
534    
535     
536     
537 });
538
539 Roo.XComponent.event = new Roo.util.Observable({
540                 events : { 
541                         /**
542                          * @event register
543                          * Fires when an Component is registered,
544                          * set the disable property on the Component to stop registration.
545                          * @param {Roo.XComponent} c the component being registerd.
546                          * 
547                          */
548                         'register' : true,
549             /**
550                          * @event beforebuild
551                          * Fires before each Component is built
552                          * can be used to apply permissions.
553                          * @param {Roo.XComponent} c the component being registerd.
554                          * 
555                          */
556                         'beforebuild' : true,
557                         /**
558                          * @event buildcomplete
559                          * Fires on the top level element when all elements have been built
560                          * @param {Roo.XComponent} the top level component.
561                          */
562                         'buildcomplete' : true
563                         
564                 }
565 });
566
567 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event); 
568