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