Roo/bootstrap/panel/Content.js
[roojs1] / Roo / bootstrap / panel / Content.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11 /**
12  * @class Roo.ContentPanel
13  * @extends Roo.util.Observable
14  * A basic ContentPanel element.
15  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
16  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
17  * @cfg {Boolean/Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
18  * @cfg {Boolean}   closable      True if the panel can be closed/removed
19  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
20  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
21  * @cfg {Toolbar}   toolbar       A toolbar for this panel
22  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
23  * @cfg {String} title          The title for this panel
24  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
25  * @cfg {String} url            Calls {@link #setUrl} with this value
26  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
27  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
28  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
29  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
30  * @cfg {Boolean} badges render the badges
31  * @cfg {String} cls  extra classes to use  
32  * @cfg {String} background (primary|secondary|success|info|warning|danger|light|dark)
33
34  * @constructor
35  * Create a new ContentPanel.
36  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
37  * @param {String/Object} config A string to set only the title or a config object
38  * @param {String} content (optional) Set the HTML content for this panel
39  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
40  */
41 Roo.bootstrap.panel.Content = function( config){
42     
43     this.tpl = config.tpl || false;
44     
45     var el = config.el;
46     var content = config.content;
47
48     if(config.autoCreate){ // xtype is available if this is called from factory
49         el = Roo.id();
50     }
51     this.el = Roo.get(el);
52     if(!this.el && config && config.autoCreate){
53         if(typeof config.autoCreate == "object"){
54             if(!config.autoCreate.id){
55                 config.autoCreate.id = config.id||el;
56             }
57             this.el = Roo.DomHelper.append(document.body,
58                         config.autoCreate, true);
59         }else{
60             var elcfg =  {
61                 tag: "div",
62                 cls: "roo-layout-inactive-content",
63                 id: config.id||el
64             };
65             if (config.html) {
66                 elcfg.html = config.html;
67                 
68             }
69                         
70             this.el = Roo.DomHelper.append(document.body, elcfg , true);
71         }
72     } 
73     this.closable = false;
74     this.loaded = false;
75     this.active = false;
76    
77       
78     if (config.toolbar && !config.toolbar.el && config.toolbar.xtype) {
79         
80         this.toolbar = new config.toolbar.xns[config.toolbar.xtype](config.toolbar);
81         
82         this.wrapEl = this.el; //this.el.wrap();
83         var ti = [];
84         if (config.toolbar.items) {
85             ti = config.toolbar.items ;
86             delete config.toolbar.items ;
87         }
88         
89         var nitems = [];
90         this.toolbar.render(this.wrapEl, 'before');
91         for(var i =0;i < ti.length;i++) {
92           //  Roo.log(['add child', items[i]]);
93             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
94         }
95         this.toolbar.items = nitems;
96         this.toolbar.el.insertBefore(this.wrapEl.dom.firstChild);
97         delete config.toolbar;
98         
99     }
100     /*
101     // xtype created footer. - not sure if will work as we normally have to render first..
102     if (this.footer && !this.footer.el && this.footer.xtype) {
103         if (!this.wrapEl) {
104             this.wrapEl = this.el.wrap();
105         }
106     
107         this.footer.container = this.wrapEl.createChild();
108          
109         this.footer = Roo.factory(this.footer, Roo);
110         
111     }
112     */
113     
114      if(typeof config == "string"){
115         this.title = config;
116     }else{
117         Roo.apply(this, config);
118     }
119     
120     if(this.resizeEl){
121         this.resizeEl = Roo.get(this.resizeEl, true);
122     }else{
123         this.resizeEl = this.el;
124     }
125     // handle view.xtype
126     
127  
128     
129     
130     this.addEvents({
131         /**
132          * @event activate
133          * Fires when this panel is activated. 
134          * @param {Roo.ContentPanel} this
135          */
136         "activate" : true,
137         /**
138          * @event deactivate
139          * Fires when this panel is activated. 
140          * @param {Roo.ContentPanel} this
141          */
142         "deactivate" : true,
143
144         /**
145          * @event resize
146          * Fires when this panel is resized if fitToFrame is true.
147          * @param {Roo.ContentPanel} this
148          * @param {Number} width The width after any component adjustments
149          * @param {Number} height The height after any component adjustments
150          */
151         "resize" : true,
152         
153          /**
154          * @event render
155          * Fires when this tab is created
156          * @param {Roo.ContentPanel} this
157          */
158         "render" : true
159         
160         
161         
162     });
163     
164
165     
166     
167     if(this.autoScroll){
168         this.resizeEl.setStyle("overflow", "auto");
169     } else {
170         // fix randome scrolling
171         //this.el.on('scroll', function() {
172         //    Roo.log('fix random scolling');
173         //    this.scrollTo('top',0); 
174         //});
175     }
176     content = content || this.content;
177     if(content){
178         this.setContent(content);
179     }
180     if(config && config.url){
181         this.setUrl(this.url, this.params, this.loadOnce);
182     }
183     
184     
185     
186     Roo.bootstrap.panel.Content.superclass.constructor.call(this);
187     
188     if (this.view && typeof(this.view.xtype) != 'undefined') {
189         this.view.el = this.el.appendChild(document.createElement("div"));
190         this.view = Roo.factory(this.view); 
191         this.view.render  &&  this.view.render(false, '');  
192     }
193     
194     
195     this.fireEvent('render', this);
196 };
197
198 Roo.extend(Roo.bootstrap.panel.Content, Roo.bootstrap.Component, {
199     
200     tabTip : '',
201     
202     setRegion : function(region){
203         this.region = region;
204         this.setActiveClass(region && !this.background);
205     },
206     
207     
208     setActiveClass: function(state)
209     {
210         if(state){
211            this.el.replaceClass("roo-layout-inactive-content", "roo-layout-active-content");
212            this.el.setStyle('position','relative');
213         }else{
214            this.el.replaceClass("roo-layout-active-content", "roo-layout-inactive-content");
215            this.el.setStyle('position', 'absolute');
216         } 
217     },
218     
219     /**
220      * Returns the toolbar for this Panel if one was configured. 
221      * @return {Roo.Toolbar} 
222      */
223     getToolbar : function(){
224         return this.toolbar;
225     },
226     
227     setActiveState : function(active)
228     {
229         this.active = active;
230         this.setActiveClass(active);
231         if(!active){
232             if(this.fireEvent("deactivate", this) === false){
233                 return false;
234             }
235             return true;
236         }
237         this.fireEvent("activate", this);
238         return true;
239     },
240     /**
241      * Updates this panel's element
242      * @param {String} content The new content
243      * @param {Boolean} loadScripts (optional) true to look for and process scripts
244     */
245     setContent : function(content, loadScripts){
246         this.el.update(content, loadScripts);
247     },
248
249     ignoreResize : function(w, h){
250         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
251             return true;
252         }else{
253             this.lastSize = {width: w, height: h};
254             return false;
255         }
256     },
257     /**
258      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
259      * @return {Roo.UpdateManager} The UpdateManager
260      */
261     getUpdateManager : function(){
262         return this.el.getUpdateManager();
263     },
264      /**
265      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
266      * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
267 <pre><code>
268 panel.load({
269     url: "your-url.php",
270     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
271     callback: yourFunction,
272     scope: yourObject, //(optional scope)
273     discardUrl: false,
274     nocache: false,
275     text: "Loading...",
276     timeout: 30,
277     scripts: false
278 });
279 </code></pre>
280      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
281      * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
282      * @param {String/Object} params (optional) The parameters to pass as either a URL encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
283      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
284      * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
285      * @return {Roo.ContentPanel} this
286      */
287     load : function(){
288         var um = this.el.getUpdateManager();
289         um.update.apply(um, arguments);
290         return this;
291     },
292
293
294     /**
295      * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
296      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
297      * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
298      * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
299      * @return {Roo.UpdateManager} The UpdateManager
300      */
301     setUrl : function(url, params, loadOnce){
302         if(this.refreshDelegate){
303             this.removeListener("activate", this.refreshDelegate);
304         }
305         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
306         this.on("activate", this.refreshDelegate);
307         return this.el.getUpdateManager();
308     },
309     
310     _handleRefresh : function(url, params, loadOnce){
311         if(!loadOnce || !this.loaded){
312             var updater = this.el.getUpdateManager();
313             updater.update(url, params, this._setLoaded.createDelegate(this));
314         }
315     },
316     
317     _setLoaded : function(){
318         this.loaded = true;
319     }, 
320     
321     /**
322      * Returns this panel's id
323      * @return {String} 
324      */
325     getId : function(){
326         return this.el.id;
327     },
328     
329     /** 
330      * Returns this panel's element - used by regiosn to add.
331      * @return {Roo.Element} 
332      */
333     getEl : function(){
334         return this.wrapEl || this.el;
335     },
336     
337    
338     
339     adjustForComponents : function(width, height)
340     {
341         //Roo.log('adjustForComponents ');
342         if(this.resizeEl != this.el){
343             width -= this.el.getFrameWidth('lr');
344             height -= this.el.getFrameWidth('tb');
345         }
346         if(this.toolbar){
347             var te = this.toolbar.getEl();
348             te.setWidth(width);
349             height -= te.getHeight();
350         }
351         if(this.footer){
352             var te = this.footer.getEl();
353             te.setWidth(width);
354             height -= te.getHeight();
355         }
356         
357         
358         if(this.adjustments){
359             width += this.adjustments[0];
360             height += this.adjustments[1];
361         }
362         return {"width": width, "height": height};
363     },
364     
365     setSize : function(width, height){
366         if(this.fitToFrame && !this.ignoreResize(width, height)){
367             if(this.fitContainer && this.resizeEl != this.el){
368                 this.el.setSize(width, height);
369             }
370             var size = this.adjustForComponents(width, height);
371             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
372             this.fireEvent('resize', this, size.width, size.height);
373         }
374     },
375     
376     /**
377      * Returns this panel's title
378      * @return {String} 
379      */
380     getTitle : function(){
381         
382         if (typeof(this.title) != 'object') {
383             return this.title;
384         }
385         
386         var t = '';
387         for (var k in this.title) {
388             if (!this.title.hasOwnProperty(k)) {
389                 continue;
390             }
391             
392             if (k.indexOf('-') >= 0) {
393                 var s = k.split('-');
394                 for (var i = 0; i<s.length; i++) {
395                     t += "<span class='visible-"+s[i]+"'>"+this.title[k]+"</span>";
396                 }
397             } else {
398                 t += "<span class='visible-"+k+"'>"+this.title[k]+"</span>";
399             }
400         }
401         return t;
402     },
403     
404     /**
405      * Set this panel's title
406      * @param {String} title
407      */
408     setTitle : function(title){
409         this.title = title;
410         if(this.region){
411             this.region.updatePanelTitle(this, title);
412         }
413     },
414     
415     /**
416      * Returns true is this panel was configured to be closable
417      * @return {Boolean} 
418      */
419     isClosable : function(){
420         return this.closable;
421     },
422     
423     beforeSlide : function(){
424         this.el.clip();
425         this.resizeEl.clip();
426     },
427     
428     afterSlide : function(){
429         this.el.unclip();
430         this.resizeEl.unclip();
431     },
432     
433     /**
434      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
435      *   Will fail silently if the {@link #setUrl} method has not been called.
436      *   This does not activate the panel, just updates its content.
437      */
438     refresh : function(){
439         if(this.refreshDelegate){
440            this.loaded = false;
441            this.refreshDelegate();
442         }
443     },
444     
445     /**
446      * Destroys this panel
447      */
448     destroy : function(){
449         this.el.removeAllListeners();
450         var tempEl = document.createElement("span");
451         tempEl.appendChild(this.el.dom);
452         tempEl.innerHTML = "";
453         this.el.remove();
454         this.el = null;
455     },
456     
457     /**
458      * form - if the content panel contains a form - this is a reference to it.
459      * @type {Roo.form.Form}
460      */
461     form : false,
462     /**
463      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
464      *    This contains a reference to it.
465      * @type {Roo.View}
466      */
467     view : false,
468     
469       /**
470      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
471      * <pre><code>
472
473 layout.addxtype({
474        xtype : 'Form',
475        items: [ .... ]
476    }
477 );
478
479 </code></pre>
480      * @param {Object} cfg Xtype definition of item to add.
481      */
482     
483     
484     getChildContainer: function () {
485         return this.getEl();
486     }
487     
488     
489     /*
490         var  ret = new Roo.factory(cfg);
491         return ret;
492         
493         
494         // add form..
495         if (cfg.xtype.match(/^Form$/)) {
496             
497             var el;
498             //if (this.footer) {
499             //    el = this.footer.container.insertSibling(false, 'before');
500             //} else {
501                 el = this.el.createChild();
502             //}
503
504             this.form = new  Roo.form.Form(cfg);
505             
506             
507             if ( this.form.allItems.length) {
508                 this.form.render(el.dom);
509             }
510             return this.form;
511         }
512         // should only have one of theses..
513         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
514             // views.. should not be just added - used named prop 'view''
515             
516             cfg.el = this.el.appendChild(document.createElement("div"));
517             // factory?
518             
519             var ret = new Roo.factory(cfg);
520              
521              ret.render && ret.render(false, ''); // render blank..
522             this.view = ret;
523             return ret;
524         }
525         return false;
526     }
527     \*/
528 });
529