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