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