Debian Codegraph @

closure-library/closure/goog/ui/menu.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 base menu class that supports key and mouse events. The menu
17 * can be bound to an existing HTML structure or can generate its own DOM.
18 *
19 * To decorate, the menu should be bound to an element containing children
20 * with the classname 'goog-menuitem'. HRs will be classed as separators.
21 *
22 * Decorate Example:
23 * <div id="menu" class="goog-menu" tabIndex="0">
24 * <div class="goog-menuitem">Google</div>
25 * <div class="goog-menuitem">Yahoo</div>
26 * <div class="goog-menuitem">MSN</div>
27 * <hr>
28 * <div class="goog-menuitem">New...</div>
29 * </div>
30 * <script>
31 *
32 * var menu = new goog.ui.Menu();
33 * menu.decorate(goog.dom.getElement('menu'));
34 *
35 * TESTED=FireFox 2.0, IE6, Opera 9, Chrome.
36 * TODO(user): Key handling is flaky in Opera and Chrome
37 * TODO(user): Rename all references of "item" to child since menu is
38 * essentially very generic and could, in theory, host a date or color picker.
39 *
40 * @see ../demos/menu.html
41 * @see ../demos/menus.html
42 */
43
44 goog.provide('goog.ui.Menu');
45 goog.provide('goog.ui.Menu.EventType');
46
47 goog.require('goog.dom.TagName');
48 goog.require('goog.math.Coordinate');
49 goog.require('goog.string');
50 goog.require('goog.style');
51 goog.require('goog.ui.Component.EventType');
52 goog.require('goog.ui.Component.State');
53 goog.require('goog.ui.Container');
54 goog.require('goog.ui.Container.Orientation');
55 goog.require('goog.ui.MenuHeader');
56 goog.require('goog.ui.MenuItem');
57 goog.require('goog.ui.MenuRenderer');
58 goog.require('goog.ui.MenuSeparator');
59
60 // The dependencies MenuHeader, MenuItem, and MenuSeparator are implicit.
61 // There are no references in the code, but we need to load these
62 // classes before goog.ui.Menu.
63
64
65
66 // TODO(robbyw): Reverse constructor argument order for consistency.
67 /**
68 * A basic menu class.
69 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
70 * @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render or
71 * decorate the container; defaults to {@link goog.ui.MenuRenderer}.
72 * @constructor
73 * @extends {goog.ui.Container}
74 */
75 goog.ui.Menu = function(opt_domHelper, opt_renderer) {
76 goog.ui.Container.call(
77 this, goog.ui.Container.Orientation.VERTICAL,
78 opt_renderer || goog.ui.MenuRenderer.getInstance(), opt_domHelper);
79
80 // Unlike Containers, Menus aren't keyboard-accessible by default. This line
81 // preserves backwards compatibility with code that depends on menus not
82 // receiving focus - e.g. {@code goog.ui.MenuButton}.
83 this.setFocusable(false);
84 };
85 goog.inherits(goog.ui.Menu, goog.ui.Container);
86 goog.tagUnsealableClass(goog.ui.Menu);
87
88
89 // TODO(robbyw): Remove this and all references to it.
90 // Please ensure that BEFORE_SHOW behavior is not disrupted as a result.
91 /**
92 * Event types dispatched by the menu.
93 * @enum {string}
94 * @deprecated Use goog.ui.Component.EventType.
95 */
96 goog.ui.Menu.EventType = {
97 /** Dispatched before the menu becomes visible */
98 BEFORE_SHOW: goog.ui.Component.EventType.BEFORE_SHOW,
99
100 /** Dispatched when the menu is shown */
101 SHOW: goog.ui.Component.EventType.SHOW,
102
103 /** Dispatched before the menu becomes hidden */
104 BEFORE_HIDE: goog.ui.Component.EventType.HIDE,
105
106 /** Dispatched when the menu is hidden */
107 HIDE: goog.ui.Component.EventType.HIDE
108 };
109
110
111 // TODO(robbyw): Remove this and all references to it.
112 /**
113 * CSS class for menus.
114 * @type {string}
115 * @deprecated Use goog.ui.MenuRenderer.CSS_CLASS.
116 */
117 goog.ui.Menu.CSS_CLASS = goog.ui.MenuRenderer.CSS_CLASS;
118
119
120 /**
121 * Coordinates of the mousedown event that caused this menu to be made visible.
122 * Used to prevent the consequent mouseup event due to a simple click from
123 * activating a menu item immediately. Considered protected; should only be used
124 * within this package or by subclasses.
125 * @type {goog.math.Coordinate|undefined}
126 */
127 goog.ui.Menu.prototype.openingCoords;
128
129
130 /**
131 * Whether the menu can move the focus to its key event target when it is
132 * shown. Default = true
133 * @type {boolean}
134 * @private
135 */
136 goog.ui.Menu.prototype.allowAutoFocus_ = true;
137
138
139 /**
140 * Whether the menu should use windows style behavior and allow disabled menu
141 * items to be highlighted (though not selectable). Defaults to false
142 * @type {boolean}
143 * @private
144 */
145 goog.ui.Menu.prototype.allowHighlightDisabled_ = false;
146
147
148 /**
149 * Returns the CSS class applied to menu elements, also used as the prefix for
150 * derived styles, if any. Subclasses should override this method as needed.
151 * Considered protected.
152 * @return {string} The CSS class applied to menu elements.
153 * @protected
154 * @deprecated Use getRenderer().getCssClass().
155 */
156 goog.ui.Menu.prototype.getCssClass = function() {
157 return this.getRenderer().getCssClass();
158 };
159
160
161 /**
162 * Returns whether the provided element is to be considered inside the menu for
163 * purposes such as dismissing the menu on an event. This is so submenus can
164 * make use of elements outside their own DOM.
165 * @param {Element} element The element to test for.
166 * @return {boolean} Whether the provided element is to be considered inside
167 * the menu.
168 */
169 goog.ui.Menu.prototype.containsElement = function(element) {
170 if (this.getRenderer().containsElement(this, element)) {
171 return true;
172 }
173
174 for (var i = 0, count = this.getChildCount(); i < count; i++) {
175 var child = this.getChildAt(i);
176 if (typeof child.containsElement == 'function' &&
177 child.containsElement(element)) {
178 return true;
179 }
180 }
181
182 return false;
183 };
184
185
186 /**
187 * Adds a new menu item at the end of the menu.
188 * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu
189 * item to add to the menu.
190 * @deprecated Use {@link #addChild} instead, with true for the second argument.
191 */
192 goog.ui.Menu.prototype.addItem = function(item) {
193 this.addChild(item, true);
194 };
195
196
197 /**
198 * Adds a new menu item at a specific index in the menu.
199 * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu
200 * item to add to the menu.
201 * @param {number} n Index at which to insert the menu item.
202 * @deprecated Use {@link #addChildAt} instead, with true for the third
203 * argument.
204 */
205 goog.ui.Menu.prototype.addItemAt = function(item, n) {
206 this.addChildAt(item, n, true);
207 };
208
209
210 /**
211 * Removes an item from the menu and disposes of it.
212 * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item The
213 * menu item to remove.
214 * @deprecated Use {@link #removeChild} instead.
215 */
216 goog.ui.Menu.prototype.removeItem = function(item) {
217 var removedChild = this.removeChild(item, true);
218 if (removedChild) {
219 removedChild.dispose();
220 }
221 };
222
223
224 /**
225 * Removes a menu item at a given index in the menu and disposes of it.
226 * @param {number} n Index of item.
227 * @deprecated Use {@link #removeChildAt} instead.
228 */
229 goog.ui.Menu.prototype.removeItemAt = function(n) {
230 var removedChild = this.removeChildAt(n, true);
231 if (removedChild) {
232 removedChild.dispose();
233 }
234 };
235
236
237 /**
238 * Returns a reference to the menu item at a given index.
239 * @param {number} n Index of menu item.
240 * @return {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator|null}
241 * Reference to the menu item.
242 * @deprecated Use {@link #getChildAt} instead.
243 */
244 goog.ui.Menu.prototype.getItemAt = function(n) {
245 return /** @type {goog.ui.MenuItem?} */ (this.getChildAt(n));
246 };
247
248
249 /**
250 * Returns the number of items in the menu (including separators).
251 * @return {number} The number of items in the menu.
252 * @deprecated Use {@link #getChildCount} instead.
253 */
254 goog.ui.Menu.prototype.getItemCount = function() {
255 return this.getChildCount();
256 };
257
258
259 /**
260 * Returns an array containing the menu items contained in the menu.
261 * @return {!Array<goog.ui.MenuItem>} An array of menu items.
262 * @deprecated Use getChildAt, forEachChild, and getChildCount.
263 */
264 goog.ui.Menu.prototype.getItems = function() {
265 // TODO(user): Remove reference to getItems and instead use getChildAt,
266 // forEachChild, and getChildCount
267 var children = [];
268 this.forEachChild(function(child) { children.push(child); });
269 return children;
270 };
271
272
273 /**
274 * Sets the position of the menu relative to the view port.
275 * @param {number|goog.math.Coordinate} x Left position or coordinate obj.
276 * @param {number=} opt_y Top position.
277 */
278 goog.ui.Menu.prototype.setPosition = function(x, opt_y) {
279 // NOTE(user): It is necessary to temporarily set the display from none, so
280 // that the position gets set correctly.
281 var visible = this.isVisible();
282 if (!visible) {
283 goog.style.setElementShown(this.getElement(), true);
284 }
285 goog.style.setPageOffset(this.getElement(), x, opt_y);
286 if (!visible) {
287 goog.style.setElementShown(this.getElement(), false);
288 }
289 };
290
291
292 /**
293 * Gets the page offset of the menu, or null if the menu isn't visible
294 * @return {goog.math.Coordinate?} Object holding the x-y coordinates of the
295 * menu or null if the menu is not visible.
296 */
297 goog.ui.Menu.prototype.getPosition = function() {
298 return this.isVisible() ? goog.style.getPageOffset(this.getElement()) : null;
299 };
300
301
302 /**
303 * Sets whether the menu can automatically move focus to its key event target
304 * when it is set to visible.
305 * @param {boolean} allow Whether the menu can automatically move focus to its
306 * key event target when it is set to visible.
307 */
308 goog.ui.Menu.prototype.setAllowAutoFocus = function(allow) {
309 this.allowAutoFocus_ = allow;
310 if (allow) {
311 this.setFocusable(true);
312 }
313 };
314
315
316 /**
317 * @return {boolean} Whether the menu can automatically move focus to its key
318 * event target when it is set to visible.
319 */
320 goog.ui.Menu.prototype.getAllowAutoFocus = function() {
321 return this.allowAutoFocus_;
322 };
323
324
325 /**
326 * Sets whether the menu will highlight disabled menu items or skip to the next
327 * active item.
328 * @param {boolean} allow Whether the menu will highlight disabled menu items or
329 * skip to the next active item.
330 */
331 goog.ui.Menu.prototype.setAllowHighlightDisabled = function(allow) {
332 this.allowHighlightDisabled_ = allow;
333 };
334
335
336 /**
337 * @return {boolean} Whether the menu will highlight disabled menu items or skip
338 * to the next active item.
339 */
340 goog.ui.Menu.prototype.getAllowHighlightDisabled = function() {
341 return this.allowHighlightDisabled_;
342 };
343
344
345 /**
346 * @override
347 * @param {boolean} show Whether to show or hide the menu.
348 * @param {boolean=} opt_force If true, doesn't check whether the menu
349 * already has the requested visibility, and doesn't dispatch any events.
350 * @param {goog.events.Event=} opt_e Mousedown event that caused this menu to
351 * be made visible (ignored if show is false).
352 */
353 goog.ui.Menu.prototype.setVisible = function(show, opt_force, opt_e) {
354 var visibilityChanged =
355 goog.ui.Menu.superClass_.setVisible.call(this, show, opt_force);
356 if (visibilityChanged && show && this.isInDocument() &&
357 this.allowAutoFocus_) {
358 this.getKeyEventTarget().focus();
359 }
360 if (show && opt_e && goog.isNumber(opt_e.clientX)) {
361 this.openingCoords = new goog.math.Coordinate(opt_e.clientX, opt_e.clientY);
362 } else {
363 this.openingCoords = null;
364 }
365 return visibilityChanged;
366 };
367
368
369 /** @override */
370 goog.ui.Menu.prototype.handleEnterItem = function(e) {
371 if (this.allowAutoFocus_) {
372 this.getKeyEventTarget().focus();
373 }
374
375 return goog.ui.Menu.superClass_.handleEnterItem.call(this, e);
376 };
377
378
379 /**
380 * Highlights the next item that begins with the specified string. If no
381 * (other) item begins with the given string, the selection is unchanged.
382 * @param {string} charStr The prefix to match.
383 * @return {boolean} Whether a matching prefix was found.
384 */
385 goog.ui.Menu.prototype.highlightNextPrefix = function(charStr) {
386 var re = new RegExp('^' + goog.string.regExpEscape(charStr), 'i');
387 return this.highlightHelper(function(index, max) {
388 // Index is >= -1 because it is set to -1 when nothing is selected.
389 var start = index < 0 ? 0 : index;
390 var wrapped = false;
391
392 // We always start looking from one after the current, because we
393 // keep the current selection only as a last resort. This makes the
394 // loop a little awkward in the case where there is no current
395 // selection, as we need to stop somewhere but can't just stop
396 // when index == start, which is why we need the 'wrapped' flag.
397 do {
398 ++index;
399 if (index == max) {
400 index = 0;
401 wrapped = true;
402 }
403 var name = this.getChildAt(index).getCaption();
404 if (name && name.match(re)) {
405 return index;
406 }
407 } while (!wrapped || index != start);
408 return this.getHighlightedIndex();
409 }, this.getHighlightedIndex());
410 };
411
412
413 /** @override */
414 goog.ui.Menu.prototype.canHighlightItem = function(item) {
415 return (this.allowHighlightDisabled_ || item.isEnabled()) &&
416 item.isVisible() && item.isSupportedState(goog.ui.Component.State.HOVER);
417 };
418
419
420 /** @override */
421 goog.ui.Menu.prototype.decorateInternal = function(element) {
422 this.decorateContent(element);
423 goog.ui.Menu.superClass_.decorateInternal.call(this, element);
424 };
425
426
427 /** @override */
428 goog.ui.Menu.prototype.handleKeyEventInternal = function(e) {
429 var handled = goog.ui.Menu.base(this, 'handleKeyEventInternal', e);
430 if (!handled) {
431 // Loop through all child components, and for each menu item call its
432 // key event handler so that keyboard mnemonics can be handled.
433 this.forEachChild(function(menuItem) {
434 if (!handled && menuItem.getMnemonic &&
435 menuItem.getMnemonic() == e.keyCode) {
436 if (this.isEnabled()) {
437 this.setHighlighted(menuItem);
438 }
439 // We still delegate to handleKeyEvent, so that it can handle
440 // enabled/disabled state.
441 handled = menuItem.handleKeyEvent(e);
442 }
443 }, this);
444 }
445 return handled;
446 };
447
448
449 /** @override */
450 goog.ui.Menu.prototype.setHighlightedIndex = function(index) {
451 goog.ui.Menu.base(this, 'setHighlightedIndex', index);
452
453 // Bring the highlighted item into view. This has no effect if the menu is not
454 // scrollable.
455 var child = this.getChildAt(index);
456 if (child) {
457 goog.style.scrollIntoContainerView(child.getElement(), this.getElement());
458 }
459 };
460
461
462 /**
463 * Decorate menu items located in any descendent node which as been explicitly
464 * marked as a 'content' node.
465 * @param {Element} element Element to decorate.
466 * @protected
467 */
468 goog.ui.Menu.prototype.decorateContent = function(element) {
469 var renderer = this.getRenderer();
470 var contentElements = this.getDomHelper().getElementsByTagNameAndClass(
471 goog.dom.TagName.DIV, goog.getCssName(renderer.getCssClass(), 'content'),
472 element);
473
474 // Some versions of IE do not like it when you access this nodeList
475 // with invalid indices. See
476 // http://code.google.com/p/closure-library/issues/detail?id=373
477 var length = contentElements.length;
478 for (var i = 0; i < length; i++) {
479 renderer.decorateChildren(this, contentElements[i]);
480 }
481 };