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