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