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.bootstrap.paenl.Content
13  * @extends Roo.util.Observable
14  * @children Roo.bootstrap.Component
15  * @parent builder Roo.bootstrap.layout.Border
16  * A basic ContentPanel element. - a panel that contain any content (eg. forms etc.)
17  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
18  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
19  * @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
20  * @cfg {Boolean}   closable      True if the panel can be closed/removed
21  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
22  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
23  * @cfg {Toolbar}   toolbar       A toolbar for this panel
24  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
25  * @cfg {String} title          The title for this panel
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  [required] (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} iframe      contents are an iframe - makes showing remote sources/CSS feasible..
33  * @cfg {Boolean} badges render the badges
34  * @cfg {String} cls  extra classes to use  
35  * @cfg {String} background (primary|secondary|success|info|warning|danger|light|dark)
36  
37  * @constructor
38  * Create a new ContentPanel.
39  * @param {String/Object} config A string to set only the title or a config object
40  
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          * @event scroll
179          * Fires when this content is scrolled
180          * @param {Roo.ContentPanel} this
181          * @param {Event} scrollEvent
182          */
183         "scroll" : true
184         
185         
186         
187     });
188     
189
190     
191     
192     if(this.autoScroll && !this.iframe){
193         this.resizeEl.setStyle("overflow", "auto");
194         this.resizeEl.on('scroll', this.onScroll, this);
195     } else {
196         // fix randome scrolling
197         //this.el.on('scroll', function() {
198         //    Roo.log('fix random scolling');
199         //    this.scrollTo('top',0); 
200         //});
201     }
202     content = content || this.content;
203     if(content){
204         this.setContent(content);
205     }
206     if(config && config.url){
207         this.setUrl(this.url, this.params, this.loadOnce);
208     }
209     
210     
211     
212     Roo.bootstrap.panel.Content.superclass.constructor.call(this);
213     
214     if (this.view && typeof(this.view.xtype) != 'undefined') {
215         this.view.el = this.el.appendChild(document.createElement("div"));
216         this.view = Roo.factory(this.view); 
217         this.view.render  &&  this.view.render(false, '');  
218     }
219     
220     
221     this.fireEvent('render', this);
222 };
223
224 Roo.extend(Roo.bootstrap.panel.Content, Roo.bootstrap.Component, {
225     
226     cls : '',
227     background : '',
228     
229     tabTip : '',
230     
231     iframe : false,
232     iframeEl : false,
233     
234     /* Resize Element - use this to work out scroll etc. */
235     resizeEl : false,
236     
237     setRegion : function(region){
238         this.region = region;
239         this.setActiveClass(region && !this.background);
240     },
241     
242     
243     setActiveClass: function(state)
244     {
245         if(state){
246            this.el.replaceClass("roo-layout-inactive-content", "roo-layout-active-content");
247            this.el.setStyle('position','relative');
248         }else{
249            this.el.replaceClass("roo-layout-active-content", "roo-layout-inactive-content");
250            this.el.setStyle('position', 'absolute');
251         } 
252     },
253     
254     /**
255      * Returns the toolbar for this Panel if one was configured. 
256      * @return {Roo.Toolbar} 
257      */
258     getToolbar : function(){
259         return this.toolbar;
260     },
261     
262     setActiveState : function(active)
263     {
264         this.active = active;
265         this.setActiveClass(active);
266         if(!active){
267             if(this.fireEvent("deactivate", this) === false){
268                 return false;
269             }
270             return true;
271         }
272         this.fireEvent("activate", this);
273         return true;
274     },
275     /**
276      * Updates this panel's element (not for iframe)
277      * @param {String} content The new content
278      * @param {Boolean} loadScripts (optional) true to look for and process scripts
279     */
280     setContent : function(content, loadScripts){
281         if (this.iframe) {
282             return;
283         }
284         
285         this.el.update(content, loadScripts);
286     },
287
288     ignoreResize : function(w, h){
289         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
290             return true;
291         }else{
292             this.lastSize = {width: w, height: h};
293             return false;
294         }
295     },
296     /**
297      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
298      * @return {Roo.UpdateManager} The UpdateManager
299      */
300     getUpdateManager : function(){
301         if (this.iframe) {
302             return false;
303         }
304         return this.el.getUpdateManager();
305     },
306      /**
307      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
308      * Does not work with IFRAME contents
309      * @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:
310 <pre><code>
311 panel.load({
312     url: "your-url.php",
313     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
314     callback: yourFunction,
315     scope: yourObject, //(optional scope)
316     discardUrl: false,
317     nocache: false,
318     text: "Loading...",
319     timeout: 30,
320     scripts: false
321 });
322 </code></pre>
323      
324      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
325      * 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.
326      * @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}
327      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
328      * @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.
329      * @return {Roo.ContentPanel} this
330      */
331     load : function(){
332         
333         if (this.iframe) {
334             return this;
335         }
336         
337         var um = this.el.getUpdateManager();
338         um.update.apply(um, arguments);
339         return this;
340     },
341
342
343     /**
344      * 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.
345      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
346      * @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)
347      * @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)
348      * @return {Roo.UpdateManager|Boolean} The UpdateManager or false if IFRAME
349      */
350     setUrl : function(url, params, loadOnce){
351         if (this.iframe) {
352             this.iframeEl.dom.src = url;
353             return false;
354         }
355         
356         if(this.refreshDelegate){
357             this.removeListener("activate", this.refreshDelegate);
358         }
359         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
360         this.on("activate", this.refreshDelegate);
361         return this.el.getUpdateManager();
362     },
363     
364     _handleRefresh : function(url, params, loadOnce){
365         if(!loadOnce || !this.loaded){
366             var updater = this.el.getUpdateManager();
367             updater.update(url, params, this._setLoaded.createDelegate(this));
368         }
369     },
370     
371     _setLoaded : function(){
372         this.loaded = true;
373     }, 
374     
375     /**
376      * Returns this panel's id
377      * @return {String} 
378      */
379     getId : function(){
380         return this.el.id;
381     },
382     
383     /** 
384      * Returns this panel's element - used by regiosn to add.
385      * @return {Roo.Element} 
386      */
387     getEl : function(){
388         return this.wrapEl || this.el;
389     },
390     
391    
392     
393     adjustForComponents : function(width, height)
394     {
395         //Roo.log('adjustForComponents ');
396         if(this.resizeEl != this.el){
397             width -= this.el.getFrameWidth('lr');
398             height -= this.el.getFrameWidth('tb');
399         }
400         if(this.toolbar){
401             var te = this.toolbar.getEl();
402             te.setWidth(width);
403             height -= te.getHeight();
404         }
405         if(this.footer){
406             var te = this.footer.getEl();
407             te.setWidth(width);
408             height -= te.getHeight();
409         }
410         
411         
412         if(this.adjustments){
413             width += this.adjustments[0];
414             height += this.adjustments[1];
415         }
416         return {"width": width, "height": height};
417     },
418     
419     setSize : function(width, height){
420         if(this.fitToFrame && !this.ignoreResize(width, height)){
421             if(this.fitContainer && this.resizeEl != this.el){
422                 this.el.setSize(width, height);
423             }
424             var size = this.adjustForComponents(width, height);
425             if (this.iframe) {
426                 this.iframeEl.setSize(width,height);
427             }
428             
429             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
430             this.fireEvent('resize', this, size.width, size.height);
431             
432             
433         }
434     },
435     
436     /**
437      * Returns this panel's title
438      * @return {String} 
439      */
440     getTitle : function(){
441         
442         if (typeof(this.title) != 'object') {
443             return this.title;
444         }
445         
446         var t = '';
447         for (var k in this.title) {
448             if (!this.title.hasOwnProperty(k)) {
449                 continue;
450             }
451             
452             if (k.indexOf('-') >= 0) {
453                 var s = k.split('-');
454                 for (var i = 0; i<s.length; i++) {
455                     t += "<span class='visible-"+s[i]+"'>"+this.title[k]+"</span>";
456                 }
457             } else {
458                 t += "<span class='visible-"+k+"'>"+this.title[k]+"</span>";
459             }
460         }
461         return t;
462     },
463     
464     /**
465      * Set this panel's title
466      * @param {String} title
467      */
468     setTitle : function(title){
469         this.title = title;
470         if(this.region){
471             this.region.updatePanelTitle(this, title);
472         }
473     },
474     
475     /**
476      * Returns true is this panel was configured to be closable
477      * @return {Boolean} 
478      */
479     isClosable : function(){
480         return this.closable;
481     },
482     
483     beforeSlide : function(){
484         this.el.clip();
485         this.resizeEl.clip();
486     },
487     
488     afterSlide : function(){
489         this.el.unclip();
490         this.resizeEl.unclip();
491     },
492     
493     /**
494      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
495      *   Will fail silently if the {@link #setUrl} method has not been called.
496      *   This does not activate the panel, just updates its content.
497      */
498     refresh : function(){
499         if(this.refreshDelegate){
500            this.loaded = false;
501            this.refreshDelegate();
502         }
503     },
504     
505     /**
506      * Destroys this panel
507      */
508     destroy : function(){
509         this.el.removeAllListeners();
510         var tempEl = document.createElement("span");
511         tempEl.appendChild(this.el.dom);
512         tempEl.innerHTML = "";
513         this.el.remove();
514         this.el = null;
515     },
516     
517     /**
518      * form - if the content panel contains a form - this is a reference to it.
519      * @type {Roo.form.Form}
520      */
521     form : false,
522     /**
523      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
524      *    This contains a reference to it.
525      * @type {Roo.View}
526      */
527     view : false,
528     
529       /**
530      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
531      * <pre><code>
532
533 layout.addxtype({
534        xtype : 'Form',
535        items: [ .... ]
536    }
537 );
538
539 </code></pre>
540      * @param {Object} cfg Xtype definition of item to add.
541      */
542     
543     
544     getChildContainer: function () {
545         return this.getEl();
546     },
547     
548     
549     onScroll : function(e)
550     {
551         this.fireEvent('scroll', this, e);
552     }
553     
554     
555     /*
556         var  ret = new Roo.factory(cfg);
557         return ret;
558         
559         
560         // add form..
561         if (cfg.xtype.match(/^Form$/)) {
562             
563             var el;
564             //if (this.footer) {
565             //    el = this.footer.container.insertSibling(false, 'before');
566             //} else {
567                 el = this.el.createChild();
568             //}
569
570             this.form = new  Roo.form.Form(cfg);
571             
572             
573             if ( this.form.allItems.length) {
574                 this.form.render(el.dom);
575             }
576             return this.form;
577         }
578         // should only have one of theses..
579         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
580             // views.. should not be just added - used named prop 'view''
581             
582             cfg.el = this.el.appendChild(document.createElement("div"));
583             // factory?
584             
585             var ret = new Roo.factory(cfg);
586              
587              ret.render && ret.render(false, ''); // render blank..
588             this.view = ret;
589             return ret;
590         }
591         return false;
592     }
593     \*/
594 });
595