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