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