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