Upgrade to ExtJS 3.2.1 - Released 04/27/2010
[extjs.git] / src / widgets / layout / ToolbarLayout.js
1 /*!
2  * Ext JS Library 3.2.1
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.layout.ToolbarLayout
9  * @extends Ext.layout.ContainerLayout
10  * Layout manager used by Ext.Toolbar. This is highly specialised for use by Toolbars and would not
11  * usually be used by any other class.
12  */
13 Ext.layout.ToolbarLayout = Ext.extend(Ext.layout.ContainerLayout, {
14     monitorResize : true,
15
16     type: 'toolbar',
17
18     /**
19      * @property triggerWidth
20      * @type Number
21      * The width allocated for the menu trigger at the extreme right end of the Toolbar
22      */
23     triggerWidth: 18,
24
25     /**
26      * @property noItemsMenuText
27      * @type String
28      * HTML fragment to render into the toolbar overflow menu if there are no items to display
29      */
30     noItemsMenuText : '<div class="x-toolbar-no-items">(None)</div>',
31
32     /**
33      * @private
34      * @property lastOverflow
35      * @type Boolean
36      * Used internally to record whether the last layout caused an overflow or not
37      */
38     lastOverflow: false,
39
40     /**
41      * @private
42      * @property tableHTML
43      * @type String
44      * String used to build the HTML injected to support the Toolbar's layout. The align property is
45      * injected into this string inside the td.x-toolbar-left element during onLayout.
46      */
47     tableHTML: [
48         '<table cellspacing="0" class="x-toolbar-ct">',
49             '<tbody>',
50                 '<tr>',
51                     '<td class="x-toolbar-left" align="{0}">',
52                         '<table cellspacing="0">',
53                             '<tbody>',
54                                 '<tr class="x-toolbar-left-row"></tr>',
55                             '</tbody>',
56                         '</table>',
57                     '</td>',
58                     '<td class="x-toolbar-right" align="right">',
59                         '<table cellspacing="0" class="x-toolbar-right-ct">',
60                             '<tbody>',
61                                 '<tr>',
62                                     '<td>',
63                                         '<table cellspacing="0">',
64                                             '<tbody>',
65                                                 '<tr class="x-toolbar-right-row"></tr>',
66                                             '</tbody>',
67                                         '</table>',
68                                     '</td>',
69                                     '<td>',
70                                         '<table cellspacing="0">',
71                                             '<tbody>',
72                                                 '<tr class="x-toolbar-extras-row"></tr>',
73                                             '</tbody>',
74                                         '</table>',
75                                     '</td>',
76                                 '</tr>',
77                             '</tbody>',
78                         '</table>',
79                     '</td>',
80                 '</tr>',
81             '</tbody>',
82         '</table>'
83     ].join(""),
84
85     /**
86      * @private
87      * Create the wrapping Toolbar HTML and render/move all the items into the correct places
88      */
89     onLayout : function(ct, target) {
90         //render the Toolbar <table> HTML if it's not already present
91         if (!this.leftTr) {
92             var align = ct.buttonAlign == 'center' ? 'center' : 'left';
93
94             target.addClass('x-toolbar-layout-ct');
95             target.insertHtml('beforeEnd', String.format(this.tableHTML, align));
96
97             this.leftTr   = target.child('tr.x-toolbar-left-row', true);
98             this.rightTr  = target.child('tr.x-toolbar-right-row', true);
99             this.extrasTr = target.child('tr.x-toolbar-extras-row', true);
100
101             if (this.hiddenItem == undefined) {
102                 /**
103                  * @property hiddenItems
104                  * @type Array
105                  * Holds all items that are currently hidden due to there not being enough space to render them
106                  * These items will appear on the expand menu.
107                  */
108                 this.hiddenItems = [];
109             }
110         }
111
112         var side     = ct.buttonAlign == 'right' ? this.rightTr : this.leftTr,
113             items    = ct.items.items,
114             position = 0;
115
116         //render each item if not already rendered, place it into the correct (left or right) target
117         for (var i = 0, len = items.length, c; i < len; i++, position++) {
118             c = items[i];
119
120             if (c.isFill) {
121                 side   = this.rightTr;
122                 position = -1;
123             } else if (!c.rendered) {
124                 c.render(this.insertCell(c, side, position));
125             } else {
126                 if (!c.xtbHidden && !this.isValidParent(c, side.childNodes[position])) {
127                     var td = this.insertCell(c, side, position);
128                     td.appendChild(c.getPositionEl().dom);
129                     c.container = Ext.get(td);
130                 }
131             }
132         }
133
134         //strip extra empty cells
135         this.cleanup(this.leftTr);
136         this.cleanup(this.rightTr);
137         this.cleanup(this.extrasTr);
138         this.fitToSize(target);
139     },
140
141     /**
142      * @private
143      * Removes any empty nodes from the given element
144      * @param {Ext.Element} el The element to clean up
145      */
146     cleanup : function(el) {
147         var cn = el.childNodes, i, c;
148
149         for (i = cn.length-1; i >= 0 && (c = cn[i]); i--) {
150             if (!c.firstChild) {
151                 el.removeChild(c);
152             }
153         }
154     },
155
156     /**
157      * @private
158      * Inserts the given Toolbar item into the given element
159      * @param {Ext.Component} c The component to add
160      * @param {Ext.Element} target The target to add the component to
161      * @param {Number} position The position to add the component at
162      */
163     insertCell : function(c, target, position) {
164         var td = document.createElement('td');
165         td.className = 'x-toolbar-cell';
166
167         target.insertBefore(td, target.childNodes[position] || null);
168
169         return td;
170     },
171
172     /**
173      * @private
174      * Hides an item because it will not fit in the available width. The item will be unhidden again
175      * if the Toolbar is resized to be large enough to show it
176      * @param {Ext.Component} item The item to hide
177      */
178     hideItem : function(item) {
179         this.hiddenItems.push(item);
180
181         item.xtbHidden = true;
182         item.xtbWidth = item.getPositionEl().dom.parentNode.offsetWidth;
183         item.hide();
184     },
185
186     /**
187      * @private
188      * Unhides an item that was previously hidden due to there not being enough space left on the Toolbar
189      * @param {Ext.Component} item The item to show
190      */
191     unhideItem : function(item) {
192         item.show();
193         item.xtbHidden = false;
194         this.hiddenItems.remove(item);
195     },
196
197     /**
198      * @private
199      * Returns the width of the given toolbar item. If the item is currently hidden because there
200      * is not enough room to render it, its previous width is returned
201      * @param {Ext.Component} c The component to measure
202      * @return {Number} The width of the item
203      */
204     getItemWidth : function(c) {
205         return c.hidden ? (c.xtbWidth || 0) : c.getPositionEl().dom.parentNode.offsetWidth;
206     },
207
208     /**
209      * @private
210      * Called at the end of onLayout. At this point the Toolbar has already been resized, so we need
211      * to fit the items into the available width. We add up the width required by all of the items in
212      * the toolbar - if we don't have enough space we hide the extra items and render the expand menu
213      * trigger.
214      * @param {Ext.Element} target The Element the Toolbar is currently laid out within
215      */
216     fitToSize : function(target) {
217         if (this.container.enableOverflow === false) {
218             return;
219         }
220
221         var width       = target.dom.clientWidth,
222             tableWidth  = target.dom.firstChild.offsetWidth,
223             clipWidth   = width - this.triggerWidth,
224             lastWidth   = this.lastWidth || 0,
225
226             hiddenItems = this.hiddenItems,
227             hasHiddens  = hiddenItems.length != 0,
228             isLarger    = width >= lastWidth;
229
230         this.lastWidth  = width;
231
232         if (tableWidth > width || (hasHiddens && isLarger)) {
233             var items     = this.container.items.items,
234                 len       = items.length,
235                 loopWidth = 0,
236                 item;
237
238             for (var i = 0; i < len; i++) {
239                 item = items[i];
240
241                 if (!item.isFill) {
242                     loopWidth += this.getItemWidth(item);
243                     if (loopWidth > clipWidth) {
244                         if (!(item.hidden || item.xtbHidden)) {
245                             this.hideItem(item);
246                         }
247                     } else if (item.xtbHidden) {
248                         this.unhideItem(item);
249                     }
250                 }
251             }
252         }
253
254         //test for number of hidden items again here because they may have changed above
255         hasHiddens = hiddenItems.length != 0;
256
257         if (hasHiddens) {
258             this.initMore();
259
260             if (!this.lastOverflow) {
261                 this.container.fireEvent('overflowchange', this.container, true);
262                 this.lastOverflow = true;
263             }
264         } else if (this.more) {
265             this.clearMenu();
266             this.more.destroy();
267             delete this.more;
268
269             if (this.lastOverflow) {
270                 this.container.fireEvent('overflowchange', this.container, false);
271                 this.lastOverflow = false;
272             }
273         }
274     },
275
276     /**
277      * @private
278      * Returns a menu config for a given component. This config is used to create a menu item
279      * to be added to the expander menu
280      * @param {Ext.Component} component The component to create the config for
281      * @param {Boolean} hideOnClick Passed through to the menu item
282      */
283     createMenuConfig : function(component, hideOnClick){
284         var config = Ext.apply({}, component.initialConfig),
285             group  = component.toggleGroup;
286
287         Ext.copyTo(config, component, [
288             'iconCls', 'icon', 'itemId', 'disabled', 'handler', 'scope', 'menu'
289         ]);
290
291         Ext.apply(config, {
292             text       : component.overflowText || component.text,
293             hideOnClick: hideOnClick
294         });
295
296         if (group || component.enableToggle) {
297             Ext.apply(config, {
298                 group  : group,
299                 checked: component.pressed,
300                 listeners: {
301                     checkchange: function(item, checked){
302                         component.toggle(checked);
303                     }
304                 }
305             });
306         }
307
308         delete config.ownerCt;
309         delete config.xtype;
310         delete config.id;
311
312         return config;
313     },
314
315     /**
316      * @private
317      * Adds the given Toolbar item to the given menu. Buttons inside a buttongroup are added individually.
318      * @param {Ext.menu.Menu} menu The menu to add to
319      * @param {Ext.Component} component The component to add
320      */
321     addComponentToMenu : function(menu, component) {
322         if (component instanceof Ext.Toolbar.Separator) {
323             menu.add('-');
324
325         } else if (Ext.isFunction(component.isXType)) {
326             if (component.isXType('splitbutton')) {
327                 menu.add(this.createMenuConfig(component, true));
328
329             } else if (component.isXType('button')) {
330                 menu.add(this.createMenuConfig(component, !component.menu));
331
332             } else if (component.isXType('buttongroup')) {
333                 component.items.each(function(item){
334                      this.addComponentToMenu(menu, item);
335                 }, this);
336             }
337         }
338     },
339
340     /**
341      * @private
342      * Deletes the sub-menu of each item in the expander menu. Submenus are created for items such as
343      * splitbuttons and buttongroups, where the Toolbar item cannot be represented by a single menu item
344      */
345     clearMenu : function(){
346         var menu = this.moreMenu;
347         if (menu && menu.items) {
348             menu.items.each(function(item){
349                 delete item.menu;
350             });
351         }
352     },
353
354     /**
355      * @private
356      * Called before the expand menu is shown, this rebuilds the menu since it was last shown because
357      * it is possible that the items hidden due to space limitations on the Toolbar have changed since.
358      * @param {Ext.menu.Menu} m The menu
359      */
360     beforeMoreShow : function(menu) {
361         var items = this.container.items.items,
362             len   = items.length,
363             item,
364             prev;
365
366         var needsSep = function(group, item){
367             return group.isXType('buttongroup') && !(item instanceof Ext.Toolbar.Separator);
368         };
369
370         this.clearMenu();
371         menu.removeAll();
372         for (var i = 0; i < len; i++) {
373             item = items[i];
374             if (item.xtbHidden) {
375                 if (prev && (needsSep(item, prev) || needsSep(prev, item))) {
376                     menu.add('-');
377                 }
378                 this.addComponentToMenu(menu, item);
379                 prev = item;
380             }
381         }
382
383         // put something so the menu isn't empty if no compatible items found
384         if (menu.items.length < 1) {
385             menu.add(this.noItemsMenuText);
386         }
387     },
388
389     /**
390      * @private
391      * Creates the expand trigger and menu, adding them to the <tr> at the extreme right of the
392      * Toolbar table
393      */
394     initMore : function(){
395         if (!this.more) {
396             /**
397              * @private
398              * @property moreMenu
399              * @type Ext.menu.Menu
400              * The expand menu - holds items for every Toolbar item that cannot be shown
401              * because the Toolbar is currently not wide enough.
402              */
403             this.moreMenu = new Ext.menu.Menu({
404                 ownerCt : this.container,
405                 listeners: {
406                     beforeshow: this.beforeMoreShow,
407                     scope: this
408                 }
409             });
410
411             /**
412              * @private
413              * @property more
414              * @type Ext.Button
415              * The expand button which triggers the overflow menu to be shown
416              */
417             this.more = new Ext.Button({
418                 iconCls: 'x-toolbar-more-icon',
419                 cls    : 'x-toolbar-more',
420                 menu   : this.moreMenu,
421                 ownerCt: this.container
422             });
423
424             var td = this.insertCell(this.more, this.extrasTr, 100);
425             this.more.render(td);
426         }
427     },
428
429     destroy : function(){
430         Ext.destroy(this.more, this.moreMenu);
431         delete this.leftTr;
432         delete this.rightTr;
433         delete this.extrasTr;
434         Ext.layout.ToolbarLayout.superclass.destroy.call(this);
435     }
436 });
437
438 Ext.Container.LAYOUTS.toolbar = Ext.layout.ToolbarLayout;