Debian Codegraph @

closure-library/closure/goog/ui/menubutton.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview A menu button control.
17 *
18 * @author [email protected] (Attila Bodis)
19 * @see ../demos/menubutton.html
20 */
21
22 goog.provide('goog.ui.MenuButton');
23
24 goog.require('goog.Timer');
25 goog.require('goog.a11y.aria');
26 goog.require('goog.a11y.aria.State');
27 goog.require('goog.asserts');
28 goog.require('goog.dom');
29 goog.require('goog.events.EventType');
30 goog.require('goog.events.KeyCodes');
31 goog.require('goog.events.KeyHandler');
32 goog.require('goog.math.Box');
33 goog.require('goog.math.Rect');
34 goog.require('goog.positioning');
35 goog.require('goog.positioning.Corner');
36 goog.require('goog.positioning.MenuAnchoredPosition');
37 goog.require('goog.positioning.Overflow');
38 goog.require('goog.style');
39 goog.require('goog.ui.Button');
40 goog.require('goog.ui.Component');
41 goog.require('goog.ui.IdGenerator');
42 goog.require('goog.ui.Menu');
43 goog.require('goog.ui.MenuButtonRenderer');
44 goog.require('goog.ui.MenuItem');
45 goog.require('goog.ui.MenuRenderer');
46 goog.require('goog.ui.registry');
47 goog.require('goog.userAgent');
48 goog.require('goog.userAgent.product');
49
50
51
52 /**
53 * A menu button control. Extends {@link goog.ui.Button} by composing a button
54 * with a dropdown arrow and a popup menu.
55 *
56 * @param {goog.ui.ControlContent=} opt_content Text caption or existing DOM
57 * structure to display as the button's caption (if any).
58 * @param {goog.ui.Menu=} opt_menu Menu to render under the button when clicked.
59 * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
60 * decorate the menu button; defaults to {@link goog.ui.MenuButtonRenderer}.
61 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
62 * document interaction.
63 * @param {!goog.ui.MenuRenderer=} opt_menuRenderer Renderer used to render or
64 * decorate the menu; defaults to {@link goog.ui.MenuRenderer}.
65 * @constructor
66 * @extends {goog.ui.Button}
67 */
68 goog.ui.MenuButton = function(
69 opt_content, opt_menu, opt_renderer, opt_domHelper, opt_menuRenderer) {
70 goog.ui.Button.call(
71 this, opt_content,
72 opt_renderer || goog.ui.MenuButtonRenderer.getInstance(), opt_domHelper);
73
74 // Menu buttons support the OPENED state.
75 this.setSupportedState(goog.ui.Component.State.OPENED, true);
76
77 /**
78 * The menu position on this button.
79 * @type {!goog.positioning.AnchoredPosition}
80 * @private
81 */
82 this.menuPosition_ = new goog.positioning.MenuAnchoredPosition(
83 null, goog.positioning.Corner.BOTTOM_START);
84
85 if (opt_menu) {
86 this.setMenu(opt_menu);
87 }
88 this.menuMargin_ = null;
89 this.timer_ = new goog.Timer(500); // 0.5 sec
90
91 // Phones running iOS prior to version 4.2.
92 if ((goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
93 // Check the webkit version against the version for iOS 4.2.1.
94 !goog.userAgent.isVersionOrHigher('533.17.9')) {
95 // @bug 4322060 This is required so that the menu works correctly on
96 // iOS prior to version 4.2. Otherwise, the blur action closes the menu
97 // before the menu button click can be processed.
98 this.setFocusablePopupMenu(true);
99 }
100
101 /** @private {!goog.ui.MenuRenderer} */
102 this.menuRenderer_ = opt_menuRenderer || goog.ui.MenuRenderer.getInstance();
103 };
104 goog.inherits(goog.ui.MenuButton, goog.ui.Button);
105 goog.tagUnsealableClass(goog.ui.MenuButton);
106
107
108 /**
109 * The menu.
110 * @type {goog.ui.Menu|undefined}
111 * @private
112 */
113 goog.ui.MenuButton.prototype.menu_;
114
115
116 /**
117 * The position element. If set, use positionElement_ to position the
118 * popup menu instead of the default which is to use the menu button element.
119 * @type {Element|undefined}
120 * @private
121 */
122 goog.ui.MenuButton.prototype.positionElement_;
123
124
125 /**
126 * The margin to apply to the menu's position when it is shown. If null, no
127 * margin will be applied.
128 * @type {goog.math.Box}
129 * @private
130 */
131 goog.ui.MenuButton.prototype.menuMargin_;
132
133
134 /**
135 * Whether the attached popup menu is focusable or not (defaults to false).
136 * Popup menus attached to menu buttons usually don't need to be focusable,
137 * i.e. the button retains keyboard focus, and forwards key events to the
138 * menu for processing. However, menus like {@link goog.ui.FilteredMenu}
139 * need to be focusable.
140 * @type {boolean}
141 * @private
142 */
143 goog.ui.MenuButton.prototype.isFocusablePopupMenu_ = false;
144
145
146 /**
147 * A Timer to correct menu position.
148 * @type {goog.Timer}
149 * @private
150 */
151 goog.ui.MenuButton.prototype.timer_;
152
153
154 /**
155 * The bounding rectangle of the button element.
156 * @type {goog.math.Rect}
157 * @private
158 */
159 goog.ui.MenuButton.prototype.buttonRect_;
160
161
162 /**
163 * The viewport rectangle.
164 * @type {goog.math.Box}
165 * @private
166 */
167 goog.ui.MenuButton.prototype.viewportBox_;
168
169
170 /**
171 * The original size.
172 * @type {goog.math.Size|undefined}
173 * @private
174 */
175 goog.ui.MenuButton.prototype.originalSize_;
176
177
178 /**
179 * Do we render the drop down menu as a sibling to the label, or at the end
180 * of the current dom?
181 * @type {boolean}
182 * @private
183 */
184 goog.ui.MenuButton.prototype.renderMenuAsSibling_ = false;
185
186
187 /**
188 * Whether to select the first item in the menu when it is opened using
189 * enter or space. By default, the first item is selected only when
190 * opened by a key up or down event. When this is on, the first item will
191 * be selected due to any of the four events.
192 * @private
193 */
194 goog.ui.MenuButton.prototype.selectFirstOnEnterOrSpace_ = false;
195
196
197 /**
198 * Sets up event handlers specific to menu buttons.
199 * @override
200 */
201 goog.ui.MenuButton.prototype.enterDocument = function() {
202 goog.ui.MenuButton.superClass_.enterDocument.call(this);
203 this.attachKeyDownEventListener_(true);
204 if (this.menu_) {
205 this.attachMenuEventListeners_(this.menu_, true);
206 }
207 goog.a11y.aria.setState(
208 this.getElementStrict(), goog.a11y.aria.State.HASPOPUP, !!this.menu_);
209 };
210
211
212 /**
213 * Removes event handlers specific to menu buttons, and ensures that the
214 * attached menu also exits the document.
215 * @override
216 */
217 goog.ui.MenuButton.prototype.exitDocument = function() {
218 goog.ui.MenuButton.superClass_.exitDocument.call(this);
219 this.attachKeyDownEventListener_(false);
220 if (this.menu_) {
221 this.setOpen(false);
222 this.menu_.exitDocument();
223 this.attachMenuEventListeners_(this.menu_, false);
224
225 var menuElement = this.menu_.getElement();
226 if (menuElement) {
227 goog.dom.removeNode(menuElement);
228 }
229 }
230 };
231
232
233 /** @override */
234 goog.ui.MenuButton.prototype.disposeInternal = function() {
235 goog.ui.MenuButton.superClass_.disposeInternal.call(this);
236 if (this.menu_) {
237 this.menu_.dispose();
238 delete this.menu_;
239 }
240 delete this.positionElement_;
241 this.timer_.dispose();
242 };
243
244
245 /**
246 * Handles mousedown events. Invokes the superclass implementation to dispatch
247 * an ACTIVATE event and activate the button. Also toggles the visibility of
248 * the attached menu.
249 * @param {goog.events.Event} e Mouse event to handle.
250 * @override
251 * @protected
252 */
253 goog.ui.MenuButton.prototype.handleMouseDown = function(e) {
254 goog.ui.MenuButton.superClass_.handleMouseDown.call(this, e);
255 if (this.isActive()) {
256 // The component was allowed to activate; toggle menu visibility.
257 this.setOpen(!this.isOpen(), e);
258 if (this.menu_) {
259 this.menu_.setMouseButtonPressed(this.isOpen());
260 }
261 }
262 };
263
264
265 /**
266 * Handles mouseup events. Invokes the superclass implementation to dispatch
267 * an ACTION event and deactivate the button.
268 * @param {goog.events.Event} e Mouse event to handle.
269 * @override
270 * @protected
271 */
272 goog.ui.MenuButton.prototype.handleMouseUp = function(e) {
273 goog.ui.MenuButton.superClass_.handleMouseUp.call(this, e);
274 if (this.menu_ && !this.isActive()) {
275 this.menu_.setMouseButtonPressed(false);
276 }
277 };
278
279
280 /**
281 * Performs the appropriate action when the menu button is activated by the
282 * user. Overrides the superclass implementation by not dispatching an {@code
283 * ACTION} event, because menu buttons exist only to reveal menus, not to
284 * perform actions themselves. Calls {@link #setActive} to deactivate the
285 * button.
286 * @param {goog.events.Event} e Mouse or key event that triggered the action.
287 * @return {boolean} Whether the action was allowed to proceed.
288 * @override
289 * @protected
290 */
291 goog.ui.MenuButton.prototype.performActionInternal = function(e) {
292 this.setActive(false);
293 return true;
294 };
295
296
297 /**
298 * Handles mousedown events over the document. If the mousedown happens over
299 * an element unrelated to the component, hides the menu.
300 * TODO(attila): Reconcile this with goog.ui.Popup (and handle frames/windows).
301 * @param {goog.events.BrowserEvent} e Mouse event to handle.
302 * @protected
303 */
304 goog.ui.MenuButton.prototype.handleDocumentMouseDown = function(e) {
305 if (this.menu_ && this.menu_.isVisible() &&
306 !this.containsElement(/** @type {Element} */ (e.target))) {
307 // User clicked somewhere else in the document while the menu was visible;
308 // dismiss menu.
309 this.setOpen(false);
310 }
311 };
312
313
314 /**
315 * Returns true if the given element is to be considered part of the component,
316 * even if it isn't a DOM descendant of the component's root element.
317 * @param {Element} element Element to test (if any).
318 * @return {boolean} Whether the element is considered part of the component.
319 * @protected
320 */
321 goog.ui.MenuButton.prototype.containsElement = function(element) {
322 return element && goog.dom.contains(this.getElement(), element) ||
323 this.menu_ && this.menu_.containsElement(element) || false;
324 };
325
326
327 /** @override */
328 goog.ui.MenuButton.prototype.handleKeyEventInternal = function(e) {
329 // Handle SPACE on keyup and all other keys on keypress.
330 if (e.keyCode == goog.events.KeyCodes.SPACE) {
331 // Prevent page scrolling in Chrome.
332 e.preventDefault();
333 if (e.type != goog.events.EventType.KEYUP) {
334 // Ignore events because KeyCodes.SPACE is handled further down.
335 return true;
336 }
337 } else if (e.type != goog.events.KeyHandler.EventType.KEY) {
338 return false;
339 }
340
341 if (this.menu_ && this.menu_.isVisible()) {
342 // Menu is open.
343 var isEnterOrSpace = e.keyCode == goog.events.KeyCodes.ENTER ||
344 e.keyCode == goog.events.KeyCodes.SPACE;
345 var handledByMenu = this.menu_.handleKeyEvent(e);
346 if (e.keyCode == goog.events.KeyCodes.ESC || isEnterOrSpace) {
347 // Dismiss the menu.
348 this.setOpen(false);
349 return true;
350 }
351 return handledByMenu;
352 }
353
354 if (e.keyCode == goog.events.KeyCodes.DOWN ||
355 e.keyCode == goog.events.KeyCodes.UP ||
356 e.keyCode == goog.events.KeyCodes.SPACE ||
357 e.keyCode == goog.events.KeyCodes.ENTER) {
358 // Menu is closed, and the user hit the down/up/space/enter key; open menu.
359 this.setOpen(true, e);
360 return true;
361 }
362
363 // Key event wasn't handled by the component.
364 return false;
365 };
366
367
368 /**
369 * Handles {@code ACTION} events dispatched by an activated menu item.
370 * @param {goog.events.Event} e Action event to handle.
371 * @protected
372 */
373 goog.ui.MenuButton.prototype.handleMenuAction = function(e) {
374 // Close the menu on click.
375 this.setOpen(false);
376 };
377
378
379 /**
380 * Handles {@code BLUR} events dispatched by the popup menu by closing it.
381 * Only registered if the menu is focusable.
382 * @param {goog.events.Event} e Blur event dispatched by a focusable menu.
383 */
384 goog.ui.MenuButton.prototype.handleMenuBlur = function(e) {
385 // Close the menu when it reports that it lost focus, unless the button is
386 // pressed (active).
387 if (!this.isActive()) {
388 this.setOpen(false);
389 }
390 };
391
392
393 /**
394 * Handles blur events dispatched by the button's key event target when it
395 * loses keyboard focus by closing the popup menu (unless it is focusable).
396 * Only registered if the button is focusable.
397 * @param {goog.events.Event} e Blur event dispatched by the menu button.
398 * @override
399 * @protected
400 */
401 goog.ui.MenuButton.prototype.handleBlur = function(e) {
402 if (!this.isFocusablePopupMenu()) {
403 this.setOpen(false);
404 }
405 goog.ui.MenuButton.superClass_.handleBlur.call(this, e);
406 };
407
408
409 /**
410 * Returns the menu attached to the button. If no menu is attached, creates a
411 * new empty menu.
412 * @return {goog.ui.Menu} Popup menu attached to the menu button.
413 */
414 goog.ui.MenuButton.prototype.getMenu = function() {
415 if (!this.menu_) {
416 this.setMenu(new goog.ui.Menu(this.getDomHelper(), this.menuRenderer_));
417 }
418 return this.menu_ || null;
419 };
420
421
422 /**
423 * Replaces the menu attached to the button with the argument, and returns the
424 * previous menu (if any).
425 * @param {goog.ui.Menu?} menu New menu to be attached to the menu button (null
426 * to remove the menu).
427 * @return {goog.ui.Menu|undefined} Previous menu (undefined if none).
428 */
429 goog.ui.MenuButton.prototype.setMenu = function(menu) {
430 var oldMenu = this.menu_;
431
432 // Do nothing unless the new menu is different from the current one.
433 if (menu != oldMenu) {
434 if (oldMenu) {
435 this.setOpen(false);
436 if (this.isInDocument()) {
437 this.attachMenuEventListeners_(oldMenu, false);
438 }
439 delete this.menu_;
440 }
441 if (this.isInDocument()) {
442 goog.a11y.aria.setState(
443 this.getElementStrict(), goog.a11y.aria.State.HASPOPUP, !!menu);
444 }
445 if (menu) {
446 this.menu_ = menu;
447 menu.setParent(this);
448 menu.setVisible(false);
449 menu.setAllowAutoFocus(this.isFocusablePopupMenu());
450 if (this.isInDocument()) {
451 this.attachMenuEventListeners_(menu, true);
452 }
453 }
454 }
455
456 return oldMenu;
457 };
458
459
460 /**
461 * Specify which positioning algorithm to use.
462 *
463 * This method is preferred over the fine-grained positioning methods like
464 * setPositionElement, setAlignMenuToStart, and setScrollOnOverflow. Calling
465 * this method will override settings by those methods.
466 *
467 * @param {goog.positioning.AnchoredPosition} position The position of the
468 * Menu the button. If the position has a null anchor, we will use the
469 * menubutton element as the anchor.
470 */
471 goog.ui.MenuButton.prototype.setMenuPosition = function(position) {
472 if (position) {
473 this.menuPosition_ = position;
474 this.positionElement_ = position.element;
475 }
476 };
477
478
479 /**
480 * Sets an element for anchoring the menu.
481 * @param {Element} positionElement New element to use for
482 * positioning the dropdown menu. Null to use the default behavior
483 * of positioning to this menu button.
484 */
485 goog.ui.MenuButton.prototype.setPositionElement = function(positionElement) {
486 this.positionElement_ = positionElement;
487 this.positionMenu();
488 };
489
490
491 /**
492 * Sets a margin that will be applied to the menu's position when it is shown.
493 * If null, no margin will be applied.
494 * @param {goog.math.Box} margin Margin to apply.
495 */
496 goog.ui.MenuButton.prototype.setMenuMargin = function(margin) {
497 this.menuMargin_ = margin;
498 };
499
500
501 /**
502 * Sets whether to select the first item in the menu when it is opened using
503 * enter or space. By default, the first item is selected only when
504 * opened by a key up or down event. When this is on, the first item will
505 * be selected due to any of the four events.
506 * @param {boolean} select
507 */
508 goog.ui.MenuButton.prototype.setSelectFirstOnEnterOrSpace = function(select) {
509 this.selectFirstOnEnterOrSpace_ = select;
510 };
511
512
513 /**
514 * Adds a new menu item at the end of the menu.
515 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator|goog.ui.Control} item Menu
516 * item to add to the menu.
517 */
518 goog.ui.MenuButton.prototype.addItem = function(item) {
519 this.getMenu().addChild(item, true);
520 };
521
522
523 /**
524 * Adds a new menu item at the specific index in the menu.
525 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
526 * menu.
527 * @param {number} index Index at which to insert the menu item.
528 */
529 goog.ui.MenuButton.prototype.addItemAt = function(item, index) {
530 this.getMenu().addChildAt(item, index, true);
531 };
532
533
534 /**
535 * Removes the item from the menu and disposes of it.
536 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The menu item to remove.
537 */
538 goog.ui.MenuButton.prototype.removeItem = function(item) {
539 var child = this.getMenu().removeChild(item, true);
540 if (child) {
541 child.dispose();
542 }
543 };
544
545
546 /**
547 * Removes the menu item at a given index in the menu and disposes of it.
548 * @param {number} index Index of item.
549 */
550 goog.ui.MenuButton.prototype.removeItemAt = function(index) {
551 var child = this.getMenu().removeChildAt(index, true);
552 if (child) {
553 child.dispose();
554 }
555 };
556
557
558 /**
559 * Returns the menu item at a given index.
560 * @param {number} index Index of menu item.
561 * @return {goog.ui.MenuItem?} Menu item (null if not found).
562 */
563 goog.ui.MenuButton.prototype.getItemAt = function(index) {
564 return this.menu_ ?
565 /** @type {goog.ui.MenuItem} */ (this.menu_.getChildAt(index)) :
566 null;
567 };
568
569
570 /**
571 * Returns the number of items in the menu (including separators).
572 * @return {number} The number of items in the menu.
573 */
574 goog.ui.MenuButton.prototype.getItemCount = function() {
575 return this.menu_ ? this.menu_.getChildCount() : 0;
576 };
577
578
579 /**
580 * Shows/hides the menu button based on the value of the argument. Also hides
581 * the popup menu if the button is being hidden.
582 * @param {boolean} visible Whether to show or hide the button.
583 * @param {boolean=} opt_force If true, doesn't check whether the component
584 * already has the requested visibility, and doesn't dispatch any events.
585 * @return {boolean} Whether the visibility was changed.
586 * @override
587 */
588 goog.ui.MenuButton.prototype.setVisible = function(visible, opt_force) {
589 var visibilityChanged =
590 goog.ui.MenuButton.superClass_.setVisible.call(this, visible, opt_force);
591 if (visibilityChanged && !this.isVisible()) {
592 this.setOpen(false);
593 }
594 return visibilityChanged;
595 };
596
597
598 /**
599 * Enables/disables the menu button based on the value of the argument, and
600 * updates its CSS styling. Also hides the popup menu if the button is being
601 * disabled.
602 * @param {boolean} enable Whether to enable or disable the button.
603 * @override
604 */
605 goog.ui.MenuButton.prototype.setEnabled = function(enable) {
606 goog.ui.MenuButton.superClass_.setEnabled.call(this, enable);
607 if (!this.isEnabled()) {
608 this.setOpen(false);
609 }
610 };
611
612
613 // TODO(nicksantos): AlignMenuToStart and ScrollOnOverflow and PositionElement
614 // should all be deprecated, in favor of people setting their own
615 // AnchoredPosition with the parameters they need. Right now, we try
616 // to be backwards-compatible as possible, but this is incomplete because
617 // the APIs are non-orthogonal.
618
619
620 /**
621 * @return {boolean} Whether the menu is aligned to the start of the button
622 * (left if the render direction is left-to-right, right if the render
623 * direction is right-to-left).
624 */
625 goog.ui.MenuButton.prototype.isAlignMenuToStart = function() {
626 var corner = this.menuPosition_.corner;
627 return corner == goog.positioning.Corner.BOTTOM_START ||
628 corner == goog.positioning.Corner.TOP_START;
629 };
630
631
632 /**
633 * Sets whether the menu is aligned to the start or the end of the button.
634 * @param {boolean} alignToStart Whether the menu is to be aligned to the start
635 * of the button (left if the render direction is left-to-right, right if
636 * the render direction is right-to-left).
637 */
638 goog.ui.MenuButton.prototype.setAlignMenuToStart = function(alignToStart) {
639 this.menuPosition_.corner = alignToStart ?
640 goog.positioning.Corner.BOTTOM_START :
641 goog.positioning.Corner.BOTTOM_END;
642 };
643
644
645 /**
646 * Sets whether the menu should scroll when it's too big to fix vertically on
647 * the screen. The css of the menu element should have overflow set to auto.
648 * Note: Adding or removing items while the menu is open will not work correctly
649 * if scrollOnOverflow is on.
650 * @param {boolean} scrollOnOverflow Whether the menu should scroll when too big
651 * to fit on the screen. If false, adjust logic will be used to try and
652 * reposition the menu to fit.
653 */
654 goog.ui.MenuButton.prototype.setScrollOnOverflow = function(scrollOnOverflow) {
655 if (this.menuPosition_.setLastResortOverflow) {
656 var overflowX = goog.positioning.Overflow.ADJUST_X;
657 var overflowY = scrollOnOverflow ? goog.positioning.Overflow.RESIZE_HEIGHT :
658 goog.positioning.Overflow.ADJUST_Y;
659 this.menuPosition_.setLastResortOverflow(overflowX | overflowY);
660 }
661 };
662
663
664 /**
665 * @return {boolean} Wether the menu will scroll when it's to big to fit
666 * vertically on the screen.
667 */
668 goog.ui.MenuButton.prototype.isScrollOnOverflow = function() {
669 return this.menuPosition_.getLastResortOverflow &&
670 !!(this.menuPosition_.getLastResortOverflow() &
671 goog.positioning.Overflow.RESIZE_HEIGHT);
672 };
673
674
675 /**
676 * @return {boolean} Whether the attached menu is focusable.
677 */
678 goog.ui.MenuButton.prototype.isFocusablePopupMenu = function() {
679 return this.isFocusablePopupMenu_;
680 };
681
682
683 /**
684 * Sets whether the attached popup menu is focusable. If the popup menu is
685 * focusable, it may steal keyboard focus from the menu button, so the button
686 * will not hide the menu on blur.
687 * @param {boolean} focusable Whether the attached menu is focusable.
688 */
689 goog.ui.MenuButton.prototype.setFocusablePopupMenu = function(focusable) {
690 // TODO(attila): The menu itself should advertise whether it is focusable.
691 this.isFocusablePopupMenu_ = focusable;
692 };
693
694
695 /**
696 * Sets whether to render the menu as a sibling element of the button.
697 * Normally, the menu is a child of document.body. This option is useful if
698 * you need the menu to inherit styles from a common parent element, or if you
699 * otherwise need it to share a parent element for desired event handling. One
700 * example of the latter is if the parent is in a goog.ui.Popup, to ensure that
701 * clicks on the menu are considered being within the popup.
702 * @param {boolean} renderMenuAsSibling Whether we render the menu at the end
703 * of the dom or as a sibling to the button/label that renders the drop
704 * down.
705 */
706 goog.ui.MenuButton.prototype.setRenderMenuAsSibling = function(
707 renderMenuAsSibling) {
708 this.renderMenuAsSibling_ = renderMenuAsSibling;
709 };
710
711
712 /**
713 * Reveals the menu and hooks up menu-specific event handling.
714 * @deprecated Use {@link #setOpen} instead.
715 */
716 goog.ui.MenuButton.prototype.showMenu = function() {
717 this.setOpen(true);
718 };
719
720
721 /**
722 * Hides the menu and cleans up menu-specific event handling.
723 * @deprecated Use {@link #setOpen} instead.
724 */
725 goog.ui.MenuButton.prototype.hideMenu = function() {
726 this.setOpen(false);
727 };
728
729
730 /**
731 * Opens or closes the attached popup menu.
732 * @param {boolean} open Whether to open or close the menu.
733 * @param {goog.events.Event=} opt_e Event that caused the menu to be opened.
734 * @override
735 */
736 goog.ui.MenuButton.prototype.setOpen = function(open, opt_e) {
737 goog.ui.MenuButton.superClass_.setOpen.call(this, open);
738 if (this.menu_ && this.hasState(goog.ui.Component.State.OPENED) == open) {
739 if (open) {
740 if (!this.menu_.isInDocument()) {
741 if (this.renderMenuAsSibling_) {
742 // When we render the menu in the same parent as this button, we
743 // prefer to add it immediately after the button. This way, the screen
744 // readers will go to the menu on the very next element after the
745 // button is read.
746 var nextElementSibling =
747 goog.dom.getNextElementSibling(this.getElement());
748 if (nextElementSibling) {
749 this.menu_.renderBefore(nextElementSibling);
750 } else {
751 this.menu_.render(
752 /** @type {Element} */ (this.getElement().parentNode));
753 }
754 } else {
755 this.menu_.render();
756 }
757 }
758 this.viewportBox_ =
759 goog.style.getVisibleRectForElement(this.getElement());
760 this.buttonRect_ = goog.style.getBounds(this.getElement());
761 this.positionMenu();
762
763 // As per aria spec, highlight the first element in the menu when
764 // keyboarding up or down. Thus, the first menu item will be announced
765 // for screen reader users. If selectFirstOnEnterOrSpace is set, do this
766 // for enter or space as well.
767 var isEnterOrSpace =
768 !!opt_e && (opt_e.keyCode == goog.events.KeyCodes.ENTER ||
769 opt_e.keyCode == goog.events.KeyCodes.SPACE);
770 var isUpOrDown = !!opt_e && (opt_e.keyCode == goog.events.KeyCodes.DOWN ||
771 opt_e.keyCode == goog.events.KeyCodes.UP);
772 var focus =
773 isUpOrDown || (isEnterOrSpace && this.selectFirstOnEnterOrSpace_);
774 if (focus) {
775 this.menu_.highlightFirst();
776 } else {
777 this.menu_.setHighlightedIndex(-1);
778 }
779 } else {
780 this.setActive(false);
781 this.menu_.setMouseButtonPressed(false);
782
783 var element = this.getElement();
784 // Clear any remaining a11y state.
785 if (element) {
786 goog.a11y.aria.setState(
787 element, goog.a11y.aria.State.ACTIVEDESCENDANT, '');
788 goog.a11y.aria.setState(element, goog.a11y.aria.State.OWNS, '');
789 }
790
791 // Clear any sizes that might have been stored.
792 if (goog.isDefAndNotNull(this.originalSize_)) {
793 this.originalSize_ = undefined;
794 var elem = this.menu_.getElement();
795 if (elem) {
796 goog.style.setSize(elem, '', '');
797 }
798 }
799 }
800 this.menu_.setVisible(open, false, opt_e);
801 // In Pivot Tables the menu button somehow gets disposed of during the
802 // setVisible call, causing attachPopupListeners_ to fail.
803 // TODO(user): Debug what happens.
804 if (!this.isDisposed()) {
805 this.attachPopupListeners_(open);
806 }
807 }
808 if (this.menu_ && this.menu_.getElement()) {
809 // Remove the aria-hidden state on the menu element so that it won't be
810 // hidden to screen readers if it's inside a dialog (see b/17610491).
811 goog.a11y.aria.removeState(
812 this.menu_.getElementStrict(), goog.a11y.aria.State.HIDDEN);
813 }
814 };
815
816
817 /**
818 * Resets the MenuButton's size. This is useful for cases where items are added
819 * or removed from the menu and scrollOnOverflow is on. In those cases the
820 * menu will not behave correctly and resize itself unless this is called
821 * (usually followed by positionMenu()).
822 */
823 goog.ui.MenuButton.prototype.invalidateMenuSize = function() {
824 this.originalSize_ = undefined;
825 };
826
827
828 /**
829 * Positions the menu under the button. May be called directly in cases when
830 * the menu size is known to change.
831 */
832 goog.ui.MenuButton.prototype.positionMenu = function() {
833 if (!this.menu_.isInDocument()) {
834 return;
835 }
836
837 var positionElement = this.positionElement_ || this.getElement();
838 var position = this.menuPosition_;
839 this.menuPosition_.element = positionElement;
840
841 var elem = this.menu_.getElement();
842 if (!this.menu_.isVisible()) {
843 elem.style.visibility = 'hidden';
844 goog.style.setElementShown(elem, true);
845 }
846
847 if (!this.originalSize_ && this.isScrollOnOverflow()) {
848 this.originalSize_ = goog.style.getSize(elem);
849 }
850 var popupCorner = goog.positioning.flipCornerVertical(position.corner);
851 position.reposition(elem, popupCorner, this.menuMargin_, this.originalSize_);
852
853 if (!this.menu_.isVisible()) {
854 goog.style.setElementShown(elem, false);
855 elem.style.visibility = 'visible';
856 }
857 };
858
859
860 /**
861 * Periodically repositions the menu while it is visible.
862 *
863 * @param {goog.events.Event} e An event object.
864 * @private
865 */
866 goog.ui.MenuButton.prototype.onTick_ = function(e) {
867 // Call positionMenu() only if the button position or size was
868 // changed, or if the window's viewport was changed.
869 var currentButtonRect = goog.style.getBounds(this.getElement());
870 var currentViewport = goog.style.getVisibleRectForElement(this.getElement());
871 if (!goog.math.Rect.equals(this.buttonRect_, currentButtonRect) ||
872 !goog.math.Box.equals(this.viewportBox_, currentViewport)) {
873 this.buttonRect_ = currentButtonRect;
874 this.viewportBox_ = currentViewport;
875 this.positionMenu();
876 }
877 };
878
879
880 /**
881 * Attaches or detaches menu event listeners to/from the given menu.
882 * Called each time a menu is attached to or detached from the button.
883 * @param {goog.ui.Menu} menu Menu on which to listen for events.
884 * @param {boolean} attach Whether to attach or detach event listeners.
885 * @private
886 */
887 goog.ui.MenuButton.prototype.attachMenuEventListeners_ = function(
888 menu, attach) {
889 var handler = this.getHandler();
890 var method = attach ? handler.listen : handler.unlisten;
891
892 // Handle events dispatched by menu items.
893 method.call(
894 handler, menu, goog.ui.Component.EventType.ACTION, this.handleMenuAction);
895 method.call(
896 handler, menu, goog.ui.Component.EventType.CLOSE, this.handleCloseItem);
897 method.call(
898 handler, menu, goog.ui.Component.EventType.HIGHLIGHT,
899 this.handleHighlightItem);
900 method.call(
901 handler, menu, goog.ui.Component.EventType.UNHIGHLIGHT,
902 this.handleUnHighlightItem);
903 };
904
905
906 /**
907 * Attaches or detaches a keydown event listener to/from the given element.
908 * Called each time the button enters or exits the document.
909 * @param {boolean} attach Whether to attach or detach the event listener.
910 * @private
911 */
912 goog.ui.MenuButton.prototype.attachKeyDownEventListener_ = function(attach) {
913 var handler = this.getHandler();
914 var method = attach ? handler.listen : handler.unlisten;
915
916 // Handle keydown events dispatched by the button.
917 method.call(
918 handler, this.getElement(), goog.events.EventType.KEYDOWN,
919 this.handleKeyDownEvent_);
920 };
921
922
923 /**
924 * Handles {@code HIGHLIGHT} events dispatched by the attached menu.
925 * @param {goog.events.Event} e Highlight event to handle.
926 */
927 goog.ui.MenuButton.prototype.handleHighlightItem = function(e) {
928 var targetEl = e.target.getElement();
929 if (targetEl) {
930 this.setAriaActiveDescendant_(targetEl);
931 }
932 };
933
934
935 /**
936 * Handles {@code KEYDOWN} events dispatched by the button element. When the
937 * button is focusable and the menu is present and visible, prevents the event
938 * from propagating since the desired behavior is only to close the menu.
939 * @param {goog.events.Event} e KeyDown event to handle.
940 * @private
941 */
942 goog.ui.MenuButton.prototype.handleKeyDownEvent_ = function(e) {
943 if (this.isSupportedState(goog.ui.Component.State.FOCUSED) &&
944 this.getKeyEventTarget() && this.menu_ && this.menu_.isVisible()) {
945 e.stopPropagation();
946 }
947 };
948
949
950 /**
951 * Handles UNHIGHLIGHT events dispatched by the associated menu.
952 * @param {goog.events.Event} e Unhighlight event to handle.
953 */
954 goog.ui.MenuButton.prototype.handleUnHighlightItem = function(e) {
955 if (!this.menu_.getHighlighted()) {
956 var element = this.getElement();
957 goog.asserts.assert(element, 'The menu button DOM element cannot be null.');
958 goog.a11y.aria.setState(element, goog.a11y.aria.State.ACTIVEDESCENDANT, '');
959 goog.a11y.aria.setState(element, goog.a11y.aria.State.OWNS, '');
960 }
961 };
962
963
964 /**
965 * Handles {@code CLOSE} events dispatched by the associated menu.
966 * @param {goog.events.Event} e Close event to handle.
967 */
968 goog.ui.MenuButton.prototype.handleCloseItem = function(e) {
969 // When a submenu is closed by pressing left arrow, no highlight event is
970 // dispatched because the newly focused item was already highlighted, so this
971 // scenario is handled by listening for the submenu close event instead.
972 if (this.isOpen() && e.target instanceof goog.ui.MenuItem) {
973 var menuItem = /** @type {!goog.ui.MenuItem} */ (e.target);
974 var menuItemEl = menuItem.getElement();
975 if (menuItem.isVisible() && menuItem.isHighlighted() &&
976 menuItemEl != null) {
977 this.setAriaActiveDescendant_(menuItemEl);
978 }
979 }
980 };
981
982
983 /**
984 * Updates the aria-activedescendant attribute to the given target element.
985 * @param {!Element} targetEl The target element.
986 * @private
987 */
988 goog.ui.MenuButton.prototype.setAriaActiveDescendant_ = function(targetEl) {
989 var element = this.getElement();
990 goog.asserts.assert(element, 'The menu button DOM element cannot be null.');
991
992 // If target element has an activedescendant, then set this control's
993 // activedescendant to that, otherwise set it to the target element. This is
994 // a workaround for some screen readers which do not handle
995 // aria-activedescendant redirection properly.
996 var targetActiveDescendant = goog.a11y.aria.getActiveDescendant(targetEl);
997 var activeDescendant = targetActiveDescendant || targetEl;
998
999 if (!activeDescendant.id) {
1000 // Create an id if there isn't one already.
1001 var idGenerator = goog.ui.IdGenerator.getInstance();
1002 activeDescendant.id = idGenerator.getNextUniqueId();
1003 }
1004
1005 goog.a11y.aria.setActiveDescendant(element, activeDescendant);
1006 goog.a11y.aria.setState(
1007 element, goog.a11y.aria.State.OWNS, activeDescendant.id);
1008 };
1009
1010
1011 /**
1012 * Attaches or detaches event listeners depending on whether the popup menu
1013 * is being shown or hidden. Starts listening for document mousedown events
1014 * and for menu blur events when the menu is shown, and stops listening for
1015 * these events when it is hidden. Called from {@link #setOpen}.
1016 * @param {boolean} attach Whether to attach or detach event listeners.
1017 * @private
1018 */
1019 goog.ui.MenuButton.prototype.attachPopupListeners_ = function(attach) {
1020 var handler = this.getHandler();
1021 var method = attach ? handler.listen : handler.unlisten;
1022
1023 // Listen for document mousedown events in the capture phase, because
1024 // the target may stop propagation of the event in the bubble phase.
1025 method.call(
1026 handler, this.getDomHelper().getDocument(),
1027 goog.events.EventType.MOUSEDOWN, this.handleDocumentMouseDown, true);
1028
1029 // Only listen for blur events dispatched by the menu if it is focusable.
1030 if (this.isFocusablePopupMenu()) {
1031 method.call(
1032 handler, /** @type {!goog.events.EventTarget} */ (this.menu_),
1033 goog.ui.Component.EventType.BLUR, this.handleMenuBlur);
1034 }
1035
1036 method.call(handler, this.timer_, goog.Timer.TICK, this.onTick_);
1037 if (attach) {
1038 this.timer_.start();
1039 } else {
1040 this.timer_.stop();
1041 }
1042 };
1043
1044
1045 // Register a decorator factory function for goog.ui.MenuButtons.
1046 goog.ui.registry.setDecoratorByClassName(
1047 goog.ui.MenuButtonRenderer.CSS_CLASS, function() {
1048 // MenuButton defaults to using MenuButtonRenderer.
1049 return new goog.ui.MenuButton(null);
1050 });