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         //disabling touch- as it's causing issues ..
150         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
151         
152         ul.on("mouseover", this.onMouseOver, this);
153         ul.on("mouseout", this.onMouseOut, this);
154         this.items.each(function(item){
155             if (item.hidden) {
156                 return;
157             }
158             
159             var li = document.createElement("li");
160             li.className = "x-menu-list-item";
161             ul.dom.appendChild(li);
162             item.render(li, this);
163         }, this);
164         this.ul = ul;
165         this.autoWidth();
166     },
167
168     // private
169     autoWidth : function(){
170         var el = this.el, ul = this.ul;
171         if(!el){
172             return;
173         }
174         var w = this.width;
175         if(w){
176             el.setWidth(w);
177         }else if(Roo.isIE){
178             el.setWidth(this.minWidth);
179             var t = el.dom.offsetWidth; // force recalc
180             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
181         }
182     },
183
184     // private
185     delayAutoWidth : function(){
186         if(this.rendered){
187             if(!this.awTask){
188                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
189             }
190             this.awTask.delay(20);
191         }
192     },
193
194     // private
195     findTargetItem : function(e){
196         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
197         if(t && t.menuItemId){
198             return this.items.get(t.menuItemId);
199         }
200     },
201
202     // private
203     onClick : function(e){
204         Roo.log("menu.onClick");
205         var t = this.findTargetItem(e);
206         if(!t){
207             return;
208         }
209         Roo.log(e);
210         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
211             if(t == this.activeItem && t.shouldDeactivate(e)){
212                 this.activeItem.deactivate();
213                 delete this.activeItem;
214                 return;
215             }
216             if(t.canActivate){
217                 this.setActiveItem(t, true);
218             }
219             return;
220             
221             
222         }
223         
224         t.onClick(e);
225         this.fireEvent("click", this, t, e);
226     },
227
228     // private
229     setActiveItem : function(item, autoExpand){
230         if(item != this.activeItem){
231             if(this.activeItem){
232                 this.activeItem.deactivate();
233             }
234             this.activeItem = item;
235             item.activate(autoExpand);
236         }else if(autoExpand){
237             item.expandMenu();
238         }
239     },
240
241     // private
242     tryActivate : function(start, step){
243         var items = this.items;
244         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
245             var item = items.get(i);
246             if(!item.disabled && item.canActivate){
247                 this.setActiveItem(item, false);
248                 return item;
249             }
250         }
251         return false;
252     },
253
254     // private
255     onMouseOver : function(e){
256         var t;
257         if(t = this.findTargetItem(e)){
258             if(t.canActivate && !t.disabled){
259                 this.setActiveItem(t, true);
260             }
261         }
262         this.fireEvent("mouseover", this, e, t);
263     },
264
265     // private
266     onMouseOut : function(e){
267         var t;
268         if(t = this.findTargetItem(e)){
269             if(t == this.activeItem && t.shouldDeactivate(e)){
270                 this.activeItem.deactivate();
271                 delete this.activeItem;
272             }
273         }
274         this.fireEvent("mouseout", this, e, t);
275     },
276
277     /**
278      * Read-only.  Returns true if the menu is currently displayed, else false.
279      * @type Boolean
280      */
281     isVisible : function(){
282         return this.el && !this.hidden;
283     },
284
285     /**
286      * Displays this menu relative to another element
287      * @param {String/HTMLElement/Roo.Element} element The element to align to
288      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
289      * the element (defaults to this.defaultAlign)
290      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
291      */
292     show : function(el, pos, parentMenu){
293         this.parentMenu = parentMenu;
294         if(!this.el){
295             this.render();
296         }
297         this.fireEvent("beforeshow", this);
298         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
299     },
300
301     /**
302      * Displays this menu at a specific xy position
303      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
304      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
305      */
306     showAt : function(xy, parentMenu, /* private: */_e){
307         this.parentMenu = parentMenu;
308         if(!this.el){
309             this.render();
310         }
311         if(_e !== false){
312             this.fireEvent("beforeshow", this);
313             xy = this.el.adjustForConstraints(xy);
314         }
315         this.el.setXY(xy);
316         this.el.show();
317         this.hidden = false;
318         this.focus();
319         this.fireEvent("show", this);
320     },
321
322     focus : function(){
323         if(!this.hidden){
324             this.doFocus.defer(50, this);
325         }
326     },
327
328     doFocus : function(){
329         if(!this.hidden){
330             this.focusEl.focus();
331         }
332     },
333
334     /**
335      * Hides this menu and optionally all parent menus
336      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
337      */
338     hide : function(deep){
339         if(this.el && this.isVisible()){
340             this.fireEvent("beforehide", this);
341             if(this.activeItem){
342                 this.activeItem.deactivate();
343                 this.activeItem = null;
344             }
345             this.el.hide();
346             this.hidden = true;
347             this.fireEvent("hide", this);
348         }
349         if(deep === true && this.parentMenu){
350             this.parentMenu.hide(true);
351         }
352     },
353
354     /**
355      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
356      * Any of the following are valid:
357      * <ul>
358      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
359      * <li>An HTMLElement object which will be converted to a menu item</li>
360      * <li>A menu item config object that will be created as a new menu item</li>
361      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
362      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
363      * </ul>
364      * Usage:
365      * <pre><code>
366 // Create the menu
367 var menu = new Roo.menu.Menu();
368
369 // Create a menu item to add by reference
370 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
371
372 // Add a bunch of items at once using different methods.
373 // Only the last item added will be returned.
374 var item = menu.add(
375     menuItem,                // add existing item by ref
376     'Dynamic Item',          // new TextItem
377     '-',                     // new separator
378     { text: 'Config Item' }  // new item by config
379 );
380 </code></pre>
381      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
382      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
383      */
384     add : function(){
385         var a = arguments, l = a.length, item;
386         for(var i = 0; i < l; i++){
387             var el = a[i];
388             if ((typeof(el) == "object") && el.xtype && el.xns) {
389                 el = Roo.factory(el, Roo.menu);
390             }
391             
392             if(el.render){ // some kind of Item
393                 item = this.addItem(el);
394             }else if(typeof el == "string"){ // string
395                 if(el == "separator" || el == "-"){
396                     item = this.addSeparator();
397                 }else{
398                     item = this.addText(el);
399                 }
400             }else if(el.tagName || el.el){ // element
401                 item = this.addElement(el);
402             }else if(typeof el == "object"){ // must be menu item config?
403                 item = this.addMenuItem(el);
404             }
405         }
406         return item;
407     },
408
409     /**
410      * Returns this menu's underlying {@link Roo.Element} object
411      * @return {Roo.Element} The element
412      */
413     getEl : function(){
414         if(!this.el){
415             this.render();
416         }
417         return this.el;
418     },
419
420     /**
421      * Adds a separator bar to the menu
422      * @return {Roo.menu.Item} The menu item that was added
423      */
424     addSeparator : function(){
425         return this.addItem(new Roo.menu.Separator());
426     },
427
428     /**
429      * Adds an {@link Roo.Element} object to the menu
430      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
431      * @return {Roo.menu.Item} The menu item that was added
432      */
433     addElement : function(el){
434         return this.addItem(new Roo.menu.BaseItem(el));
435     },
436
437     /**
438      * Adds an existing object based on {@link Roo.menu.Item} to the menu
439      * @param {Roo.menu.Item} item The menu item to add
440      * @return {Roo.menu.Item} The menu item that was added
441      */
442     addItem : function(item){
443         this.items.add(item);
444         if(this.ul){
445             var li = document.createElement("li");
446             li.className = "x-menu-list-item";
447             this.ul.dom.appendChild(li);
448             item.render(li, this);
449             this.delayAutoWidth();
450         }
451         return item;
452     },
453
454     /**
455      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
456      * @param {Object} config A MenuItem config object
457      * @return {Roo.menu.Item} The menu item that was added
458      */
459     addMenuItem : function(config){
460         if(!(config instanceof Roo.menu.Item)){
461             if(typeof config.checked == "boolean"){ // must be check menu item config?
462                 config = new Roo.menu.CheckItem(config);
463             }else{
464                 config = new Roo.menu.Item(config);
465             }
466         }
467         return this.addItem(config);
468     },
469
470     /**
471      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
472      * @param {String} text The text to display in the menu item
473      * @return {Roo.menu.Item} The menu item that was added
474      */
475     addText : function(text){
476         return this.addItem(new Roo.menu.TextItem({ text : text }));
477     },
478
479     /**
480      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
481      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
482      * @param {Roo.menu.Item} item The menu item to add
483      * @return {Roo.menu.Item} The menu item that was added
484      */
485     insert : function(index, item){
486         this.items.insert(index, item);
487         if(this.ul){
488             var li = document.createElement("li");
489             li.className = "x-menu-list-item";
490             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
491             item.render(li, this);
492             this.delayAutoWidth();
493         }
494         return item;
495     },
496
497     /**
498      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
499      * @param {Roo.menu.Item} item The menu item to remove
500      */
501     remove : function(item){
502         this.items.removeKey(item.id);
503         item.destroy();
504     },
505
506     /**
507      * Removes and destroys all items in the menu
508      */
509     removeAll : function(){
510         var f;
511         while(f = this.items.first()){
512             this.remove(f);
513         }
514     }
515 });
516
517 // MenuNav is a private utility class used internally by the Menu
518 Roo.menu.MenuNav = function(menu){
519     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
520     this.scope = this.menu = menu;
521 };
522
523 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
524     doRelay : function(e, h){
525         var k = e.getKey();
526         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
527             this.menu.tryActivate(0, 1);
528             return false;
529         }
530         return h.call(this.scope || this, e, this.menu);
531     },
532
533     up : function(e, m){
534         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
535             m.tryActivate(m.items.length-1, -1);
536         }
537     },
538
539     down : function(e, m){
540         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
541             m.tryActivate(0, 1);
542         }
543     },
544
545     right : function(e, m){
546         if(m.activeItem){
547             m.activeItem.expandMenu(true);
548         }
549     },
550
551     left : function(e, m){
552         m.hide();
553         if(m.parentMenu && m.parentMenu.activeItem){
554             m.parentMenu.activeItem.activate();
555         }
556     },
557
558     enter : function(e, m){
559         if(m.activeItem){
560             e.stopPropagation();
561             m.activeItem.onClick(e);
562             m.fireEvent("click", this, m.activeItem);
563             return true;
564         }
565     }
566 });