Roo/bootstrap/panel/Tabs.js
[roojs1] / Roo / bootstrap / panel / Tabs.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.TabPanel
13  * @extends Roo.util.Observable
14  * A lightweight tab container.
15  * <br><br>
16  * Usage:
17  * <pre><code>
18 // basic tabs 1, built from existing content
19 var tabs = new Roo.TabPanel("tabs1");
20 tabs.addTab("script", "View Script");
21 tabs.addTab("markup", "View Markup");
22 tabs.activate("script");
23
24 // more advanced tabs, built from javascript
25 var jtabs = new Roo.TabPanel("jtabs");
26 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
27
28 // set up the UpdateManager
29 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
30 var updater = tab2.getUpdateManager();
31 updater.setDefaultUrl("ajax1.htm");
32 tab2.on('activate', updater.refresh, updater, true);
33
34 // Use setUrl for Ajax loading
35 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
36 tab3.setUrl("ajax2.htm", null, true);
37
38 // Disabled tab
39 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
40 tab4.disable();
41
42 jtabs.activate("jtabs-1");
43  * </code></pre>
44  * @constructor
45  * Create a new TabPanel.
46  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
47  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
48  */
49 Roo.bootstrap.panel.Tabs = function(config){
50     /**
51     * The container element for this TabPanel.
52     * @type Roo.Element
53     */
54     this.el = Roo.get(config.el, true);
55     if(config){
56         if(typeof config == "boolean"){
57             this.tabPosition = config ? "bottom" : "top";
58         }else{
59             Roo.apply(this, config);
60         }
61     }
62     
63     if(this.tabPosition == "bottom"){
64         this.bodyEl = Roo.get(this.createBody(this.el.dom));
65         this.el.addClass("roo-tabs-bottom");
66     }
67     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
68     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
69     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
70     if(Roo.isIE){
71         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
72     }
73     if(this.tabPosition != "bottom"){
74         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
75          * @type Roo.Element
76          */
77         this.bodyEl = Roo.get(this.createBody(this.el.dom));
78         this.el.addClass("x-tabs-top");
79     }
80     this.items = [];
81
82     this.bodyEl.setStyle("position", "relative");
83
84     this.active = null;
85     this.activateDelegate = this.activate.createDelegate(this);
86
87     this.addEvents({
88         /**
89          * @event tabchange
90          * Fires when the active tab changes
91          * @param {Roo.TabPanel} this
92          * @param {Roo.TabPanelItem} activePanel The new active tab
93          */
94         "tabchange": true,
95         /**
96          * @event beforetabchange
97          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
98          * @param {Roo.TabPanel} this
99          * @param {Object} e Set cancel to true on this object to cancel the tab change
100          * @param {Roo.TabPanelItem} tab The tab being changed to
101          */
102         "beforetabchange" : true
103     });
104
105     Roo.EventManager.onWindowResize(this.onResize, this);
106     this.cpad = this.el.getPadding("lr");
107     this.hiddenCount = 0;
108
109
110     // toolbar on the tabbar support...
111     if (this.toolbar) {
112         alert("no toolbar support yet");
113         this.toolbar  = false;
114         /*
115         var tcfg = this.toolbar;
116         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
117         this.toolbar = new Roo.Toolbar(tcfg);
118         if (Roo.isSafari) {
119             var tbl = tcfg.container.child('table', true);
120             tbl.setAttribute('width', '100%');
121         }
122         */
123         
124     }
125    
126
127
128     Roo.TabPanel.superclass.constructor.call(this);
129 };
130
131 Roo.extend(Roo.bootstrap.panel.Tabs, Roo.util.Observable, {
132     /*
133      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
134      */
135     tabPosition : "top",
136     /*
137      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
138      */
139     currentTabWidth : 0,
140     /*
141      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
142      */
143     minTabWidth : 40,
144     /*
145      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
146      */
147     maxTabWidth : 250,
148     /*
149      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
150      */
151     preferredTabWidth : 175,
152     /*
153      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
154      */
155     resizeTabs : false,
156     /*
157      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
158      */
159     monitorResize : true,
160     /*
161      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
162      */
163     toolbar : false,
164
165     /**
166      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
167      * @param {String} id The id of the div to use <b>or create</b>
168      * @param {String} text The text for the tab
169      * @param {String} content (optional) Content to put in the TabPanelItem body
170      * @param {Boolean} closable (optional) True to create a close icon on the tab
171      * @return {Roo.TabPanelItem} The created TabPanelItem
172      */
173     addTab : function(id, text, content, closable)
174     {
175         var item = Roo.bootstrap.panel.TabItem({
176             panel: this,
177             id : id,
178             text : text,
179             closable : closable
180         });
181         this.addTabItem(item);
182         if(content){
183             item.setContent(content);
184         }
185         return item;
186     },
187
188     /**
189      * Returns the {@link Roo.TabPanelItem} with the specified id/index
190      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
191      * @return {Roo.TabPanelItem}
192      */
193     getTab : function(id){
194         return this.items[id];
195     },
196
197     /**
198      * Hides the {@link Roo.TabPanelItem} with the specified id/index
199      * @param {String/Number} id The id or index of the TabPanelItem to hide.
200      */
201     hideTab : function(id){
202         var t = this.items[id];
203         if(!t.isHidden()){
204            t.setHidden(true);
205            this.hiddenCount++;
206            this.autoSizeTabs();
207         }
208     },
209
210     /**
211      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
212      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
213      */
214     unhideTab : function(id){
215         var t = this.items[id];
216         if(t.isHidden()){
217            t.setHidden(false);
218            this.hiddenCount--;
219            this.autoSizeTabs();
220         }
221     },
222
223     /**
224      * Adds an existing {@link Roo.TabPanelItem}.
225      * @param {Roo.TabPanelItem} item The TabPanelItem to add
226      */
227     addTabItem : function(item){
228         this.items[item.id] = item;
229         this.items.push(item);
230         if(this.resizeTabs){
231            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
232            this.autoSizeTabs();
233         }else{
234             item.autoSize();
235         }
236     },
237
238     /**
239      * Removes a {@link Roo.TabPanelItem}.
240      * @param {String/Number} id The id or index of the TabPanelItem to remove.
241      */
242     removeTab : function(id){
243         var items = this.items;
244         var tab = items[id];
245         if(!tab) { return; }
246         var index = items.indexOf(tab);
247         if(this.active == tab && items.length > 1){
248             var newTab = this.getNextAvailable(index);
249             if(newTab) {
250                 newTab.activate();
251             }
252         }
253         this.stripEl.dom.removeChild(tab.pnode.dom);
254         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
255             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
256         }
257         items.splice(index, 1);
258         delete this.items[tab.id];
259         tab.fireEvent("close", tab);
260         tab.purgeListeners();
261         this.autoSizeTabs();
262     },
263
264     getNextAvailable : function(start){
265         var items = this.items;
266         var index = start;
267         // look for a next tab that will slide over to
268         // replace the one being removed
269         while(index < items.length){
270             var item = items[++index];
271             if(item && !item.isHidden()){
272                 return item;
273             }
274         }
275         // if one isn't found select the previous tab (on the left)
276         index = start;
277         while(index >= 0){
278             var item = items[--index];
279             if(item && !item.isHidden()){
280                 return item;
281             }
282         }
283         return null;
284     },
285
286     /**
287      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
288      * @param {String/Number} id The id or index of the TabPanelItem to disable.
289      */
290     disableTab : function(id){
291         var tab = this.items[id];
292         if(tab && this.active != tab){
293             tab.disable();
294         }
295     },
296
297     /**
298      * Enables a {@link Roo.TabPanelItem} that is disabled.
299      * @param {String/Number} id The id or index of the TabPanelItem to enable.
300      */
301     enableTab : function(id){
302         var tab = this.items[id];
303         tab.enable();
304     },
305
306     /**
307      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
308      * @param {String/Number} id The id or index of the TabPanelItem to activate.
309      * @return {Roo.TabPanelItem} The TabPanelItem.
310      */
311     activate : function(id){
312         var tab = this.items[id];
313         if(!tab){
314             return null;
315         }
316         if(tab == this.active || tab.disabled){
317             return tab;
318         }
319         var e = {};
320         this.fireEvent("beforetabchange", this, e, tab);
321         if(e.cancel !== true && !tab.disabled){
322             if(this.active){
323                 this.active.hide();
324             }
325             this.active = this.items[id];
326             this.active.show();
327             this.fireEvent("tabchange", this, this.active);
328         }
329         return tab;
330     },
331
332     /**
333      * Gets the active {@link Roo.TabPanelItem}.
334      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
335      */
336     getActiveTab : function(){
337         return this.active;
338     },
339
340     /**
341      * Updates the tab body element to fit the height of the container element
342      * for overflow scrolling
343      * @param {Number} targetHeight (optional) Override the starting height from the elements height
344      */
345     syncHeight : function(targetHeight){
346         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
347         var bm = this.bodyEl.getMargins();
348         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
349         this.bodyEl.setHeight(newHeight);
350         return newHeight;
351     },
352
353     onResize : function(){
354         if(this.monitorResize){
355             this.autoSizeTabs();
356         }
357     },
358
359     /**
360      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
361      */
362     beginUpdate : function(){
363         this.updating = true;
364     },
365
366     /**
367      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
368      */
369     endUpdate : function(){
370         this.updating = false;
371         this.autoSizeTabs();
372     },
373
374     /**
375      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
376      */
377     autoSizeTabs : function(){
378         var count = this.items.length;
379         var vcount = count - this.hiddenCount;
380         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
381             return;
382         }
383         var w = Math.max(this.el.getWidth() - this.cpad, 10);
384         var availWidth = Math.floor(w / vcount);
385         var b = this.stripBody;
386         if(b.getWidth() > w){
387             var tabs = this.items;
388             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
389             if(availWidth < this.minTabWidth){
390                 /*if(!this.sleft){    // incomplete scrolling code
391                     this.createScrollButtons();
392                 }
393                 this.showScroll();
394                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
395             }
396         }else{
397             if(this.currentTabWidth < this.preferredTabWidth){
398                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
399             }
400         }
401     },
402
403     /**
404      * Returns the number of tabs in this TabPanel.
405      * @return {Number}
406      */
407      getCount : function(){
408          return this.items.length;
409      },
410
411     /**
412      * Resizes all the tabs to the passed width
413      * @param {Number} The new width
414      */
415     setTabWidth : function(width){
416         this.currentTabWidth = width;
417         for(var i = 0, len = this.items.length; i < len; i++) {
418                 if(!this.items[i].isHidden()) {
419                 this.items[i].setWidth(width);
420             }
421         }
422     },
423
424     /**
425      * Destroys this TabPanel
426      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
427      */
428     destroy : function(removeEl){
429         Roo.EventManager.removeResizeListener(this.onResize, this);
430         for(var i = 0, len = this.items.length; i < len; i++){
431             this.items[i].purgeListeners();
432         }
433         if(removeEl === true){
434             this.el.update("");
435             this.el.remove();
436         }
437     },
438     
439     createStrip : function(container)
440     {
441         var strip = document.createElement("nav");
442         strip.className = "navbar navbar-default"; //"x-tabs-wrap";
443         container.appendChild(strip);
444         return strip;
445     },
446     
447     createStripList : function(strip)
448     {
449         // div wrapper for retard IE
450         // returns the "tr" element.
451         strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
452             '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
453             '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
454         return strip.firstChild.firstChild.firstChild.firstChild;
455     },
456     createBody : function(container)
457     {
458         var body = document.createElement("div");
459         Roo.id(body, "tab-body");
460         Roo.fly(body).addClass("x-tabs-body");
461         container.appendChild(body);
462         return body;
463     },
464     createItemBody :function(bodyEl, id){
465         var body = Roo.getDom(id);
466         if(!body){
467             body = document.createElement("div");
468             body.id = id;
469         }
470         Roo.fly(body).addClass("x-tabs-item-body");
471         bodyEl.insertBefore(body, bodyEl.firstChild);
472         return body;
473     },
474     /** @private */
475     createStripElements :  function(stripEl, text, closable){
476         var td = document.createElement("td");
477         stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
478         //stripEl.appendChild(td);
479         if(closable){
480             td.className = "x-tabs-closable";
481             if(!this.closeTpl){
482                 this.closeTpl = new Roo.Template(
483                    '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
484                    '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
485                    '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
486                 );
487             }
488             var el = this.closeTpl.overwrite(td, {"text": text});
489             var close = el.getElementsByTagName("div")[0];
490             var inner = el.getElementsByTagName("em")[0];
491             return {"el": el, "close": close, "inner": inner};
492         } else {
493             if(!this.tabTpl){
494                 this.tabTpl = new Roo.Template(
495                    '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
496                    '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
497                 );
498             }
499             var el = this.tabTpl.overwrite(td, {"text": text});
500             var inner = el.getElementsByTagName("em")[0];
501             return {"el": el, "inner": inner};
502         }
503     }
504         
505     
506 });