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