Roo/menu/Menu.js
[roojs1] / Roo / menu / Menu.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 /**
13  * @class Roo.menu.Menu
14  * @extends Roo.util.Observable
15  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
16  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
17  * @constructor
18  * Creates a new Menu
19  * @param {Object} config Configuration options
20  */
21 Roo.menu.Menu = function(config){
22     Roo.apply(this, config);
23     this.id = this.id || Roo.id();
24     this.addEvents({
25         /**
26          * @event beforeshow
27          * Fires before this menu is displayed
28          * @param {Roo.menu.Menu} this
29          */
30         beforeshow : true,
31         /**
32          * @event beforehide
33          * Fires before this menu is hidden
34          * @param {Roo.menu.Menu} this
35          */
36         beforehide : true,
37         /**
38          * @event show
39          * Fires after this menu is displayed
40          * @param {Roo.menu.Menu} this
41          */
42         show : true,
43         /**
44          * @event hide
45          * Fires after this menu is hidden
46          * @param {Roo.menu.Menu} this
47          */
48         hide : true,
49         /**
50          * @event click
51          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
52          * @param {Roo.menu.Menu} this
53          * @param {Roo.menu.Item} menuItem The menu item that was clicked
54          * @param {Roo.EventObject} e
55          */
56         click : true,
57         /**
58          * @event mouseover
59          * Fires when the mouse is hovering over this menu
60          * @param {Roo.menu.Menu} this
61          * @param {Roo.EventObject} e
62          * @param {Roo.menu.Item} menuItem The menu item that was clicked
63          */
64         mouseover : true,
65         /**
66          * @event mouseout
67          * Fires when the mouse exits this menu
68          * @param {Roo.menu.Menu} this
69          * @param {Roo.EventObject} e
70          * @param {Roo.menu.Item} menuItem The menu item that was clicked
71          */
72         mouseout : true,
73         /**
74          * @event itemclick
75          * Fires when a menu item contained in this menu is clicked
76          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
77          * @param {Roo.EventObject} e
78          */
79         itemclick: true
80     });
81     if (this.registerMenu) {
82         Roo.menu.MenuMgr.register(this);
83     }
84     
85     var mis = this.items;
86     this.items = new Roo.util.MixedCollection();
87     if(mis){
88         this.add.apply(this, mis);
89     }
90 };
91
92 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
93     /**
94      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
95      */
96     minWidth : 120,
97     /**
98      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
99      * for bottom-right shadow (defaults to "sides")
100      */
101     shadow : "sides",
102     /**
103      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
104      * this menu (defaults to "tl-tr?")
105      */
106     subMenuAlign : "tl-tr?",
107     /**
108      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
109      * relative to its element of origin (defaults to "tl-bl?")
110      */
111     defaultAlign : "tl-bl?",
112     /**
113      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
114      */
115     allowOtherMenus : false,
116     /**
117      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
118      */
119     registerMenu : true,
120
121     hidden:true,
122
123     // private
124     render : function(){
125         if(this.el){
126             return;
127         }
128         var el = this.el = new Roo.Layer({
129             cls: "x-menu",
130             shadow:this.shadow,
131             constrain: false,
132             parentEl: this.parentEl || document.body,
133             zindex:15000
134         });
135
136         this.keyNav = new Roo.menu.MenuNav(this);
137
138         if(this.plain){
139             el.addClass("x-menu-plain");
140         }
141         if(this.cls){
142             el.addClass(this.cls);
143         }
144         // generic focus element
145         this.focusEl = el.createChild({
146             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
147         });
148         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
149         ul.on("click", this.onClick, this);
150         ul.on("mouseover", this.onMouseOver, this);
151         ul.on("mouseout", this.onMouseOut, this);
152         this.items.each(function(item){
153             if (item.hidden) {
154                 return;
155             }
156             
157             var li = document.createElement("li");
158             li.className = "x-menu-list-item";
159             ul.dom.appendChild(li);
160             item.render(li, this);
161         }, this);
162         this.ul = ul;
163         this.autoWidth();
164     },
165
166     // private
167     autoWidth : function(){
168         var el = this.el, ul = this.ul;
169         if(!el){
170             return;
171         }
172         var w = this.width;
173         if(w){
174             el.setWidth(w);
175         }else if(Roo.isIE){
176             el.setWidth(this.minWidth);
177             var t = el.dom.offsetWidth; // force recalc
178             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
179         }
180     },
181
182     // private
183     delayAutoWidth : function(){
184         if(this.rendered){
185             if(!this.awTask){
186                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
187             }
188             this.awTask.delay(20);
189         }
190     },
191
192     // private
193     findTargetItem : function(e){
194         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
195         if(t && t.menuItemId){
196             return this.items.get(t.menuItemId);
197         }
198     },
199
200     // private
201     onClick : function(e){
202         var t;
203         if(t = this.findTargetItem(e)){
204             t.onClick(e);
205             this.fireEvent("click", this, t, e);
206         }
207     },
208
209     // private
210     setActiveItem : function(item, autoExpand){
211         if(item != this.activeItem){
212             if(this.activeItem){
213                 this.activeItem.deactivate();
214             }
215             this.activeItem = item;
216             item.activate(autoExpand);
217         }else if(autoExpand){
218             item.expandMenu();
219         }
220     },
221
222     // private
223     tryActivate : function(start, step){
224         var items = this.items;
225         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
226             var item = items.get(i);
227             if(!item.disabled && item.canActivate){
228                 this.setActiveItem(item, false);
229                 return item;
230             }
231         }
232         return false;
233     },
234
235     // private
236     onMouseOver : function(e){
237         var t;
238         if(t = this.findTargetItem(e)){
239             if(t.canActivate && !t.disabled){
240                 this.setActiveItem(t, true);
241             }
242         }
243         this.fireEvent("mouseover", this, e, t);
244     },
245
246     // private
247     onMouseOut : function(e){
248         var t;
249         if(t = this.findTargetItem(e)){
250             if(t == this.activeItem && t.shouldDeactivate(e)){
251                 this.activeItem.deactivate();
252                 delete this.activeItem;
253             }
254         }
255         this.fireEvent("mouseout", this, e, t);
256     },
257
258     /**
259      * Read-only.  Returns true if the menu is currently displayed, else false.
260      * @type Boolean
261      */
262     isVisible : function(){
263         return this.el && !this.hidden;
264     },
265
266     /**
267      * Displays this menu relative to another element
268      * @param {String/HTMLElement/Roo.Element} element The element to align to
269      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
270      * the element (defaults to this.defaultAlign)
271      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
272      */
273     show : function(el, pos, parentMenu){
274         this.parentMenu = parentMenu;
275         if(!this.el){
276             this.render();
277         }
278         this.fireEvent("beforeshow", this);
279         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
280     },
281
282     /**
283      * Displays this menu at a specific xy position
284      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
285      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
286      */
287     showAt : function(xy, parentMenu, /* private: */_e){
288         this.parentMenu = parentMenu;
289         if(!this.el){
290             this.render();
291         }
292         if(_e !== false){
293             this.fireEvent("beforeshow", this);
294             xy = this.el.adjustForConstraints(xy);
295         }
296         this.el.setXY(xy);
297         this.el.show();
298         this.hidden = false;
299         this.focus();
300         this.fireEvent("show", this);
301     },
302
303     focus : function(){
304         if(!this.hidden){
305             this.doFocus.defer(50, this);
306         }
307     },
308
309     doFocus : function(){
310         if(!this.hidden){
311             this.focusEl.focus();
312         }
313     },
314
315     /**
316      * Hides this menu and optionally all parent menus
317      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
318      */
319     hide : function(deep){
320         if(this.el && this.isVisible()){
321             this.fireEvent("beforehide", this);
322             if(this.activeItem){
323                 this.activeItem.deactivate();
324                 this.activeItem = null;
325             }
326             this.el.hide();
327             this.hidden = true;
328             this.fireEvent("hide", this);
329         }
330         if(deep === true && this.parentMenu){
331             this.parentMenu.hide(true);
332         }
333     },
334
335     /**
336      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
337      * Any of the following are valid:
338      * <ul>
339      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
340      * <li>An HTMLElement object which will be converted to a menu item</li>
341      * <li>A menu item config object that will be created as a new menu item</li>
342      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
343      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
344      * </ul>
345      * Usage:
346      * <pre><code>
347 // Create the menu
348 var menu = new Roo.menu.Menu();
349
350 // Create a menu item to add by reference
351 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
352
353 // Add a bunch of items at once using different methods.
354 // Only the last item added will be returned.
355 var item = menu.add(
356     menuItem,                // add existing item by ref
357     'Dynamic Item',          // new TextItem
358     '-',                     // new separator
359     { text: 'Config Item' }  // new item by config
360 );
361 </code></pre>
362      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
363      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
364      */
365     add : function(){
366         var a = arguments, l = a.length, item;
367         for(var i = 0; i < l; i++){
368             var el = a[i];
369             if ((typeof(el) == "object") && el.xtype && el.xns) {
370                 el = Roo.factory(el, Roo.menu);
371             }
372             
373             if(el.render){ // some kind of Item
374                 item = this.addItem(el);
375             }else if(typeof el == "string"){ // string
376                 if(el == "separator" || el == "-"){
377                     item = this.addSeparator();
378                 }else{
379                     item = this.addText(el);
380                 }
381             }else if(el.tagName || el.el){ // element
382                 item = this.addElement(el);
383             }else if(typeof el == "object"){ // must be menu item config?
384                 item = this.addMenuItem(el);
385             }
386         }
387         return item;
388     },
389
390     /**
391      * Returns this menu's underlying {@link Roo.Element} object
392      * @return {Roo.Element} The element
393      */
394     getEl : function(){
395         if(!this.el){
396             this.render();
397         }
398         return this.el;
399     },
400
401     /**
402      * Adds a separator bar to the menu
403      * @return {Roo.menu.Item} The menu item that was added
404      */
405     addSeparator : function(){
406         return this.addItem(new Roo.menu.Separator());
407     },
408
409     /**
410      * Adds an {@link Roo.Element} object to the menu
411      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
412      * @return {Roo.menu.Item} The menu item that was added
413      */
414     addElement : function(el){
415         return this.addItem(new Roo.menu.BaseItem(el));
416     },
417
418     /**
419      * Adds an existing object based on {@link Roo.menu.Item} to the menu
420      * @param {Roo.menu.Item} item The menu item to add
421      * @return {Roo.menu.Item} The menu item that was added
422      */
423     addItem : function(item){
424         this.items.add(item);
425         if(this.ul){
426             var li = document.createElement("li");
427             li.className = "x-menu-list-item";
428             this.ul.dom.appendChild(li);
429             item.render(li, this);
430             this.delayAutoWidth();
431         }
432         return item;
433     },
434
435     /**
436      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
437      * @param {Object} config A MenuItem config object
438      * @return {Roo.menu.Item} The menu item that was added
439      */
440     addMenuItem : function(config){
441         if(!(config instanceof Roo.menu.Item)){
442             if(typeof config.checked == "boolean"){ // must be check menu item config?
443                 config = new Roo.menu.CheckItem(config);
444             }else{
445                 config = new Roo.menu.Item(config);
446             }
447         }
448         return this.addItem(config);
449     },
450
451     /**
452      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
453      * @param {String} text The text to display in the menu item
454      * @return {Roo.menu.Item} The menu item that was added
455      */
456     addText : function(text){
457         return this.addItem(new Roo.menu.TextItem({ text : text }));
458     },
459
460     /**
461      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
462      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
463      * @param {Roo.menu.Item} item The menu item to add
464      * @return {Roo.menu.Item} The menu item that was added
465      */
466     insert : function(index, item){
467         this.items.insert(index, item);
468         if(this.ul){
469             var li = document.createElement("li");
470             li.className = "x-menu-list-item";
471             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
472             item.render(li, this);
473             this.delayAutoWidth();
474         }
475         return item;
476     },
477
478     /**
479      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
480      * @param {Roo.menu.Item} item The menu item to remove
481      */
482     remove : function(item){
483         this.items.removeKey(item.id);
484         item.destroy();
485     },
486
487     /**
488      * Removes and destroys all items in the menu
489      */
490     removeAll : function(){
491         var f;
492         while(f = this.items.first()){
493             this.remove(f);
494         }
495     }
496 });
497
498 // MenuNav is a private utility class used internally by the Menu
499 Roo.menu.MenuNav = function(menu){
500     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
501     this.scope = this.menu = menu;
502 };
503
504 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
505     doRelay : function(e, h){
506         var k = e.getKey();
507         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
508             this.menu.tryActivate(0, 1);
509             return false;
510         }
511         return h.call(this.scope || this, e, this.menu);
512     },
513
514     up : function(e, m){
515         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
516             m.tryActivate(m.items.length-1, -1);
517         }
518     },
519
520     down : function(e, m){
521         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
522             m.tryActivate(0, 1);
523         }
524     },
525
526     right : function(e, m){
527         if(m.activeItem){
528             m.activeItem.expandMenu(true);
529         }
530     },
531
532     left : function(e, m){
533         m.hide();
534         if(m.parentMenu && m.parentMenu.activeItem){
535             m.parentMenu.activeItem.activate();
536         }
537     },
538
539     enter : function(e, m){
540         if(m.activeItem){
541             e.stopPropagation();
542             m.activeItem.onClick(e);
543             m.fireEvent("click", this, m.activeItem);
544             return true;
545         }
546     }
547 });