Debian Codegraph @

closure-library/closure/goog/ui/select.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 class that supports single selection from a dropdown menu,
17 * with semantics similar to the native HTML <code>&lt;select&gt;</code>
18 * element.
19 *
20 * @author [email protected] (Attila Bodis)
21 * @see ../demos/select.html
22 */
23
24 goog.provide('goog.ui.Select');
25
26 goog.require('goog.a11y.aria');
27 goog.require('goog.a11y.aria.Role');
28 goog.require('goog.a11y.aria.State');
29 goog.require('goog.array');
30 goog.require('goog.events.EventType');
31 goog.require('goog.ui.Component');
32 goog.require('goog.ui.IdGenerator');
33 goog.require('goog.ui.MenuButton');
34 goog.require('goog.ui.MenuItem');
35 goog.require('goog.ui.MenuRenderer');
36 goog.require('goog.ui.SelectionModel');
37 goog.require('goog.ui.registry');
38
39
40
41 /**
42 * A selection control. Extends {@link goog.ui.MenuButton} by composing a
43 * menu with a selection model, and automatically updating the button's caption
44 * based on the current selection.
45 *
46 * Select fires the following events:
47 * CHANGE - after selection changes.
48 *
49 * @param {goog.ui.ControlContent=} opt_caption Default caption or existing DOM
50 * structure to display as the button's caption when nothing is selected.
51 * Defaults to no caption.
52 * @param {goog.ui.Menu=} opt_menu Menu containing selection options.
53 * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
54 * decorate the control; defaults to {@link goog.ui.MenuButtonRenderer}.
55 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
56 * document interaction.
57 * @param {!goog.ui.MenuRenderer=} opt_menuRenderer Renderer used to render or
58 * decorate the menu; defaults to {@link goog.ui.MenuRenderer}.
59 * @constructor
60 * @extends {goog.ui.MenuButton}
61 */
62 goog.ui.Select = function(
63 opt_caption, opt_menu, opt_renderer, opt_domHelper, opt_menuRenderer) {
64 goog.ui.Select.base(
65 this, 'constructor', opt_caption, opt_menu, opt_renderer, opt_domHelper,
66 opt_menuRenderer ||
67 new goog.ui.MenuRenderer(goog.a11y.aria.Role.LISTBOX));
68 /**
69 * Default caption to show when no option is selected.
70 * @private {goog.ui.ControlContent}
71 */
72 this.defaultCaption_ = this.getContent();
73
74 /**
75 * The initial value of the aria label of the content element. This will be
76 * null until the caption is first populated and will be non-null thereafter.
77 * @private {?string}
78 */
79 this.initialAriaLabel_ = null;
80
81 this.setPreferredAriaRole(goog.a11y.aria.Role.LISTBOX);
82 };
83 goog.inherits(goog.ui.Select, goog.ui.MenuButton);
84 goog.tagUnsealableClass(goog.ui.Select);
85
86
87 /**
88 * The selection model controlling the items in the menu.
89 * @type {goog.ui.SelectionModel}
90 * @private
91 */
92 goog.ui.Select.prototype.selectionModel_ = null;
93
94
95 /** @override */
96 goog.ui.Select.prototype.enterDocument = function() {
97 goog.ui.Select.superClass_.enterDocument.call(this);
98 this.updateCaption();
99 this.listenToSelectionModelEvents_();
100 };
101
102
103 /**
104 * Decorates the given element with this control. Overrides the superclass
105 * implementation by initializing the default caption on the select button.
106 * @param {Element} element Element to decorate.
107 * @override
108 */
109 goog.ui.Select.prototype.decorateInternal = function(element) {
110 goog.ui.Select.superClass_.decorateInternal.call(this, element);
111 var caption = this.getCaption();
112 if (caption) {
113 // Initialize the default caption.
114 this.setDefaultCaption(caption);
115 } else if (!this.getSelectedItem()) {
116 // If there is no default caption and no selected item, select the first
117 // option (this is technically an arbitrary choice, but what most people
118 // would expect to happen).
119 this.setSelectedIndex(0);
120 }
121 };
122
123
124 /** @override */
125 goog.ui.Select.prototype.disposeInternal = function() {
126 goog.ui.Select.superClass_.disposeInternal.call(this);
127
128 if (this.selectionModel_) {
129 this.selectionModel_.dispose();
130 this.selectionModel_ = null;
131 }
132
133 this.defaultCaption_ = null;
134 };
135
136
137 /**
138 * Handles {@link goog.ui.Component.EventType.ACTION} events dispatched by
139 * the menu item clicked by the user. Updates the selection model, calls
140 * the superclass implementation to hide the menu, stops the propagation of
141 * the event, and dispatches an ACTION event on behalf of the select control
142 * itself. Overrides {@link goog.ui.MenuButton#handleMenuAction}.
143 * @param {goog.events.Event} e Action event to handle.
144 * @override
145 */
146 goog.ui.Select.prototype.handleMenuAction = function(e) {
147 this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (e.target));
148 goog.ui.Select.base(this, 'handleMenuAction', e);
149
150 // NOTE(chrishenry): We should not stop propagation and then fire
151 // our own ACTION event. Fixing this without breaking anyone
152 // relying on this event is hard though.
153 e.stopPropagation();
154 this.dispatchEvent(goog.ui.Component.EventType.ACTION);
155 };
156
157
158 /**
159 * Handles {@link goog.events.EventType.SELECT} events raised by the
160 * selection model when the selection changes. Updates the contents of the
161 * select button.
162 * @param {goog.events.Event} e Selection event to handle.
163 */
164 goog.ui.Select.prototype.handleSelectionChange = function(e) {
165 var item = this.getSelectedItem();
166 goog.ui.Select.superClass_.setValue.call(this, item && item.getValue());
167 this.updateCaption();
168 };
169
170
171 /**
172 * Replaces the menu currently attached to the control (if any) with the given
173 * argument, and updates the selection model. Does nothing if the new menu is
174 * the same as the old one. Overrides {@link goog.ui.MenuButton#setMenu}.
175 * @param {goog.ui.Menu} menu New menu to be attached to the menu button.
176 * @return {goog.ui.Menu|undefined} Previous menu (undefined if none).
177 * @override
178 */
179 goog.ui.Select.prototype.setMenu = function(menu) {
180 // Call superclass implementation to replace the menu.
181 var oldMenu = goog.ui.Select.superClass_.setMenu.call(this, menu);
182
183 // Do nothing unless the new menu is different from the current one.
184 if (menu != oldMenu) {
185 // Clear the old selection model (if any).
186 if (this.selectionModel_) {
187 this.selectionModel_.clear();
188 }
189
190 // Initialize new selection model (unless the new menu is null).
191 if (menu) {
192 if (this.selectionModel_) {
193 menu.forEachChild(function(child, index) {
194 this.setCorrectAriaRole_(
195 /** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (child));
196 this.selectionModel_.addItem(child);
197 }, this);
198 } else {
199 this.createSelectionModel_(menu);
200 }
201 }
202 }
203
204 return oldMenu;
205 };
206
207
208 /**
209 * Returns the default caption to be shown when no option is selected.
210 * @return {goog.ui.ControlContent} Default caption.
211 */
212 goog.ui.Select.prototype.getDefaultCaption = function() {
213 return this.defaultCaption_;
214 };
215
216
217 /**
218 * Sets the default caption to the given string or DOM structure.
219 * @param {goog.ui.ControlContent} caption Default caption to be shown
220 * when no option is selected.
221 */
222 goog.ui.Select.prototype.setDefaultCaption = function(caption) {
223 this.defaultCaption_ = caption;
224 this.updateCaption();
225 };
226
227
228 /**
229 * Adds a new menu item at the end of the menu.
230 * @param {goog.ui.Control} item Menu item to add to the menu.
231 * @override
232 */
233 goog.ui.Select.prototype.addItem = function(item) {
234 this.setCorrectAriaRole_(
235 /** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (item));
236 goog.ui.Select.superClass_.addItem.call(this, item);
237
238 if (this.selectionModel_) {
239 this.selectionModel_.addItem(item);
240 } else {
241 this.createSelectionModel_(this.getMenu());
242 }
243 this.updateAriaActiveDescendant_();
244 };
245
246
247 /**
248 * Adds a new menu item at a specific index in the menu.
249 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
250 * menu.
251 * @param {number} index Index at which to insert the menu item.
252 * @override
253 */
254 goog.ui.Select.prototype.addItemAt = function(item, index) {
255 this.setCorrectAriaRole_(
256 /** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (item));
257 goog.ui.Select.superClass_.addItemAt.call(this, item, index);
258
259 if (this.selectionModel_) {
260 this.selectionModel_.addItemAt(item, index);
261 } else {
262 this.createSelectionModel_(this.getMenu());
263 }
264 };
265
266
267 /**
268 * Removes an item from the menu and disposes it.
269 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The menu item to remove.
270 * @override
271 */
272 goog.ui.Select.prototype.removeItem = function(item) {
273 goog.ui.Select.superClass_.removeItem.call(this, item);
274 if (this.selectionModel_) {
275 this.selectionModel_.removeItem(item);
276 }
277 };
278
279
280 /**
281 * Removes a menu item at a given index in the menu and disposes it.
282 * @param {number} index Index of item.
283 * @override
284 */
285 goog.ui.Select.prototype.removeItemAt = function(index) {
286 goog.ui.Select.superClass_.removeItemAt.call(this, index);
287 if (this.selectionModel_) {
288 this.selectionModel_.removeItemAt(index);
289 }
290 };
291
292
293 /**
294 * Selects the specified option (assumed to be in the select menu), and
295 * deselects the previously selected option, if any. A null argument clears
296 * the selection.
297 * @param {goog.ui.MenuItem} item Option to be selected (null to clear
298 * the selection).
299 */
300 goog.ui.Select.prototype.setSelectedItem = function(item) {
301 if (this.selectionModel_) {
302 var prevItem = this.getSelectedItem();
303 this.selectionModel_.setSelectedItem(item);
304
305 if (item != prevItem) {
306 this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
307 }
308 }
309 };
310
311
312 /**
313 * Selects the option at the specified index, or clears the selection if the
314 * index is out of bounds.
315 * @param {number} index Index of the option to be selected.
316 */
317 goog.ui.Select.prototype.setSelectedIndex = function(index) {
318 if (this.selectionModel_) {
319 this.setSelectedItem(/** @type {goog.ui.MenuItem} */
320 (this.selectionModel_.getItemAt(index)));
321 }
322 };
323
324
325 /**
326 * Selects the first option found with an associated value equal to the
327 * argument, or clears the selection if no such option is found. A null
328 * argument also clears the selection. Overrides {@link
329 * goog.ui.Button#setValue}.
330 * @param {*} value Value of the option to be selected (null to clear
331 * the selection).
332 * @override
333 */
334 goog.ui.Select.prototype.setValue = function(value) {
335 if (goog.isDefAndNotNull(value) && this.selectionModel_) {
336 for (var i = 0, item; item = this.selectionModel_.getItemAt(i); i++) {
337 if (item && typeof item.getValue == 'function' &&
338 item.getValue() == value) {
339 this.setSelectedItem(/** @type {!goog.ui.MenuItem} */ (item));
340 return;
341 }
342 }
343 }
344
345 this.setSelectedItem(null);
346 };
347
348
349 /**
350 * Gets the value associated with the currently selected option (null if none).
351 *
352 * Note that unlike {@link goog.ui.Button#getValue} which this method overrides,
353 * the "value" of a Select instance is the value of its selected menu item, not
354 * its own value. This makes a difference because the "value" of a Button is
355 * reset to the value of the element it decorates when it's added to the DOM
356 * (via ButtonRenderer), whereas the value of the selected item is unaffected.
357 * So while setValue() has no effect on a Button before it is added to the DOM,
358 * it will make a persistent change to a Select instance (which is consistent
359 * with any changes made by {@link goog.ui.Select#setSelectedItem} and
360 * {@link goog.ui.Select#setSelectedIndex}).
361 *
362 * @override
363 */
364 goog.ui.Select.prototype.getValue = function() {
365 var selectedItem = this.getSelectedItem();
366 return selectedItem ? selectedItem.getValue() : null;
367 };
368
369
370 /**
371 * Returns the currently selected option.
372 * @return {goog.ui.MenuItem} The currently selected option (null if none).
373 */
374 goog.ui.Select.prototype.getSelectedItem = function() {
375 return this.selectionModel_ ?
376 /** @type {goog.ui.MenuItem} */ (this.selectionModel_.getSelectedItem()) :
377 null;
378 };
379
380
381 /**
382 * Returns the index of the currently selected option.
383 * @return {number} 0-based index of the currently selected option (-1 if none).
384 */
385 goog.ui.Select.prototype.getSelectedIndex = function() {
386 return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1;
387 };
388
389
390 /**
391 * @return {goog.ui.SelectionModel} The selection model.
392 * @protected
393 */
394 goog.ui.Select.prototype.getSelectionModel = function() {
395 return this.selectionModel_;
396 };
397
398
399 /**
400 * Creates a new selection model and sets up an event listener to handle
401 * {@link goog.events.EventType.SELECT} events dispatched by it.
402 * @param {goog.ui.Component=} opt_component If provided, will add the
403 * component's children as items to the selection model.
404 * @private
405 */
406 goog.ui.Select.prototype.createSelectionModel_ = function(opt_component) {
407 this.selectionModel_ = new goog.ui.SelectionModel();
408 if (opt_component) {
409 opt_component.forEachChild(function(child, index) {
410 this.setCorrectAriaRole_(
411 /** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (child));
412 this.selectionModel_.addItem(child);
413 }, this);
414 }
415 this.listenToSelectionModelEvents_();
416 };
417
418
419 /**
420 * Subscribes to events dispatched by the selection model.
421 * @private
422 */
423 goog.ui.Select.prototype.listenToSelectionModelEvents_ = function() {
424 if (this.selectionModel_) {
425 this.getHandler().listen(
426 this.selectionModel_, goog.events.EventType.SELECT,
427 this.handleSelectionChange);
428 }
429 };
430
431
432 /**
433 * Updates the caption to be shown in the select button. If no option is
434 * selected and a default caption is set, sets the caption to the default
435 * caption; otherwise to the empty string.
436 * @protected
437 */
438 goog.ui.Select.prototype.updateCaption = function() {
439 var item = this.getSelectedItem();
440 this.setContent(item ? item.getCaption() : this.defaultCaption_);
441
442 var contentElement = this.getRenderer().getContentElement(this.getElement());
443 // Despite the ControlRenderer interface indicating the return value is
444 // {Element}, many renderers cast element.firstChild to {Element} when it is
445 // really {Node}. Checking tagName verifies this is an {!Element}.
446 if (contentElement && this.getDomHelper().isElement(contentElement)) {
447 if (this.initialAriaLabel_ == null) {
448 this.initialAriaLabel_ = goog.a11y.aria.getLabel(contentElement);
449 }
450 var itemElement = item ? item.getElement() : null;
451 goog.a11y.aria.setLabel(
452 contentElement, itemElement ? goog.a11y.aria.getLabel(itemElement) :
453 this.initialAriaLabel_);
454 this.updateAriaActiveDescendant_();
455 }
456 };
457
458
459 /**
460 * Updates the aria active descendant attribute.
461 * @private
462 */
463 goog.ui.Select.prototype.updateAriaActiveDescendant_ = function() {
464 var renderer = this.getRenderer();
465 if (renderer) {
466 var contentElement = renderer.getContentElement(this.getElement());
467 if (contentElement) {
468 var buttonElement = this.getElementStrict();
469 if (!contentElement.id) {
470 contentElement.id = goog.ui.IdGenerator.getInstance().getNextUniqueId();
471 }
472 goog.a11y.aria.setRole(contentElement, goog.a11y.aria.Role.OPTION);
473 goog.a11y.aria.setState(
474 buttonElement, goog.a11y.aria.State.ACTIVEDESCENDANT,
475 contentElement.id);
476 if (this.selectionModel_) {
477 // We can't use selectionmodel's getItemCount here because we need to
478 // skip separators.
479 var items = this.selectionModel_.getItems();
480 goog.a11y.aria.setState(
481 contentElement, goog.a11y.aria.State.SETSIZE,
482 this.getNumMenuItems_(items));
483 // Set a human-readable selection index, excluding menu separators.
484 var index = this.selectionModel_.getSelectedIndex();
485 goog.a11y.aria.setState(
486 contentElement, goog.a11y.aria.State.POSINSET, index >= 0 ?
487 this.getNumMenuItems_(goog.array.slice(items, 0, index + 1)) :
488 0);
489 }
490 }
491 }
492 };
493
494
495 /**
496 * Gets the number of menu items in the array.
497 * @param {!Array<?Object>} items The items.
498 * @return {number}
499 * @private
500 */
501 goog.ui.Select.prototype.getNumMenuItems_ = function(items) {
502 return goog.array.count(
503 items, function(item) { return item instanceof goog.ui.MenuItem; });
504 };
505
506
507 /**
508 * Sets the correct ARIA role for the menu item or separator.
509 * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The item to set.
510 * @private
511 */
512 goog.ui.Select.prototype.setCorrectAriaRole_ = function(item) {
513 item.setPreferredAriaRole(
514 item instanceof goog.ui.MenuItem ? goog.a11y.aria.Role.OPTION :
515 goog.a11y.aria.Role.SEPARATOR);
516 };
517
518
519 /**
520 * Opens or closes the menu. Overrides {@link goog.ui.MenuButton#setOpen} by
521 * highlighting the currently selected option on open.
522 * @param {boolean} open Whether to open or close the menu.
523 * @param {goog.events.Event=} opt_e Mousedown event that caused the menu to
524 * be opened.
525 * @override
526 */
527 goog.ui.Select.prototype.setOpen = function(open, opt_e) {
528 goog.ui.Select.superClass_.setOpen.call(this, open, opt_e);
529
530 if (this.isOpen()) {
531 this.getMenu().setHighlightedIndex(this.getSelectedIndex());
532 } else {
533 this.updateAriaActiveDescendant_();
534 }
535 };
536
537
538 // Register a decorator factory function for goog.ui.Selects.
539 goog.ui.registry.setDecoratorByClassName(
540 goog.getCssName('goog-select'), function() {
541 // Select defaults to using MenuButtonRenderer, since it shares its L&F.
542 return new goog.ui.Select(null);
543 });