select.js 18 KB

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