Uncommited changes synced
[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, tpl)
175     {
176         var item = new Roo.bootstrap.panel.TabItem({
177             panel: this,
178             id : id,
179             text : text,
180             closable : closable,
181             tpl : tpl
182         });
183         this.addTabItem(item);
184         if(content){
185             item.setContent(content);
186         }
187         return item;
188     },
189
190     /**
191      * Returns the {@link Roo.TabPanelItem} with the specified id/index
192      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
193      * @return {Roo.TabPanelItem}
194      */
195     getTab : function(id){
196         return this.items[id];
197     },
198
199     /**
200      * Hides the {@link Roo.TabPanelItem} with the specified id/index
201      * @param {String/Number} id The id or index of the TabPanelItem to hide.
202      */
203     hideTab : function(id){
204         var t = this.items[id];
205         if(!t.isHidden()){
206            t.setHidden(true);
207            this.hiddenCount++;
208            this.autoSizeTabs();
209         }
210     },
211
212     /**
213      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
214      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
215      */
216     unhideTab : function(id){
217         var t = this.items[id];
218         if(t.isHidden()){
219            t.setHidden(false);
220            this.hiddenCount--;
221            this.autoSizeTabs();
222         }
223     },
224
225     /**
226      * Adds an existing {@link Roo.TabPanelItem}.
227      * @param {Roo.TabPanelItem} item The TabPanelItem to add
228      */
229     addTabItem : function(item){
230         this.items[item.id] = item;
231         this.items.push(item);
232       //  if(this.resizeTabs){
233     //       item.setWidth(this.currentTabWidth || this.preferredTabWidth);
234   //         this.autoSizeTabs();
235 //        }else{
236 //            item.autoSize();
237        // }
238     },
239
240     /**
241      * Removes a {@link Roo.TabPanelItem}.
242      * @param {String/Number} id The id or index of the TabPanelItem to remove.
243      */
244     removeTab : function(id){
245         var items = this.items;
246         var tab = items[id];
247         if(!tab) { return; }
248         var index = items.indexOf(tab);
249         if(this.active == tab && items.length > 1){
250             var newTab = this.getNextAvailable(index);
251             if(newTab) {
252                 newTab.activate();
253             }
254         }
255         this.stripEl.dom.removeChild(tab.pnode.dom);
256         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
257             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
258         }
259         items.splice(index, 1);
260         delete this.items[tab.id];
261         tab.fireEvent("close", tab);
262         tab.purgeListeners();
263         this.autoSizeTabs();
264     },
265
266     getNextAvailable : function(start){
267         var items = this.items;
268         var index = start;
269         // look for a next tab that will slide over to
270         // replace the one being removed
271         while(index < items.length){
272             var item = items[++index];
273             if(item && !item.isHidden()){
274                 return item;
275             }
276         }
277         // if one isn't found select the previous tab (on the left)
278         index = start;
279         while(index >= 0){
280             var item = items[--index];
281             if(item && !item.isHidden()){
282                 return item;
283             }
284         }
285         return null;
286     },
287
288     /**
289      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
290      * @param {String/Number} id The id or index of the TabPanelItem to disable.
291      */
292     disableTab : function(id){
293         var tab = this.items[id];
294         if(tab && this.active != tab){
295             tab.disable();
296         }
297     },
298
299     /**
300      * Enables a {@link Roo.TabPanelItem} that is disabled.
301      * @param {String/Number} id The id or index of the TabPanelItem to enable.
302      */
303     enableTab : function(id){
304         var tab = this.items[id];
305         tab.enable();
306     },
307
308     /**
309      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
310      * @param {String/Number} id The id or index of the TabPanelItem to activate.
311      * @return {Roo.TabPanelItem} The TabPanelItem.
312      */
313     activate : function(id){
314         var tab = this.items[id];
315         if(!tab){
316             return null;
317         }
318         if(tab == this.active || tab.disabled){
319             return tab;
320         }
321         var e = {};
322         this.fireEvent("beforetabchange", this, e, tab);
323         if(e.cancel !== true && !tab.disabled){
324             if(this.active){
325                 this.active.hide();
326             }
327             this.active = this.items[id];
328             this.active.show();
329             this.fireEvent("tabchange", this, this.active);
330         }
331         return tab;
332     },
333
334     /**
335      * Gets the active {@link Roo.TabPanelItem}.
336      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
337      */
338     getActiveTab : function(){
339         return this.active;
340     },
341
342     /**
343      * Updates the tab body element to fit the height of the container element
344      * for overflow scrolling
345      * @param {Number} targetHeight (optional) Override the starting height from the elements height
346      */
347     syncHeight : function(targetHeight){
348         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
349         var bm = this.bodyEl.getMargins();
350         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
351         this.bodyEl.setHeight(newHeight);
352         return newHeight;
353     },
354
355     onResize : function(){
356         if(this.monitorResize){
357             this.autoSizeTabs();
358         }
359     },
360
361     /**
362      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
363      */
364     beginUpdate : function(){
365         this.updating = true;
366     },
367
368     /**
369      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
370      */
371     endUpdate : function(){
372         this.updating = false;
373         this.autoSizeTabs();
374     },
375
376     /**
377      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
378      */
379     autoSizeTabs : function(){
380         var count = this.items.length;
381         var vcount = count - this.hiddenCount;
382         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
383             return;
384         }
385         var w = Math.max(this.el.getWidth() - this.cpad, 10);
386         var availWidth = Math.floor(w / vcount);
387         var b = this.stripBody;
388         if(b.getWidth() > w){
389             var tabs = this.items;
390             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
391             if(availWidth < this.minTabWidth){
392                 /*if(!this.sleft){    // incomplete scrolling code
393                     this.createScrollButtons();
394                 }
395                 this.showScroll();
396                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
397             }
398         }else{
399             if(this.currentTabWidth < this.preferredTabWidth){
400                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
401             }
402         }
403     },
404
405     /**
406      * Returns the number of tabs in this TabPanel.
407      * @return {Number}
408      */
409      getCount : function(){
410          return this.items.length;
411      },
412
413     /**
414      * Resizes all the tabs to the passed width
415      * @param {Number} The new width
416      */
417     setTabWidth : function(width){
418         this.currentTabWidth = width;
419         for(var i = 0, len = this.items.length; i < len; i++) {
420                 if(!this.items[i].isHidden()) {
421                 this.items[i].setWidth(width);
422             }
423         }
424     },
425
426     /**
427      * Destroys this TabPanel
428      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
429      */
430     destroy : function(removeEl){
431         Roo.EventManager.removeResizeListener(this.onResize, this);
432         for(var i = 0, len = this.items.length; i < len; i++){
433             this.items[i].purgeListeners();
434         }
435         if(removeEl === true){
436             this.el.update("");
437             this.el.remove();
438         }
439     },
440     
441     createStrip : function(container)
442     {
443         var strip = document.createElement("nav");
444         strip.className = Roo.bootstrap.version == 4 ?
445             "navbar-light bg-light" : 
446             "navbar navbar-default"; //"x-tabs-wrap";
447         container.appendChild(strip);
448         return strip;
449     },
450     
451     createStripList : function(strip)
452     {
453         // div wrapper for retard IE
454         // returns the "tr" element.
455         strip.innerHTML = '<ul class="nav nav-tabs" role="tablist"></ul>';
456         //'<div class="x-tabs-strip-wrap">'+
457           //  '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
458           //  '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
459         return strip.firstChild; //.firstChild.firstChild.firstChild;
460     },
461     createBody : function(container)
462     {
463         var body = document.createElement("div");
464         Roo.id(body, "tab-body");
465         //Roo.fly(body).addClass("x-tabs-body");
466         Roo.fly(body).addClass("tab-content");
467         container.appendChild(body);
468         return body;
469     },
470     createItemBody :function(bodyEl, id){
471         var body = Roo.getDom(id);
472         if(!body){
473             body = document.createElement("div");
474             body.id = id;
475         }
476         //Roo.fly(body).addClass("x-tabs-item-body");
477         Roo.fly(body).addClass("tab-pane");
478          bodyEl.insertBefore(body, bodyEl.firstChild);
479         return body;
480     },
481     /** @private */
482     createStripElements :  function(stripEl, text, closable, tpl)
483     {
484         var td = document.createElement("li"); // was td..
485         td.className = 'nav-item';
486         
487         //stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
488         
489         
490         stripEl.appendChild(td);
491         /*if(closable){
492             td.className = "x-tabs-closable";
493             if(!this.closeTpl){
494                 this.closeTpl = 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>' +
497                    '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
498                 );
499             }
500             var el = this.closeTpl.overwrite(td, {"text": text});
501             var close = el.getElementsByTagName("div")[0];
502             var inner = el.getElementsByTagName("em")[0];
503             return {"el": el, "close": close, "inner": inner};
504         } else {
505         */
506         // not sure what this is..
507 //            if(!this.tabTpl){
508                 //this.tabTpl = new Roo.Template(
509                 //   '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
510                 //   '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
511                 //);
512 //                this.tabTpl = new Roo.Template(
513 //                   '<a href="#">' +
514 //                   '<span unselectable="on"' +
515 //                            (this.disableTooltips ? '' : ' title="{text}"') +
516 //                            ' >{text}</span></a>'
517 //                );
518 //                
519 //            }
520
521
522             var template = tpl || this.tabTpl || false;
523             
524             if(!template){
525                 template =  new Roo.Template(
526                         Roo.bootstrap.version == 4 ? 
527                             (
528                                 '<a class="nav-link" href="#" unselectable="on"' +
529                                      (this.disableTooltips ? '' : ' title="{text}"') +
530                                      ' >{text}</a>'
531                             ) : (
532                                 '<a class="nav-link" href="#">' +
533                                 '<span unselectable="on"' +
534                                          (this.disableTooltips ? '' : ' title="{text}"') +
535                                     ' >{text}</span></a>'
536                             )
537                 );
538             }
539             
540             switch (typeof(template)) {
541                 case 'object' :
542                     break;
543                 case 'string' :
544                     template = new Roo.Template(template);
545                     break;
546                 default :
547                     break;
548             }
549             
550             var el = template.overwrite(td, {"text": text});
551             
552             var inner = el.getElementsByTagName("span")[0];
553             
554             return {"el": el, "inner": inner};
555             
556     }
557         
558     
559 });