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