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