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