Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / menu / Menu.js
1 /**
2  * @class Ext.menu.Menu
3  * @extends Ext.panel.Panel
4  *
5  * A menu object. This is the container to which you may add {@link Ext.menu.Item menu items}.
6  *
7  * Menus may contain either {@link Ext.menu.Item menu items}, or general {@link Ext.Component Components}.
8  * Menus may also contain {@link Ext.panel.AbstractPanel#dockedItems docked items} because it extends {@link Ext.panel.Panel}.
9  *
10  * To make a contained general {@link Ext.Component Component} line up with other {@link Ext.menu.Item menu items},
11  * specify `{@link Ext.menu.Item#iconCls iconCls}: 'no-icon'` _or_ `{@link Ext.menu.Item#indent indent}: true`.
12  * This reserves a space for an icon, and indents the Component in line with the other menu items.
13  * See {@link Ext.form.field.ComboBox}.{@link Ext.form.field.ComboBox#getListParent getListParent} for an example.
14
15  * By default, Menus are absolutely positioned, floating Components. By configuring a Menu with `{@link #floating}:false`,
16  * a Menu may be used as a child of a {@link Ext.container.Container Container}.
17  * {@img Ext.menu.Item/Ext.menu.Item.png Ext.menu.Item component}
18 __Example Usage__
19         Ext.create('Ext.menu.Menu', {
20                 width: 100,
21                 height: 100,
22                 margin: '0 0 10 0',
23                 floating: false,  // usually you want this set to True (default)
24                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
25                 items: [{                        
26                         text: 'regular item 1'        
27                 },{
28                     text: 'regular item 2'
29                 },{
30                         text: 'regular item 3'  
31                 }]
32         }); 
33         
34         Ext.create('Ext.menu.Menu', {
35                 width: 100,
36                 height: 100,
37                 plain: true,
38                 floating: false,  // usually you want this set to True (default)
39                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
40                 items: [{                        
41                         text: 'plain item 1'    
42                 },{
43                     text: 'plain item 2'
44                 },{
45                         text: 'plain item 3'
46                 }]
47         }); 
48  * @xtype menu
49  * @markdown
50  * @constructor
51  * @param {Object} config The config object
52  */
53 Ext.define('Ext.menu.Menu', {
54     extend: 'Ext.panel.Panel',
55     alias: 'widget.menu',
56     requires: [
57         'Ext.layout.container.Fit',
58         'Ext.layout.container.VBox',
59         'Ext.menu.CheckItem',
60         'Ext.menu.Item',
61         'Ext.menu.KeyNav',
62         'Ext.menu.Manager',
63         'Ext.menu.Separator'
64     ],
65
66     /**
67      * @cfg {Boolean} allowOtherMenus
68      * True to allow multiple menus to be displayed at the same time. Defaults to `false`.
69      * @markdown
70      */
71     allowOtherMenus: false,
72
73     /**
74      * @cfg {String} ariaRole @hide
75      */
76     ariaRole: 'menu',
77
78     /**
79      * @cfg {Boolean} autoRender @hide
80      * floating is true, so autoRender always happens
81      */
82
83     /**
84      * @cfg {String} defaultAlign
85      * The default {@link Ext.core.Element#getAlignToXY Ext.core.Element#getAlignToXY} anchor position value for this menu
86      * relative to its element of origin. Defaults to `'tl-bl?'`.
87      * @markdown
88      */
89     defaultAlign: 'tl-bl?',
90
91     /**
92      * @cfg {Boolean} floating
93      * A Menu configured as `floating: true` (the default) will be rendered as an absolutely positioned,
94      * {@link Ext.Component#floating floating} {@link Ext.Component Component}. If configured as `floating: false`, the Menu may be
95      * used as a child item of another {@link Ext.container.Container Container}.
96      * @markdown
97      */
98     floating: true,
99
100     /**
101      * @cfg {Boolean} @hide
102      * Menu performs its own size changing constraining, so ensure Component's constraining is not applied
103      */
104     constrain: false,
105
106     /**
107      * @cfg {Boolean} hidden
108      * True to initially render the Menu as hidden, requiring to be shown manually.
109      * Defaults to `true` when `floating: true`, and defaults to `false` when `floating: false`.
110      * @markdown
111      */
112     hidden: true,
113
114     /**
115      * @cfg {Boolean} ignoreParentClicks
116      * True to ignore clicks on any item in this menu that is a parent item (displays a submenu)
117      * so that the submenu is not dismissed when clicking the parent item. Defaults to `false`.
118      * @markdown
119      */
120     ignoreParentClicks: false,
121
122     isMenu: true,
123
124     /**
125      * @cfg {String/Object} layout @hide
126      */
127
128     /**
129      * @cfg {Boolean} showSeparator True to show the icon separator. (defaults to true).
130      */
131     showSeparator : true,
132
133     /**
134      * @cfg {Number} minWidth
135      * The minimum width of the Menu. Defaults to `120`.
136      * @markdown
137      */
138     minWidth: 120,
139
140     /**
141      * @cfg {Boolean} plain
142      * True to remove the incised line down the left side of the menu and to not
143      * indent general Component items. Defaults to `false`.
144      * @markdown
145      */
146
147     initComponent: function() {
148         var me = this,
149             prefix = Ext.baseCSSPrefix,
150             cls = [prefix + 'menu'],
151             bodyCls = me.bodyCls ? [me.bodyCls] : [];
152
153         me.addEvents(
154             /**
155              * @event click
156              * Fires when this menu is clicked
157              * @param {Ext.menu.Menu} menu The menu which has been clicked
158              * @param {Ext.Component} item The menu item that was clicked. `undefined` if not applicable.
159              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}.
160              * @markdown
161              */
162             'click',
163
164             /**
165              * @event mouseenter
166              * Fires when the mouse enters this menu
167              * @param {Ext.menu.Menu} menu The menu
168              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
169              * @markdown
170              */
171             'mouseenter',
172
173             /**
174              * @event mouseleave
175              * Fires when the mouse leaves this menu
176              * @param {Ext.menu.Menu} menu The menu
177              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
178              * @markdown
179              */
180             'mouseleave',
181
182             /**
183              * @event mouseover
184              * Fires when the mouse is hovering over this menu
185              * @param {Ext.menu.Menu} menu The menu
186              * @param {Ext.Component} item The menu item that the mouse is over. `undefined` if not applicable.
187              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
188              */
189             'mouseover'
190         );
191
192         Ext.menu.Manager.register(me);
193
194         // Menu classes
195         if (me.plain) {
196             cls.push(prefix + 'menu-plain');
197         }
198         me.cls = cls.join(' ');
199
200         // Menu body classes
201         bodyCls.unshift(prefix + 'menu-body');
202         me.bodyCls = bodyCls.join(' ');
203
204         // Internal vbox layout, with scrolling overflow
205         // Placed in initComponent (rather than prototype) in order to support dynamic layout/scroller
206         // options if we wish to allow for such configurations on the Menu.
207         // e.g., scrolling speed, vbox align stretch, etc.
208         me.layout = {
209             type: 'vbox',
210             align: 'stretchmax',
211             autoSize: true,
212             clearInnerCtOnLayout: true,
213             overflowHandler: 'Scroller'
214         };
215
216         // hidden defaults to false if floating is configured as false
217         if (me.floating === false && me.initialConfig.hidden !== true) {
218             me.hidden = false;
219         }
220
221         me.callParent(arguments);
222
223         me.on('beforeshow', function() {
224             var hasItems = !!me.items.length;
225             // FIXME: When a menu has its show cancelled because of no items, it
226             // gets a visibility: hidden applied to it (instead of the default display: none)
227             // Not sure why, but we remove this style when we want to show again.
228             if (hasItems && me.rendered) {
229                 me.el.setStyle('visibility', null);
230             }
231             return hasItems;
232         });
233     },
234
235     afterRender: function(ct) {
236         var me = this,
237             prefix = Ext.baseCSSPrefix,
238             space = ' ';
239
240         me.callParent(arguments);
241
242         // TODO: Move this to a subTemplate When we support them in the future
243         if (me.showSeparator) {
244             me.iconSepEl = me.layout.getRenderTarget().insertFirst({
245                 cls: prefix + 'menu-icon-separator',
246                 html: space
247             });
248         }
249
250         me.focusEl = me.el.createChild({
251             cls: prefix + 'menu-focus',
252             tabIndex: '-1',
253             html: space
254         });
255
256         me.mon(me.el, {
257             click: me.onClick,
258             mouseover: me.onMouseOver,
259             scope: me
260         });
261         me.mouseMonitor = me.el.monitorMouseLeave(100, me.onMouseLeave, me);
262
263         if (me.showSeparator && ((!Ext.isStrict && Ext.isIE) || Ext.isIE6)) {
264             me.iconSepEl.setHeight(me.el.getHeight());
265         }
266
267         me.keyNav = Ext.create('Ext.menu.KeyNav', me);
268     },
269
270     afterLayout: function() {
271         var me = this;
272         me.callParent(arguments);
273
274         // For IE6 & IE quirks, we have to resize the el and body since position: absolute
275         // floating elements inherit their parent's width, making them the width of
276         // document.body instead of the width of their contents.
277         // This includes left/right dock items.
278         if ((!Ext.iStrict && Ext.isIE) || Ext.isIE6) {
279             var innerCt = me.layout.getRenderTarget(),
280                 innerCtWidth = 0,
281                 dis = me.dockedItems,
282                 l = dis.length,
283                 i = 0,
284                 di, clone, newWidth;
285
286             innerCtWidth = innerCt.getWidth();
287
288             newWidth = innerCtWidth + me.body.getBorderWidth('lr') + me.body.getPadding('lr');
289
290             // First set the body to the new width
291             me.body.setWidth(newWidth);
292
293             // Now we calculate additional width (docked items) and set the el's width
294             for (; i < l, di = dis.getAt(i); i++) {
295                 if (di.dock == 'left' || di.dock == 'right') {
296                     newWidth += di.getWidth();
297                 }
298             }
299             me.el.setWidth(newWidth);
300         }
301     },
302
303     /**
304      * Returns whether a menu item can be activated or not.
305      * @return {Boolean}
306      */
307     canActivateItem: function(item) {
308         return item && !item.isDisabled() && item.isVisible() && (item.canActivate || item.getXTypes().indexOf('menuitem') < 0);
309     },
310
311     /**
312      * Deactivates the current active item on the menu, if one exists.
313      */
314     deactivateActiveItem: function() {
315         var me = this;
316
317         if (me.activeItem) {
318             me.activeItem.deactivate();
319             if (!me.activeItem.activated) {
320                 delete me.activeItem;
321             }
322         }
323         if (me.focusedItem) {
324             me.focusedItem.blur();
325             if (!me.focusedItem.$focused) {
326                 delete me.focusedItem;
327             }
328         }
329     },
330
331     // inherit docs
332     getFocusEl: function() {
333         return this.focusEl;
334     },
335
336     // inherit docs
337     hide: function() {
338         this.deactivateActiveItem();
339         this.callParent(arguments);
340     },
341
342     // private
343     getItemFromEvent: function(e) {
344         return this.getChildByElement(e.getTarget());
345     },
346
347     lookupComponent: function(cmp) {
348         var me = this;
349
350         if (Ext.isString(cmp)) {
351             cmp = me.lookupItemFromString(cmp);
352         } else if (Ext.isObject(cmp)) {
353             cmp = me.lookupItemFromObject(cmp);
354         }
355
356         // Apply our minWidth to all of our child components so it's accounted
357         // for in our VBox layout
358         cmp.minWidth = cmp.minWidth || me.minWidth;
359
360         return cmp;
361     },
362
363     // private
364     lookupItemFromObject: function(cmp) {
365         var me = this,
366             prefix = Ext.baseCSSPrefix,
367             cls,
368             intercept;
369
370         if (!cmp.isComponent) {
371             if (!cmp.xtype) {
372                 cmp = Ext.create('Ext.menu.' + (Ext.isBoolean(cmp.checked) ? 'Check': '') + 'Item', cmp);
373             } else {
374                 cmp = Ext.ComponentManager.create(cmp, cmp.xtype);
375             }
376         }
377
378         if (cmp.isMenuItem) {
379             cmp.parentMenu = me;
380         }
381
382         if (!cmp.isMenuItem && !cmp.dock) {
383             cls = [prefix + 'menu-item', prefix + 'menu-item-cmp'];
384             intercept = Ext.Function.createInterceptor;
385
386             // Wrap focus/blur to control component focus
387             cmp.focus = intercept(cmp.focus, function() {
388                 this.$focused = true;
389             }, cmp);
390             cmp.blur = intercept(cmp.blur, function() {
391                 this.$focused = false;
392             }, cmp);
393
394             if (!me.plain && (cmp.indent === true || cmp.iconCls === 'no-icon')) {
395                 cls.push(prefix + 'menu-item-indent');
396             }
397
398             if (cmp.rendered) {
399                 cmp.el.addCls(cls);
400             } else {
401                 cmp.cls = (cmp.cls ? cmp.cls : '') + ' ' + cls.join(' ');
402             }
403             cmp.isMenuItem = true;
404         }
405         return cmp;
406     },
407
408     // private
409     lookupItemFromString: function(cmp) {
410         return (cmp == 'separator' || cmp == '-') ?
411             Ext.createWidget('menuseparator')
412             : Ext.createWidget('menuitem', {
413                 canActivate: false,
414                 hideOnClick: false,
415                 plain: true,
416                 text: cmp
417             });
418     },
419
420     onClick: function(e) {
421         var me = this,
422             item;
423
424         if (me.disabled) {
425             e.stopEvent();
426             return;
427         }
428
429         if ((e.getTarget() == me.focusEl.dom) || e.within(me.layout.getRenderTarget())) {
430             item = me.getItemFromEvent(e) || me.activeItem;
431
432             if (item) {
433                 if (item.getXTypes().indexOf('menuitem') >= 0) {
434                     if (!item.menu || !me.ignoreParentClicks) {
435                         item.onClick(e);
436                     } else {
437                         e.stopEvent();
438                     }
439                 }
440             }
441             me.fireEvent('click', me, item, e);
442         }
443     },
444
445     onDestroy: function() {
446         var me = this;
447
448         Ext.menu.Manager.unregister(me);
449         if (me.rendered) {
450             me.el.un(me.mouseMonitor);
451             me.keyNav.destroy();
452             delete me.keyNav;
453         }
454         me.callParent(arguments);
455     },
456
457     onMouseLeave: function(e) {
458         var me = this;
459
460         me.deactivateActiveItem();
461
462         if (me.disabled) {
463             return;
464         }
465
466         me.fireEvent('mouseleave', me, e);
467     },
468
469     onMouseOver: function(e) {
470         var me = this,
471             fromEl = e.getRelatedTarget(),
472             mouseEnter = !me.el.contains(fromEl),
473             item = me.getItemFromEvent(e);
474
475         if (mouseEnter && me.parentMenu) {
476             me.parentMenu.setActiveItem(me.parentItem);
477             me.parentMenu.mouseMonitor.mouseenter();
478         }
479
480         if (me.disabled) {
481             return;
482         }
483
484         if (item) {
485             me.setActiveItem(item);
486             if (item.activated && item.expandMenu) {
487                 item.expandMenu();
488             }
489         }
490         if (mouseEnter) {
491             me.fireEvent('mouseenter', me, e);
492         }
493         me.fireEvent('mouseover', me, item, e);
494     },
495
496     setActiveItem: function(item) {
497         var me = this;
498
499         if (item && (item != me.activeItem && item != me.focusedItem)) {
500             me.deactivateActiveItem();
501             if (me.canActivateItem(item)) {
502                 if (item.activate) {
503                     item.activate();
504                     if (item.activated) {
505                         me.activeItem = item;
506                         me.focusedItem = item;
507                         me.focus();
508                     }
509                 } else {
510                     item.focus();
511                     me.focusedItem = item;
512                 }
513             }
514             item.el.scrollIntoView(me.layout.getRenderTarget());
515         }
516     },
517
518     /**
519      * Shows the floating menu by the specified {@link Ext.Component Component} or {@link Ext.core.Element Element}.
520      * @param {Mixed component} The {@link Ext.Component} or {@link Ext.core.Element} to show the menu by.
521      * @param {String} position (optional) Alignment position as used by {@link Ext.core.Element#getAlignToXY Ext.core.Element.getAlignToXY}. Defaults to `{@link #defaultAlign}`.
522      * @param {Array} offsets (optional) Alignment offsets as used by {@link Ext.core.Element#getAlignToXY Ext.core.Element.getAlignToXY}. Defaults to `undefined`.
523      * @return {Menu} This Menu.
524      * @markdown
525      */
526     showBy: function(cmp, pos, off) {
527         var me = this,
528             xy,
529             region;
530
531         if (me.floating && cmp) {
532             me.layout.autoSize = true;
533             me.show();
534
535             // Component or Element
536             cmp = cmp.el || cmp;
537
538             // Convert absolute to floatParent-relative coordinates if necessary.
539             xy = me.el.getAlignToXY(cmp, pos || me.defaultAlign, off);
540             if (me.floatParent) {
541                 region = me.floatParent.getTargetEl().getViewRegion();
542                 xy[0] -= region.x;
543                 xy[1] -= region.y;
544             }
545             me.showAt(xy);
546         }
547         return me;
548     },
549     
550     // inherit docs
551     showAt: function(){
552         this.callParent(arguments);
553         if (this.floating) {
554             this.doConstrain();
555         }    
556     },
557
558     doConstrain : function() {
559         var me = this,
560             y = me.el.getY(),
561             max, full,
562             vector,
563             returnY = y, normalY, parentEl, scrollTop, viewHeight;
564
565         delete me.height;
566         me.setSize();
567         full = me.getHeight();
568         if (me.floating) {
569             parentEl = Ext.fly(me.el.dom.parentNode);
570             scrollTop = parentEl.getScroll().top;
571             viewHeight = parentEl.getViewSize().height;
572             //Normalize y by the scroll position for the parent element.  Need to move it into the coordinate space
573             //of the view.
574             normalY = y - scrollTop;
575             max = me.maxHeight ? me.maxHeight : viewHeight - normalY;
576             if (full > viewHeight) {
577                 max = viewHeight;
578                 //Set returnY equal to (0,0) in view space by reducing y by the value of normalY
579                 returnY = y - normalY;
580             } else if (max < full) {
581                 returnY = y - (full - max);
582                 max = full;
583             }
584         }else{
585             max = me.getHeight();
586         }
587         // Always respect maxHeight
588         if (me.maxHeight){
589             max = Math.min(me.maxHeight, max);
590         }
591         if (full > max && max > 0){
592             me.layout.autoSize = false;
593             me.setHeight(max);
594             if (me.showSeparator){
595                 me.iconSepEl.setHeight(me.layout.getRenderTarget().dom.scrollHeight);
596             }
597         }
598         vector = me.getConstrainVector();
599         if (vector) {
600             me.setPosition(me.getPosition()[0] + vector[0]);
601         }
602         me.el.setY(returnY);
603     }
604 });