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