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