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