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