control.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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 Base class for UI controls such as buttons, menus, menu items,
  16. * toolbar buttons, etc. The implementation is based on a generalized version
  17. * of {@link goog.ui.MenuItem}.
  18. * TODO(attila): If the renderer framework works well, pull it into Component.
  19. *
  20. * @author attila@google.com (Attila Bodis)
  21. * @see ../demos/control.html
  22. * @see http://code.google.com/p/closure-library/wiki/IntroToControls
  23. */
  24. goog.provide('goog.ui.Control');
  25. goog.require('goog.Disposable');
  26. goog.require('goog.array');
  27. goog.require('goog.dom');
  28. goog.require('goog.events.BrowserEvent');
  29. goog.require('goog.events.Event');
  30. goog.require('goog.events.EventHandler');
  31. goog.require('goog.events.EventType');
  32. goog.require('goog.events.KeyCodes');
  33. goog.require('goog.events.KeyHandler');
  34. goog.require('goog.string');
  35. goog.require('goog.ui.Component');
  36. /** @suppress {extraRequire} */
  37. goog.require('goog.ui.ControlContent');
  38. goog.require('goog.ui.ControlRenderer');
  39. goog.require('goog.ui.registry');
  40. goog.require('goog.userAgent');
  41. /**
  42. * Base class for UI controls. Extends {@link goog.ui.Component} by adding
  43. * the following:
  44. * <ul>
  45. * <li>a {@link goog.events.KeyHandler}, to simplify keyboard handling,
  46. * <li>a pluggable <em>renderer</em> framework, to simplify the creation of
  47. * simple controls without the need to subclass this class,
  48. * <li>the notion of component <em>content</em>, like a text caption or DOM
  49. * structure displayed in the component (e.g. a button label),
  50. * <li>getter and setter for component content, as well as a getter and
  51. * setter specifically for caption text (for convenience),
  52. * <li>support for hiding/showing the component,
  53. <li>fine-grained control over supported states and state transition
  54. events, and
  55. * <li>default mouse and keyboard event handling.
  56. * </ul>
  57. * This class has sufficient built-in functionality for most simple UI controls.
  58. * All controls dispatch SHOW, HIDE, ENTER, LEAVE, and ACTION events on show,
  59. * hide, mouseover, mouseout, and user action, respectively. Additional states
  60. * are also supported. See closure/demos/control.html
  61. * for example usage.
  62. * @param {goog.ui.ControlContent=} opt_content Text caption or DOM structure
  63. * to display as the content of the control (if any).
  64. * @param {goog.ui.ControlRenderer=} opt_renderer Renderer used to render or
  65. * decorate the component; defaults to {@link goog.ui.ControlRenderer}.
  66. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
  67. * document interaction.
  68. * @constructor
  69. * @extends {goog.ui.Component}
  70. */
  71. goog.ui.Control = function(opt_content, opt_renderer, opt_domHelper) {
  72. goog.ui.Component.call(this, opt_domHelper);
  73. this.renderer_ =
  74. opt_renderer || goog.ui.registry.getDefaultRenderer(this.constructor);
  75. this.setContentInternal(goog.isDef(opt_content) ? opt_content : null);
  76. /** @private {?string} The control's aria-label. */
  77. this.ariaLabel_ = null;
  78. /** @private {goog.ui.Control.IeMouseEventSequenceSimulator_} */
  79. this.ieMouseEventSequenceSimulator_;
  80. };
  81. goog.inherits(goog.ui.Control, goog.ui.Component);
  82. goog.tagUnsealableClass(goog.ui.Control);
  83. // Renderer registry.
  84. // TODO(attila): Refactor existing usages inside Google in a follow-up CL.
  85. /**
  86. * Maps a CSS class name to a function that returns a new instance of
  87. * {@link goog.ui.Control} or a subclass thereof, suitable to decorate
  88. * an element that has the specified CSS class. UI components that extend
  89. * {@link goog.ui.Control} and want {@link goog.ui.Container}s to be able
  90. * to discover and decorate elements using them should register a factory
  91. * function via this API.
  92. * @param {string} className CSS class name.
  93. * @param {Function} decoratorFunction Function that takes no arguments and
  94. * returns a new instance of a control to decorate an element with the
  95. * given class.
  96. * @deprecated Use {@link goog.ui.registry.setDecoratorByClassName} instead.
  97. */
  98. goog.ui.Control.registerDecorator = goog.ui.registry.setDecoratorByClassName;
  99. /**
  100. * Takes an element and returns a new instance of {@link goog.ui.Control}
  101. * or a subclass, suitable to decorate it (based on the element's CSS class).
  102. * @param {Element} element Element to decorate.
  103. * @return {goog.ui.Control?} New control instance to decorate the element
  104. * (null if none).
  105. * @deprecated Use {@link goog.ui.registry.getDecorator} instead.
  106. */
  107. goog.ui.Control.getDecorator =
  108. /** @type {function(Element): goog.ui.Control} */ (
  109. goog.ui.registry.getDecorator);
  110. /**
  111. * Renderer associated with the component.
  112. * @type {goog.ui.ControlRenderer|undefined}
  113. * @private
  114. */
  115. goog.ui.Control.prototype.renderer_;
  116. /**
  117. * Text caption or DOM structure displayed in the component.
  118. * @type {goog.ui.ControlContent}
  119. * @private
  120. */
  121. goog.ui.Control.prototype.content_ = null;
  122. /**
  123. * Current component state; a bit mask of {@link goog.ui.Component.State}s.
  124. * @type {number}
  125. * @private
  126. */
  127. goog.ui.Control.prototype.state_ = 0x00;
  128. /**
  129. * A bit mask of {@link goog.ui.Component.State}s this component supports.
  130. * @type {number}
  131. * @private
  132. */
  133. goog.ui.Control.prototype.supportedStates_ = goog.ui.Component.State.DISABLED |
  134. goog.ui.Component.State.HOVER | goog.ui.Component.State.ACTIVE |
  135. goog.ui.Component.State.FOCUSED;
  136. /**
  137. * A bit mask of {@link goog.ui.Component.State}s for which this component
  138. * provides default event handling. For example, a component that handles
  139. * the HOVER state automatically will highlight itself on mouseover, whereas
  140. * a component that doesn't handle HOVER automatically will only dispatch
  141. * ENTER and LEAVE events but not call {@link setHighlighted} on itself.
  142. * By default, components provide default event handling for all states.
  143. * Controls hosted in containers (e.g. menu items in a menu, or buttons in a
  144. * toolbar) will typically want to have their container manage their highlight
  145. * state. Selectable controls managed by a selection model will also typically
  146. * want their selection state to be managed by the model.
  147. * @type {number}
  148. * @private
  149. */
  150. goog.ui.Control.prototype.autoStates_ = goog.ui.Component.State.ALL;
  151. /**
  152. * A bit mask of {@link goog.ui.Component.State}s for which this component
  153. * dispatches state transition events. Because events are expensive, the
  154. * default behavior is to not dispatch any state transition events at all.
  155. * Use the {@link #setDispatchTransitionEvents} API to request transition
  156. * events as needed. Subclasses may enable transition events by default.
  157. * Controls hosted in containers or managed by a selection model will typically
  158. * want to dispatch transition events.
  159. * @type {number}
  160. * @private
  161. */
  162. goog.ui.Control.prototype.statesWithTransitionEvents_ = 0x00;
  163. /**
  164. * Component visibility.
  165. * @type {boolean}
  166. * @private
  167. */
  168. goog.ui.Control.prototype.visible_ = true;
  169. /**
  170. * Keyboard event handler.
  171. * @type {goog.events.KeyHandler}
  172. * @private
  173. */
  174. goog.ui.Control.prototype.keyHandler_;
  175. /**
  176. * Additional class name(s) to apply to the control's root element, if any.
  177. * @type {Array<string>?}
  178. * @private
  179. */
  180. goog.ui.Control.prototype.extraClassNames_ = null;
  181. /**
  182. * Whether the control should listen for and handle mouse events; defaults to
  183. * true.
  184. * @type {boolean}
  185. * @private
  186. */
  187. goog.ui.Control.prototype.handleMouseEvents_ = true;
  188. /**
  189. * Whether the control allows text selection within its DOM. Defaults to false.
  190. * @type {boolean}
  191. * @private
  192. */
  193. goog.ui.Control.prototype.allowTextSelection_ = false;
  194. /**
  195. * The control's preferred ARIA role.
  196. * @type {?goog.a11y.aria.Role}
  197. * @private
  198. */
  199. goog.ui.Control.prototype.preferredAriaRole_ = null;
  200. // Event handler and renderer management.
  201. /**
  202. * Returns true if the control is configured to handle its own mouse events,
  203. * false otherwise. Controls not hosted in {@link goog.ui.Container}s have
  204. * to handle their own mouse events, but controls hosted in containers may
  205. * allow their parent to handle mouse events on their behalf. Considered
  206. * protected; should only be used within this package and by subclasses.
  207. * @return {boolean} Whether the control handles its own mouse events.
  208. */
  209. goog.ui.Control.prototype.isHandleMouseEvents = function() {
  210. return this.handleMouseEvents_;
  211. };
  212. /**
  213. * Enables or disables mouse event handling for the control. Containers may
  214. * use this method to disable mouse event handling in their child controls.
  215. * Considered protected; should only be used within this package and by
  216. * subclasses.
  217. * @param {boolean} enable Whether to enable or disable mouse event handling.
  218. */
  219. goog.ui.Control.prototype.setHandleMouseEvents = function(enable) {
  220. if (this.isInDocument() && enable != this.handleMouseEvents_) {
  221. // Already in the document; need to update event handler.
  222. this.enableMouseEventHandling_(enable);
  223. }
  224. this.handleMouseEvents_ = enable;
  225. };
  226. /**
  227. * Returns the DOM element on which the control is listening for keyboard
  228. * events (null if none).
  229. * @return {Element} Element on which the control is listening for key
  230. * events.
  231. */
  232. goog.ui.Control.prototype.getKeyEventTarget = function() {
  233. // Delegate to renderer.
  234. return this.renderer_.getKeyEventTarget(this);
  235. };
  236. /**
  237. * Returns the keyboard event handler for this component, lazily created the
  238. * first time this method is called. Considered protected; should only be
  239. * used within this package and by subclasses.
  240. * @return {!goog.events.KeyHandler} Keyboard event handler for this component.
  241. * @protected
  242. */
  243. goog.ui.Control.prototype.getKeyHandler = function() {
  244. return this.keyHandler_ || (this.keyHandler_ = new goog.events.KeyHandler());
  245. };
  246. /**
  247. * Returns the renderer used by this component to render itself or to decorate
  248. * an existing element.
  249. * @return {goog.ui.ControlRenderer|undefined} Renderer used by the component
  250. * (undefined if none).
  251. */
  252. goog.ui.Control.prototype.getRenderer = function() {
  253. return this.renderer_;
  254. };
  255. /**
  256. * Registers the given renderer with the component. Changing renderers after
  257. * the component has entered the document is an error.
  258. * @param {goog.ui.ControlRenderer} renderer Renderer used by the component.
  259. * @throws {Error} If the control is already in the document.
  260. */
  261. goog.ui.Control.prototype.setRenderer = function(renderer) {
  262. if (this.isInDocument()) {
  263. // Too late.
  264. throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
  265. }
  266. if (this.getElement()) {
  267. // The component has already been rendered, but isn't yet in the document.
  268. // Replace the renderer and delete the current DOM, so it can be re-rendered
  269. // using the new renderer the next time someone calls render().
  270. this.setElementInternal(null);
  271. }
  272. this.renderer_ = renderer;
  273. };
  274. // Support for additional styling.
  275. /**
  276. * Returns any additional class name(s) to be applied to the component's
  277. * root element, or null if no extra class names are needed.
  278. * @return {Array<string>?} Additional class names to be applied to
  279. * the component's root element (null if none).
  280. */
  281. goog.ui.Control.prototype.getExtraClassNames = function() {
  282. return this.extraClassNames_;
  283. };
  284. /**
  285. * Adds the given class name to the list of classes to be applied to the
  286. * component's root element.
  287. * @param {string} className Additional class name to be applied to the
  288. * component's root element.
  289. */
  290. goog.ui.Control.prototype.addClassName = function(className) {
  291. if (className) {
  292. if (this.extraClassNames_) {
  293. if (!goog.array.contains(this.extraClassNames_, className)) {
  294. this.extraClassNames_.push(className);
  295. }
  296. } else {
  297. this.extraClassNames_ = [className];
  298. }
  299. this.renderer_.enableExtraClassName(this, className, true);
  300. }
  301. };
  302. /**
  303. * Removes the given class name from the list of classes to be applied to
  304. * the component's root element.
  305. * @param {string} className Class name to be removed from the component's root
  306. * element.
  307. */
  308. goog.ui.Control.prototype.removeClassName = function(className) {
  309. if (className && this.extraClassNames_ &&
  310. goog.array.remove(this.extraClassNames_, className)) {
  311. if (this.extraClassNames_.length == 0) {
  312. this.extraClassNames_ = null;
  313. }
  314. this.renderer_.enableExtraClassName(this, className, false);
  315. }
  316. };
  317. /**
  318. * Adds or removes the given class name to/from the list of classes to be
  319. * applied to the component's root element.
  320. * @param {string} className CSS class name to add or remove.
  321. * @param {boolean} enable Whether to add or remove the class name.
  322. */
  323. goog.ui.Control.prototype.enableClassName = function(className, enable) {
  324. if (enable) {
  325. this.addClassName(className);
  326. } else {
  327. this.removeClassName(className);
  328. }
  329. };
  330. // Standard goog.ui.Component implementation.
  331. /**
  332. * Creates the control's DOM. Overrides {@link goog.ui.Component#createDom} by
  333. * delegating DOM manipulation to the control's renderer.
  334. * @override
  335. */
  336. goog.ui.Control.prototype.createDom = function() {
  337. var element = this.renderer_.createDom(this);
  338. this.setElementInternal(element);
  339. // Initialize ARIA role.
  340. this.renderer_.setAriaRole(element, this.getPreferredAriaRole());
  341. // Initialize text selection.
  342. if (!this.isAllowTextSelection()) {
  343. // The renderer is assumed to create selectable elements. Since making
  344. // elements unselectable is expensive, only do it if needed (bug 1037090).
  345. this.renderer_.setAllowTextSelection(element, false);
  346. }
  347. // Initialize visibility.
  348. if (!this.isVisible()) {
  349. // The renderer is assumed to create visible elements. Since hiding
  350. // elements can be expensive, only do it if needed (bug 1037105).
  351. this.renderer_.setVisible(element, false);
  352. }
  353. };
  354. /**
  355. * Returns the control's preferred ARIA role. This can be used by a control to
  356. * override the role that would be assigned by the renderer. This is useful in
  357. * cases where a different ARIA role is appropriate for a control because of the
  358. * context in which it's used. E.g., a {@link goog.ui.MenuButton} added to a
  359. * {@link goog.ui.Select} should have an ARIA role of LISTBOX and not MENUITEM.
  360. * @return {?goog.a11y.aria.Role} This control's preferred ARIA role or null if
  361. * no preferred ARIA role is set.
  362. */
  363. goog.ui.Control.prototype.getPreferredAriaRole = function() {
  364. return this.preferredAriaRole_;
  365. };
  366. /**
  367. * Sets the control's preferred ARIA role. This can be used to override the role
  368. * that would be assigned by the renderer. This is useful in cases where a
  369. * different ARIA role is appropriate for a control because of the
  370. * context in which it's used. E.g., a {@link goog.ui.MenuButton} added to a
  371. * {@link goog.ui.Select} should have an ARIA role of LISTBOX and not MENUITEM.
  372. * @param {goog.a11y.aria.Role} role This control's preferred ARIA role.
  373. */
  374. goog.ui.Control.prototype.setPreferredAriaRole = function(role) {
  375. this.preferredAriaRole_ = role;
  376. };
  377. /**
  378. * Gets the control's aria label.
  379. * @return {?string} This control's aria label.
  380. */
  381. goog.ui.Control.prototype.getAriaLabel = function() {
  382. return this.ariaLabel_;
  383. };
  384. /**
  385. * Sets the control's aria label. This can be used to assign aria label to the
  386. * element after it is rendered.
  387. * @param {string} label The string to set as the aria label for this control.
  388. * No escaping is done on this value.
  389. */
  390. goog.ui.Control.prototype.setAriaLabel = function(label) {
  391. this.ariaLabel_ = label;
  392. var element = this.getElement();
  393. if (element) {
  394. this.renderer_.setAriaLabel(element, label);
  395. }
  396. };
  397. /**
  398. * Returns the DOM element into which child components are to be rendered,
  399. * or null if the control itself hasn't been rendered yet. Overrides
  400. * {@link goog.ui.Component#getContentElement} by delegating to the renderer.
  401. * @return {Element} Element to contain child elements (null if none).
  402. * @override
  403. */
  404. goog.ui.Control.prototype.getContentElement = function() {
  405. // Delegate to renderer.
  406. return this.renderer_.getContentElement(this.getElement());
  407. };
  408. /**
  409. * Returns true if the given element can be decorated by this component.
  410. * Overrides {@link goog.ui.Component#canDecorate}.
  411. * @param {Element} element Element to decorate.
  412. * @return {boolean} Whether the element can be decorated by this component.
  413. * @override
  414. */
  415. goog.ui.Control.prototype.canDecorate = function(element) {
  416. // Controls support pluggable renderers; delegate to the renderer.
  417. return this.renderer_.canDecorate(element);
  418. };
  419. /**
  420. * Decorates the given element with this component. Overrides {@link
  421. * goog.ui.Component#decorateInternal} by delegating DOM manipulation
  422. * to the control's renderer.
  423. * @param {Element} element Element to decorate.
  424. * @protected
  425. * @override
  426. */
  427. goog.ui.Control.prototype.decorateInternal = function(element) {
  428. element = this.renderer_.decorate(this, element);
  429. this.setElementInternal(element);
  430. // Initialize ARIA role.
  431. this.renderer_.setAriaRole(element, this.getPreferredAriaRole());
  432. // Initialize text selection.
  433. if (!this.isAllowTextSelection()) {
  434. // Decorated elements are assumed to be selectable. Since making elements
  435. // unselectable is expensive, only do it if needed (bug 1037090).
  436. this.renderer_.setAllowTextSelection(element, false);
  437. }
  438. // Initialize visibility based on the decorated element's styling.
  439. this.visible_ = element.style.display != 'none';
  440. };
  441. /**
  442. * Configures the component after its DOM has been rendered, and sets up event
  443. * handling. Overrides {@link goog.ui.Component#enterDocument}.
  444. * @override
  445. */
  446. goog.ui.Control.prototype.enterDocument = function() {
  447. goog.ui.Control.superClass_.enterDocument.call(this);
  448. // Call the renderer's setAriaStates method to set element's aria attributes.
  449. this.renderer_.setAriaStates(this, this.getElementStrict());
  450. // Call the renderer's initializeDom method to configure properties of the
  451. // control's DOM that can only be done once it's in the document.
  452. this.renderer_.initializeDom(this);
  453. // Initialize event handling if at least one state other than DISABLED is
  454. // supported.
  455. if (this.supportedStates_ & ~goog.ui.Component.State.DISABLED) {
  456. // Initialize mouse event handling if the control is configured to handle
  457. // its own mouse events. (Controls hosted in containers don't need to
  458. // handle their own mouse events.)
  459. if (this.isHandleMouseEvents()) {
  460. this.enableMouseEventHandling_(true);
  461. }
  462. // Initialize keyboard event handling if the control is focusable and has
  463. // a key event target. (Controls hosted in containers typically aren't
  464. // focusable, allowing their container to handle keyboard events for them.)
  465. if (this.isSupportedState(goog.ui.Component.State.FOCUSED)) {
  466. var keyTarget = this.getKeyEventTarget();
  467. if (keyTarget) {
  468. var keyHandler = this.getKeyHandler();
  469. keyHandler.attach(keyTarget);
  470. this.getHandler()
  471. .listen(
  472. keyHandler, goog.events.KeyHandler.EventType.KEY,
  473. this.handleKeyEvent)
  474. .listen(keyTarget, goog.events.EventType.FOCUS, this.handleFocus)
  475. .listen(keyTarget, goog.events.EventType.BLUR, this.handleBlur);
  476. }
  477. }
  478. }
  479. };
  480. /**
  481. * Enables or disables mouse event handling on the control.
  482. * @param {boolean} enable Whether to enable mouse event handling.
  483. * @private
  484. */
  485. goog.ui.Control.prototype.enableMouseEventHandling_ = function(enable) {
  486. var handler = this.getHandler();
  487. var element = this.getElement();
  488. if (enable) {
  489. handler
  490. .listen(element, goog.events.EventType.MOUSEOVER, this.handleMouseOver)
  491. .listen(element, goog.events.EventType.MOUSEDOWN, this.handleMouseDown)
  492. .listen(element, goog.events.EventType.MOUSEUP, this.handleMouseUp)
  493. .listen(element, goog.events.EventType.MOUSEOUT, this.handleMouseOut);
  494. if (this.handleContextMenu != goog.nullFunction) {
  495. handler.listen(
  496. element, goog.events.EventType.CONTEXTMENU, this.handleContextMenu);
  497. }
  498. if (goog.userAgent.IE) {
  499. // Versions of IE before 9 send only one click event followed by a
  500. // dblclick, so we must explicitly listen for these. In later versions,
  501. // two click events are fired and so a dblclick listener is unnecessary.
  502. if (!goog.userAgent.isVersionOrHigher(9)) {
  503. handler.listen(
  504. element, goog.events.EventType.DBLCLICK, this.handleDblClick);
  505. }
  506. if (!this.ieMouseEventSequenceSimulator_) {
  507. this.ieMouseEventSequenceSimulator_ =
  508. new goog.ui.Control.IeMouseEventSequenceSimulator_(this);
  509. this.registerDisposable(this.ieMouseEventSequenceSimulator_);
  510. }
  511. }
  512. } else {
  513. handler
  514. .unlisten(
  515. element, goog.events.EventType.MOUSEOVER, this.handleMouseOver)
  516. .unlisten(
  517. element, goog.events.EventType.MOUSEDOWN, this.handleMouseDown)
  518. .unlisten(element, goog.events.EventType.MOUSEUP, this.handleMouseUp)
  519. .unlisten(element, goog.events.EventType.MOUSEOUT, this.handleMouseOut);
  520. if (this.handleContextMenu != goog.nullFunction) {
  521. handler.unlisten(
  522. element, goog.events.EventType.CONTEXTMENU, this.handleContextMenu);
  523. }
  524. if (goog.userAgent.IE) {
  525. if (!goog.userAgent.isVersionOrHigher(9)) {
  526. handler.unlisten(
  527. element, goog.events.EventType.DBLCLICK, this.handleDblClick);
  528. }
  529. goog.dispose(this.ieMouseEventSequenceSimulator_);
  530. this.ieMouseEventSequenceSimulator_ = null;
  531. }
  532. }
  533. };
  534. /**
  535. * Cleans up the component before its DOM is removed from the document, and
  536. * removes event handlers. Overrides {@link goog.ui.Component#exitDocument}
  537. * by making sure that components that are removed from the document aren't
  538. * focusable (i.e. have no tab index).
  539. * @override
  540. */
  541. goog.ui.Control.prototype.exitDocument = function() {
  542. goog.ui.Control.superClass_.exitDocument.call(this);
  543. if (this.keyHandler_) {
  544. this.keyHandler_.detach();
  545. }
  546. if (this.isVisible() && this.isEnabled()) {
  547. this.renderer_.setFocusable(this, false);
  548. }
  549. };
  550. /** @override */
  551. goog.ui.Control.prototype.disposeInternal = function() {
  552. goog.ui.Control.superClass_.disposeInternal.call(this);
  553. if (this.keyHandler_) {
  554. this.keyHandler_.dispose();
  555. delete this.keyHandler_;
  556. }
  557. delete this.renderer_;
  558. this.content_ = null;
  559. this.extraClassNames_ = null;
  560. this.ieMouseEventSequenceSimulator_ = null;
  561. };
  562. // Component content management.
  563. /**
  564. * Returns the text caption or DOM structure displayed in the component.
  565. * @return {goog.ui.ControlContent} Text caption or DOM structure
  566. * comprising the component's contents.
  567. */
  568. goog.ui.Control.prototype.getContent = function() {
  569. return this.content_;
  570. };
  571. /**
  572. * Sets the component's content to the given text caption, element, or array of
  573. * nodes. (If the argument is an array of nodes, it must be an actual array,
  574. * not an array-like object.)
  575. * @param {goog.ui.ControlContent} content Text caption or DOM
  576. * structure to set as the component's contents.
  577. */
  578. goog.ui.Control.prototype.setContent = function(content) {
  579. // Controls support pluggable renderers; delegate to the renderer.
  580. this.renderer_.setContent(this.getElement(), content);
  581. // setContentInternal needs to be after the renderer, since the implementation
  582. // may depend on the content being in the DOM.
  583. this.setContentInternal(content);
  584. };
  585. /**
  586. * Sets the component's content to the given text caption, element, or array
  587. * of nodes. Unlike {@link #setContent}, doesn't modify the component's DOM.
  588. * Called by renderers during element decoration.
  589. *
  590. * This should only be used by subclasses and its associated renderers.
  591. *
  592. * @param {goog.ui.ControlContent} content Text caption or DOM structure
  593. * to set as the component's contents.
  594. */
  595. goog.ui.Control.prototype.setContentInternal = function(content) {
  596. this.content_ = content;
  597. };
  598. /**
  599. * @return {string} Text caption of the control or empty string if none.
  600. */
  601. goog.ui.Control.prototype.getCaption = function() {
  602. var content = this.getContent();
  603. if (!content) {
  604. return '';
  605. }
  606. var caption = goog.isString(content) ?
  607. content :
  608. goog.isArray(content) ?
  609. goog.array.map(content, goog.dom.getRawTextContent).join('') :
  610. goog.dom.getTextContent(/** @type {!Node} */ (content));
  611. return goog.string.collapseBreakingSpaces(caption);
  612. };
  613. /**
  614. * Sets the text caption of the component.
  615. * @param {string} caption Text caption of the component.
  616. */
  617. goog.ui.Control.prototype.setCaption = function(caption) {
  618. this.setContent(caption);
  619. };
  620. // Component state management.
  621. /** @override */
  622. goog.ui.Control.prototype.setRightToLeft = function(rightToLeft) {
  623. // The superclass implementation ensures the control isn't in the document.
  624. goog.ui.Control.superClass_.setRightToLeft.call(this, rightToLeft);
  625. var element = this.getElement();
  626. if (element) {
  627. this.renderer_.setRightToLeft(element, rightToLeft);
  628. }
  629. };
  630. /**
  631. * Returns true if the control allows text selection within its DOM, false
  632. * otherwise. Controls that disallow text selection have the appropriate
  633. * unselectable styling applied to their elements. Note that controls hosted
  634. * in containers will report that they allow text selection even if their
  635. * container disallows text selection.
  636. * @return {boolean} Whether the control allows text selection.
  637. */
  638. goog.ui.Control.prototype.isAllowTextSelection = function() {
  639. return this.allowTextSelection_;
  640. };
  641. /**
  642. * Allows or disallows text selection within the control's DOM.
  643. * @param {boolean} allow Whether the control should allow text selection.
  644. */
  645. goog.ui.Control.prototype.setAllowTextSelection = function(allow) {
  646. this.allowTextSelection_ = allow;
  647. var element = this.getElement();
  648. if (element) {
  649. this.renderer_.setAllowTextSelection(element, allow);
  650. }
  651. };
  652. /**
  653. * Returns true if the component's visibility is set to visible, false if
  654. * it is set to hidden. A component that is set to hidden is guaranteed
  655. * to be hidden from the user, but the reverse isn't necessarily true.
  656. * A component may be set to visible but can otherwise be obscured by another
  657. * element, rendered off-screen, or hidden using direct CSS manipulation.
  658. * @return {boolean} Whether the component is visible.
  659. */
  660. goog.ui.Control.prototype.isVisible = function() {
  661. return this.visible_;
  662. };
  663. /**
  664. * Shows or hides the component. Does nothing if the component already has
  665. * the requested visibility. Otherwise, dispatches a SHOW or HIDE event as
  666. * appropriate, giving listeners a chance to prevent the visibility change.
  667. * When showing a component that is both enabled and focusable, ensures that
  668. * its key target has a tab index. When hiding a component that is enabled
  669. * and focusable, blurs its key target and removes its tab index.
  670. * @param {boolean} visible Whether to show or hide the component.
  671. * @param {boolean=} opt_force If true, doesn't check whether the component
  672. * already has the requested visibility, and doesn't dispatch any events.
  673. * @return {boolean} Whether the visibility was changed.
  674. */
  675. goog.ui.Control.prototype.setVisible = function(visible, opt_force) {
  676. if (opt_force || (this.visible_ != visible &&
  677. this.dispatchEvent(
  678. visible ? goog.ui.Component.EventType.SHOW :
  679. goog.ui.Component.EventType.HIDE))) {
  680. var element = this.getElement();
  681. if (element) {
  682. this.renderer_.setVisible(element, visible);
  683. }
  684. if (this.isEnabled()) {
  685. this.renderer_.setFocusable(this, visible);
  686. }
  687. this.visible_ = visible;
  688. return true;
  689. }
  690. return false;
  691. };
  692. /**
  693. * Returns true if the component is enabled, false otherwise.
  694. * @return {boolean} Whether the component is enabled.
  695. */
  696. goog.ui.Control.prototype.isEnabled = function() {
  697. return !this.hasState(goog.ui.Component.State.DISABLED);
  698. };
  699. /**
  700. * Returns true if the control has a parent that is itself disabled, false
  701. * otherwise.
  702. * @return {boolean} Whether the component is hosted in a disabled container.
  703. * @private
  704. */
  705. goog.ui.Control.prototype.isParentDisabled_ = function() {
  706. var parent = this.getParent();
  707. return !!parent && typeof parent.isEnabled == 'function' &&
  708. !parent.isEnabled();
  709. };
  710. /**
  711. * Enables or disables the component. Does nothing if this state transition
  712. * is disallowed. If the component is both visible and focusable, updates its
  713. * focused state and tab index as needed. If the component is being disabled,
  714. * ensures that it is also deactivated and un-highlighted first. Note that the
  715. * component's enabled/disabled state is "locked" as long as it is hosted in a
  716. * {@link goog.ui.Container} that is itself disabled; this is to prevent clients
  717. * from accidentally re-enabling a control that is in a disabled container.
  718. * @param {boolean} enable Whether to enable or disable the component.
  719. * @see #isTransitionAllowed
  720. */
  721. goog.ui.Control.prototype.setEnabled = function(enable) {
  722. if (!this.isParentDisabled_() &&
  723. this.isTransitionAllowed(goog.ui.Component.State.DISABLED, !enable)) {
  724. if (!enable) {
  725. this.setActive(false);
  726. this.setHighlighted(false);
  727. }
  728. if (this.isVisible()) {
  729. this.renderer_.setFocusable(this, enable);
  730. }
  731. this.setState(goog.ui.Component.State.DISABLED, !enable, true);
  732. }
  733. };
  734. /**
  735. * Returns true if the component is currently highlighted, false otherwise.
  736. * @return {boolean} Whether the component is highlighted.
  737. */
  738. goog.ui.Control.prototype.isHighlighted = function() {
  739. return this.hasState(goog.ui.Component.State.HOVER);
  740. };
  741. /**
  742. * Highlights or unhighlights the component. Does nothing if this state
  743. * transition is disallowed.
  744. * @param {boolean} highlight Whether to highlight or unhighlight the component.
  745. * @see #isTransitionAllowed
  746. */
  747. goog.ui.Control.prototype.setHighlighted = function(highlight) {
  748. if (this.isTransitionAllowed(goog.ui.Component.State.HOVER, highlight)) {
  749. this.setState(goog.ui.Component.State.HOVER, highlight);
  750. }
  751. };
  752. /**
  753. * Returns true if the component is active (pressed), false otherwise.
  754. * @return {boolean} Whether the component is active.
  755. */
  756. goog.ui.Control.prototype.isActive = function() {
  757. return this.hasState(goog.ui.Component.State.ACTIVE);
  758. };
  759. /**
  760. * Activates or deactivates the component. Does nothing if this state
  761. * transition is disallowed.
  762. * @param {boolean} active Whether to activate or deactivate the component.
  763. * @see #isTransitionAllowed
  764. */
  765. goog.ui.Control.prototype.setActive = function(active) {
  766. if (this.isTransitionAllowed(goog.ui.Component.State.ACTIVE, active)) {
  767. this.setState(goog.ui.Component.State.ACTIVE, active);
  768. }
  769. };
  770. /**
  771. * Returns true if the component is selected, false otherwise.
  772. * @return {boolean} Whether the component is selected.
  773. */
  774. goog.ui.Control.prototype.isSelected = function() {
  775. return this.hasState(goog.ui.Component.State.SELECTED);
  776. };
  777. /**
  778. * Selects or unselects the component. Does nothing if this state transition
  779. * is disallowed.
  780. * @param {boolean} select Whether to select or unselect the component.
  781. * @see #isTransitionAllowed
  782. */
  783. goog.ui.Control.prototype.setSelected = function(select) {
  784. if (this.isTransitionAllowed(goog.ui.Component.State.SELECTED, select)) {
  785. this.setState(goog.ui.Component.State.SELECTED, select);
  786. }
  787. };
  788. /**
  789. * Returns true if the component is checked, false otherwise.
  790. * @return {boolean} Whether the component is checked.
  791. */
  792. goog.ui.Control.prototype.isChecked = function() {
  793. return this.hasState(goog.ui.Component.State.CHECKED);
  794. };
  795. /**
  796. * Checks or unchecks the component. Does nothing if this state transition
  797. * is disallowed.
  798. * @param {boolean} check Whether to check or uncheck the component.
  799. * @see #isTransitionAllowed
  800. */
  801. goog.ui.Control.prototype.setChecked = function(check) {
  802. if (this.isTransitionAllowed(goog.ui.Component.State.CHECKED, check)) {
  803. this.setState(goog.ui.Component.State.CHECKED, check);
  804. }
  805. };
  806. /**
  807. * Returns true if the component is styled to indicate that it has keyboard
  808. * focus, false otherwise. Note that {@code isFocused()} returning true
  809. * doesn't guarantee that the component's key event target has keyborad focus,
  810. * only that it is styled as such.
  811. * @return {boolean} Whether the component is styled to indicate as having
  812. * keyboard focus.
  813. */
  814. goog.ui.Control.prototype.isFocused = function() {
  815. return this.hasState(goog.ui.Component.State.FOCUSED);
  816. };
  817. /**
  818. * Applies or removes styling indicating that the component has keyboard focus.
  819. * Note that unlike the other "set" methods, this method is called as a result
  820. * of the component's element having received or lost keyboard focus, not the
  821. * other way around, so calling {@code setFocused(true)} doesn't guarantee that
  822. * the component's key event target has keyboard focus, only that it is styled
  823. * as such.
  824. * @param {boolean} focused Whether to apply or remove styling to indicate that
  825. * the component's element has keyboard focus.
  826. */
  827. goog.ui.Control.prototype.setFocused = function(focused) {
  828. if (this.isTransitionAllowed(goog.ui.Component.State.FOCUSED, focused)) {
  829. this.setState(goog.ui.Component.State.FOCUSED, focused);
  830. }
  831. };
  832. /**
  833. * Returns true if the component is open (expanded), false otherwise.
  834. * @return {boolean} Whether the component is open.
  835. */
  836. goog.ui.Control.prototype.isOpen = function() {
  837. return this.hasState(goog.ui.Component.State.OPENED);
  838. };
  839. /**
  840. * Opens (expands) or closes (collapses) the component. Does nothing if this
  841. * state transition is disallowed.
  842. * @param {boolean} open Whether to open or close the component.
  843. * @see #isTransitionAllowed
  844. */
  845. goog.ui.Control.prototype.setOpen = function(open) {
  846. if (this.isTransitionAllowed(goog.ui.Component.State.OPENED, open)) {
  847. this.setState(goog.ui.Component.State.OPENED, open);
  848. }
  849. };
  850. /**
  851. * Returns the component's state as a bit mask of {@link
  852. * goog.ui.Component.State}s.
  853. * @return {number} Bit mask representing component state.
  854. */
  855. goog.ui.Control.prototype.getState = function() {
  856. return this.state_;
  857. };
  858. /**
  859. * Returns true if the component is in the specified state, false otherwise.
  860. * @param {goog.ui.Component.State} state State to check.
  861. * @return {boolean} Whether the component is in the given state.
  862. */
  863. goog.ui.Control.prototype.hasState = function(state) {
  864. return !!(this.state_ & state);
  865. };
  866. /**
  867. * Sets or clears the given state on the component, and updates its styling
  868. * accordingly. Does nothing if the component is already in the correct state
  869. * or if it doesn't support the specified state. Doesn't dispatch any state
  870. * transition events; use advisedly.
  871. * @param {goog.ui.Component.State} state State to set or clear.
  872. * @param {boolean} enable Whether to set or clear the state (if supported).
  873. * @param {boolean=} opt_calledFrom Prevents looping with setEnabled.
  874. */
  875. goog.ui.Control.prototype.setState = function(state, enable, opt_calledFrom) {
  876. if (!opt_calledFrom && state == goog.ui.Component.State.DISABLED) {
  877. this.setEnabled(!enable);
  878. return;
  879. }
  880. if (this.isSupportedState(state) && enable != this.hasState(state)) {
  881. // Delegate actual styling to the renderer, since it is DOM-specific.
  882. this.renderer_.setState(this, state, enable);
  883. this.state_ = enable ? this.state_ | state : this.state_ & ~state;
  884. }
  885. };
  886. /**
  887. * Sets the component's state to the state represented by a bit mask of
  888. * {@link goog.ui.Component.State}s. Unlike {@link #setState}, doesn't
  889. * update the component's styling, and doesn't reject unsupported states.
  890. * Called by renderers during element decoration. Considered protected;
  891. * should only be used within this package and by subclasses.
  892. *
  893. * This should only be used by subclasses and its associated renderers.
  894. *
  895. * @param {number} state Bit mask representing component state.
  896. */
  897. goog.ui.Control.prototype.setStateInternal = function(state) {
  898. this.state_ = state;
  899. };
  900. /**
  901. * Returns true if the component supports the specified state, false otherwise.
  902. * @param {goog.ui.Component.State} state State to check.
  903. * @return {boolean} Whether the component supports the given state.
  904. */
  905. goog.ui.Control.prototype.isSupportedState = function(state) {
  906. return !!(this.supportedStates_ & state);
  907. };
  908. /**
  909. * Enables or disables support for the given state. Disabling support
  910. * for a state while the component is in that state is an error.
  911. * @param {goog.ui.Component.State} state State to support or de-support.
  912. * @param {boolean} support Whether the component should support the state.
  913. * @throws {Error} If disabling support for a state the control is currently in.
  914. */
  915. goog.ui.Control.prototype.setSupportedState = function(state, support) {
  916. if (this.isInDocument() && this.hasState(state) && !support) {
  917. // Since we hook up event handlers in enterDocument(), this is an error.
  918. throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
  919. }
  920. if (!support && this.hasState(state)) {
  921. // We are removing support for a state that the component is currently in.
  922. this.setState(state, false);
  923. }
  924. this.supportedStates_ =
  925. support ? this.supportedStates_ | state : this.supportedStates_ & ~state;
  926. };
  927. /**
  928. * Returns true if the component provides default event handling for the state,
  929. * false otherwise.
  930. * @param {goog.ui.Component.State} state State to check.
  931. * @return {boolean} Whether the component provides default event handling for
  932. * the state.
  933. */
  934. goog.ui.Control.prototype.isAutoState = function(state) {
  935. return !!(this.autoStates_ & state) && this.isSupportedState(state);
  936. };
  937. /**
  938. * Enables or disables automatic event handling for the given state(s).
  939. * @param {number} states Bit mask of {@link goog.ui.Component.State}s for which
  940. * default event handling is to be enabled or disabled.
  941. * @param {boolean} enable Whether the component should provide default event
  942. * handling for the state(s).
  943. */
  944. goog.ui.Control.prototype.setAutoStates = function(states, enable) {
  945. this.autoStates_ =
  946. enable ? this.autoStates_ | states : this.autoStates_ & ~states;
  947. };
  948. /**
  949. * Returns true if the component is set to dispatch transition events for the
  950. * given state, false otherwise.
  951. * @param {goog.ui.Component.State} state State to check.
  952. * @return {boolean} Whether the component dispatches transition events for
  953. * the state.
  954. */
  955. goog.ui.Control.prototype.isDispatchTransitionEvents = function(state) {
  956. return !!(this.statesWithTransitionEvents_ & state) &&
  957. this.isSupportedState(state);
  958. };
  959. /**
  960. * Enables or disables transition events for the given state(s). Controls
  961. * handle state transitions internally by default, and only dispatch state
  962. * transition events if explicitly requested to do so by calling this method.
  963. * @param {number} states Bit mask of {@link goog.ui.Component.State}s for
  964. * which transition events should be enabled or disabled.
  965. * @param {boolean} enable Whether transition events should be enabled.
  966. */
  967. goog.ui.Control.prototype.setDispatchTransitionEvents = function(
  968. states, enable) {
  969. this.statesWithTransitionEvents_ = enable ?
  970. this.statesWithTransitionEvents_ | states :
  971. this.statesWithTransitionEvents_ & ~states;
  972. };
  973. /**
  974. * Returns true if the transition into or out of the given state is allowed to
  975. * proceed, false otherwise. A state transition is allowed under the following
  976. * conditions:
  977. * <ul>
  978. * <li>the component supports the state,
  979. * <li>the component isn't already in the target state,
  980. * <li>either the component is configured not to dispatch events for this
  981. * state transition, or a transition event was dispatched and wasn't
  982. * canceled by any event listener, and
  983. * <li>the component hasn't been disposed of
  984. * </ul>
  985. * Considered protected; should only be used within this package and by
  986. * subclasses.
  987. * @param {goog.ui.Component.State} state State to/from which the control is
  988. * transitioning.
  989. * @param {boolean} enable Whether the control is entering or leaving the state.
  990. * @return {boolean} Whether the state transition is allowed to proceed.
  991. * @protected
  992. */
  993. goog.ui.Control.prototype.isTransitionAllowed = function(state, enable) {
  994. return this.isSupportedState(state) && this.hasState(state) != enable &&
  995. (!(this.statesWithTransitionEvents_ & state) ||
  996. this.dispatchEvent(
  997. goog.ui.Component.getStateTransitionEvent(state, enable))) &&
  998. !this.isDisposed();
  999. };
  1000. // Default event handlers, to be overridden in subclasses.
  1001. /**
  1002. * Handles mouseover events. Dispatches an ENTER event; if the event isn't
  1003. * canceled, the component is enabled, and it supports auto-highlighting,
  1004. * highlights the component. Considered protected; should only be used
  1005. * within this package and by subclasses.
  1006. * @param {goog.events.BrowserEvent} e Mouse event to handle.
  1007. */
  1008. goog.ui.Control.prototype.handleMouseOver = function(e) {
  1009. // Ignore mouse moves between descendants.
  1010. if (!goog.ui.Control.isMouseEventWithinElement_(e, this.getElement()) &&
  1011. this.dispatchEvent(goog.ui.Component.EventType.ENTER) &&
  1012. this.isEnabled() && this.isAutoState(goog.ui.Component.State.HOVER)) {
  1013. this.setHighlighted(true);
  1014. }
  1015. };
  1016. /**
  1017. * Handles mouseout events. Dispatches a LEAVE event; if the event isn't
  1018. * canceled, and the component supports auto-highlighting, deactivates and
  1019. * un-highlights the component. Considered protected; should only be used
  1020. * within this package and by subclasses.
  1021. * @param {goog.events.BrowserEvent} e Mouse event to handle.
  1022. */
  1023. goog.ui.Control.prototype.handleMouseOut = function(e) {
  1024. if (!goog.ui.Control.isMouseEventWithinElement_(e, this.getElement()) &&
  1025. this.dispatchEvent(goog.ui.Component.EventType.LEAVE)) {
  1026. if (this.isAutoState(goog.ui.Component.State.ACTIVE)) {
  1027. // Deactivate on mouseout; otherwise we lose track of the mouse button.
  1028. this.setActive(false);
  1029. }
  1030. if (this.isAutoState(goog.ui.Component.State.HOVER)) {
  1031. this.setHighlighted(false);
  1032. }
  1033. }
  1034. };
  1035. /**
  1036. * Handles contextmenu events.
  1037. * @param {goog.events.BrowserEvent} e Event to handle.
  1038. */
  1039. goog.ui.Control.prototype.handleContextMenu = goog.nullFunction;
  1040. /**
  1041. * Checks if a mouse event (mouseover or mouseout) occurred below an element.
  1042. * @param {goog.events.BrowserEvent} e Mouse event (should be mouseover or
  1043. * mouseout).
  1044. * @param {Element} elem The ancestor element.
  1045. * @return {boolean} Whether the event has a relatedTarget (the element the
  1046. * mouse is coming from) and it's a descendent of elem.
  1047. * @private
  1048. */
  1049. goog.ui.Control.isMouseEventWithinElement_ = function(e, elem) {
  1050. // If relatedTarget is null, it means there was no previous element (e.g.
  1051. // the mouse moved out of the window). Assume this means that the mouse
  1052. // event was not within the element.
  1053. return !!e.relatedTarget && goog.dom.contains(elem, e.relatedTarget);
  1054. };
  1055. /**
  1056. * Handles mousedown events. If the component is enabled, highlights and
  1057. * activates it. If the component isn't configured for keyboard access,
  1058. * prevents it from receiving keyboard focus. Considered protected; should
  1059. * only be used within this package and by subclasses.
  1060. * @param {goog.events.Event} e Mouse event to handle.
  1061. */
  1062. goog.ui.Control.prototype.handleMouseDown = function(e) {
  1063. if (this.isEnabled()) {
  1064. // Highlight enabled control on mousedown, regardless of the mouse button.
  1065. if (this.isAutoState(goog.ui.Component.State.HOVER)) {
  1066. this.setHighlighted(true);
  1067. }
  1068. // For the left button only, activate the control, and focus its key event
  1069. // target (if supported).
  1070. if (e.isMouseActionButton()) {
  1071. if (this.isAutoState(goog.ui.Component.State.ACTIVE)) {
  1072. this.setActive(true);
  1073. }
  1074. if (this.renderer_ && this.renderer_.isFocusable(this)) {
  1075. this.getKeyEventTarget().focus();
  1076. }
  1077. }
  1078. }
  1079. // Cancel the default action unless the control allows text selection.
  1080. if (!this.isAllowTextSelection() && e.isMouseActionButton()) {
  1081. e.preventDefault();
  1082. }
  1083. };
  1084. /**
  1085. * Handles mouseup events. If the component is enabled, highlights it. If
  1086. * the component has previously been activated, performs its associated action
  1087. * by calling {@link performActionInternal}, then deactivates it. Considered
  1088. * protected; should only be used within this package and by subclasses.
  1089. * @param {goog.events.Event} e Mouse event to handle.
  1090. */
  1091. goog.ui.Control.prototype.handleMouseUp = function(e) {
  1092. if (this.isEnabled()) {
  1093. if (this.isAutoState(goog.ui.Component.State.HOVER)) {
  1094. this.setHighlighted(true);
  1095. }
  1096. if (this.isActive() && this.performActionInternal(e) &&
  1097. this.isAutoState(goog.ui.Component.State.ACTIVE)) {
  1098. this.setActive(false);
  1099. }
  1100. }
  1101. };
  1102. /**
  1103. * Handles dblclick events. Should only be registered if the user agent is
  1104. * IE. If the component is enabled, performs its associated action by calling
  1105. * {@link performActionInternal}. This is used to allow more performant
  1106. * buttons in IE. In IE, no mousedown event is fired when that mousedown will
  1107. * trigger a dblclick event. Because of this, a user clicking quickly will
  1108. * only cause ACTION events to fire on every other click. This is a workaround
  1109. * to generate ACTION events for every click. Unfortunately, this workaround
  1110. * won't ever trigger the ACTIVE state. This is roughly the same behaviour as
  1111. * if this were a 'button' element with a listener on mouseup. Considered
  1112. * protected; should only be used within this package and by subclasses.
  1113. * @param {goog.events.Event} e Mouse event to handle.
  1114. */
  1115. goog.ui.Control.prototype.handleDblClick = function(e) {
  1116. if (this.isEnabled()) {
  1117. this.performActionInternal(e);
  1118. }
  1119. };
  1120. /**
  1121. * Performs the appropriate action when the control is activated by the user.
  1122. * The default implementation first updates the checked and selected state of
  1123. * controls that support them, then dispatches an ACTION event. Considered
  1124. * protected; should only be used within this package and by subclasses.
  1125. * @param {goog.events.Event} e Event that triggered the action.
  1126. * @return {boolean} Whether the action is allowed to proceed.
  1127. * @protected
  1128. */
  1129. goog.ui.Control.prototype.performActionInternal = function(e) {
  1130. if (this.isAutoState(goog.ui.Component.State.CHECKED)) {
  1131. this.setChecked(!this.isChecked());
  1132. }
  1133. if (this.isAutoState(goog.ui.Component.State.SELECTED)) {
  1134. this.setSelected(true);
  1135. }
  1136. if (this.isAutoState(goog.ui.Component.State.OPENED)) {
  1137. this.setOpen(!this.isOpen());
  1138. }
  1139. var actionEvent =
  1140. new goog.events.Event(goog.ui.Component.EventType.ACTION, this);
  1141. if (e) {
  1142. actionEvent.altKey = e.altKey;
  1143. actionEvent.ctrlKey = e.ctrlKey;
  1144. actionEvent.metaKey = e.metaKey;
  1145. actionEvent.shiftKey = e.shiftKey;
  1146. actionEvent.platformModifierKey = e.platformModifierKey;
  1147. }
  1148. return this.dispatchEvent(actionEvent);
  1149. };
  1150. /**
  1151. * Handles focus events on the component's key event target element. If the
  1152. * component is focusable, updates its state and styling to indicate that it
  1153. * now has keyboard focus. Considered protected; should only be used within
  1154. * this package and by subclasses. <b>Warning:</b> IE dispatches focus and
  1155. * blur events asynchronously!
  1156. * @param {goog.events.Event} e Focus event to handle.
  1157. */
  1158. goog.ui.Control.prototype.handleFocus = function(e) {
  1159. if (this.isAutoState(goog.ui.Component.State.FOCUSED)) {
  1160. this.setFocused(true);
  1161. }
  1162. };
  1163. /**
  1164. * Handles blur events on the component's key event target element. Always
  1165. * deactivates the component. In addition, if the component is focusable,
  1166. * updates its state and styling to indicate that it no longer has keyboard
  1167. * focus. Considered protected; should only be used within this package and
  1168. * by subclasses. <b>Warning:</b> IE dispatches focus and blur events
  1169. * asynchronously!
  1170. * @param {goog.events.Event} e Blur event to handle.
  1171. */
  1172. goog.ui.Control.prototype.handleBlur = function(e) {
  1173. if (this.isAutoState(goog.ui.Component.State.ACTIVE)) {
  1174. this.setActive(false);
  1175. }
  1176. if (this.isAutoState(goog.ui.Component.State.FOCUSED)) {
  1177. this.setFocused(false);
  1178. }
  1179. };
  1180. /**
  1181. * Attempts to handle a keyboard event, if the component is enabled and visible,
  1182. * by calling {@link handleKeyEventInternal}. Considered protected; should only
  1183. * be used within this package and by subclasses.
  1184. * @param {goog.events.KeyEvent} e Key event to handle.
  1185. * @return {boolean} Whether the key event was handled.
  1186. */
  1187. goog.ui.Control.prototype.handleKeyEvent = function(e) {
  1188. if (this.isVisible() && this.isEnabled() && this.handleKeyEventInternal(e)) {
  1189. e.preventDefault();
  1190. e.stopPropagation();
  1191. return true;
  1192. }
  1193. return false;
  1194. };
  1195. /**
  1196. * Attempts to handle a keyboard event; returns true if the event was handled,
  1197. * false otherwise. Considered protected; should only be used within this
  1198. * package and by subclasses.
  1199. * @param {goog.events.KeyEvent} e Key event to handle.
  1200. * @return {boolean} Whether the key event was handled.
  1201. * @protected
  1202. */
  1203. goog.ui.Control.prototype.handleKeyEventInternal = function(e) {
  1204. return e.keyCode == goog.events.KeyCodes.ENTER &&
  1205. this.performActionInternal(e);
  1206. };
  1207. // Register the default renderer for goog.ui.Controls.
  1208. goog.ui.registry.setDefaultRenderer(goog.ui.Control, goog.ui.ControlRenderer);
  1209. // Register a decorator factory function for goog.ui.Controls.
  1210. goog.ui.registry.setDecoratorByClassName(
  1211. goog.ui.ControlRenderer.CSS_CLASS,
  1212. function() { return new goog.ui.Control(null); });
  1213. /**
  1214. * A singleton that helps goog.ui.Control instances play well with screen
  1215. * readers. It necessitated by shortcomings in IE, and need not be
  1216. * instantiated in any other browser.
  1217. *
  1218. * In most cases, a click on a goog.ui.Control results in a sequence of events:
  1219. * MOUSEDOWN, MOUSEUP and CLICK. UI controls rely on this sequence since most
  1220. * behavior is trigged by MOUSEDOWN and MOUSEUP. But when IE is used with some
  1221. * traditional screen readers (JAWS, NVDA and perhaps others), IE only sends
  1222. * the CLICK event, resulting in the control being unresponsive. This class
  1223. * monitors the sequence of these events, and if it detects a CLICK event not
  1224. * not preceded by a MOUSEUP event, directly calls the control's event handlers
  1225. * for MOUSEDOWN, then MOUSEUP. While the resulting sequence is different from
  1226. * the norm (the CLICK comes first instead of last), testing thus far shows
  1227. * the resulting behavior to be correct.
  1228. *
  1229. * See http://goo.gl/qvQR4C for more details.
  1230. *
  1231. * @param {!goog.ui.Control} control
  1232. * @constructor
  1233. * @extends {goog.Disposable}
  1234. * @private
  1235. */
  1236. goog.ui.Control.IeMouseEventSequenceSimulator_ = function(control) {
  1237. goog.ui.Control.IeMouseEventSequenceSimulator_.base(this, 'constructor');
  1238. /** @private {goog.ui.Control}*/
  1239. this.control_ = control;
  1240. /** @private {boolean} */
  1241. this.clickExpected_ = false;
  1242. /** @private @const {!goog.events.EventHandler<
  1243. * !goog.ui.Control.IeMouseEventSequenceSimulator_>}
  1244. */
  1245. this.handler_ = new goog.events.EventHandler(this);
  1246. this.registerDisposable(this.handler_);
  1247. var element = this.control_.getElementStrict();
  1248. this.handler_
  1249. .listen(element, goog.events.EventType.MOUSEDOWN, this.handleMouseDown_)
  1250. .listen(element, goog.events.EventType.MOUSEUP, this.handleMouseUp_)
  1251. .listen(element, goog.events.EventType.CLICK, this.handleClick_);
  1252. };
  1253. goog.inherits(goog.ui.Control.IeMouseEventSequenceSimulator_, goog.Disposable);
  1254. /**
  1255. * Whether this browser supports synthetic MouseEvents.
  1256. *
  1257. * See https://msdn.microsoft.com/library/dn905219(v=vs.85).aspx for details.
  1258. *
  1259. * @private {boolean}
  1260. * @const
  1261. */
  1262. goog.ui.Control.IeMouseEventSequenceSimulator_.SYNTHETIC_EVENTS_ =
  1263. !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9);
  1264. /** @private */
  1265. goog.ui.Control.IeMouseEventSequenceSimulator_.prototype.handleMouseDown_ =
  1266. function() {
  1267. this.clickExpected_ = false;
  1268. };
  1269. /** @private */
  1270. goog.ui.Control.IeMouseEventSequenceSimulator_.prototype.handleMouseUp_ =
  1271. function() {
  1272. this.clickExpected_ = true;
  1273. };
  1274. /**
  1275. * @param {!MouseEvent} e
  1276. * @param {goog.events.EventType} typeArg
  1277. * @return {!MouseEvent}
  1278. * @private
  1279. */
  1280. goog.ui.Control.IeMouseEventSequenceSimulator_.makeLeftMouseEvent_ = function(
  1281. e, typeArg) {
  1282. 'use strict';
  1283. if (!goog.ui.Control.IeMouseEventSequenceSimulator_.SYNTHETIC_EVENTS_) {
  1284. // IE < 9 does not support synthetic mouse events. Therefore, reuse the
  1285. // existing MouseEvent by overwriting the read only button and type
  1286. // properties. As IE < 9 does not support ES5 strict mode this will not
  1287. // generate an exception even when the script specifies "use strict".
  1288. e.button = goog.events.BrowserEvent.MouseButton.LEFT;
  1289. e.type = typeArg;
  1290. return e;
  1291. }
  1292. var event = /** @type {!MouseEvent} */ (document.createEvent('MouseEvents'));
  1293. event.initMouseEvent(
  1294. typeArg, e.bubbles, e.cancelable,
  1295. e.view || null, // IE9 errors if view is undefined
  1296. e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey,
  1297. e.shiftKey, e.metaKey, goog.events.BrowserEvent.MouseButton.LEFT,
  1298. e.relatedTarget || null); // IE9 errors if relatedTarget is undefined
  1299. return event;
  1300. };
  1301. /**
  1302. * @param {!goog.events.Event} e
  1303. * @private
  1304. */
  1305. goog.ui.Control.IeMouseEventSequenceSimulator_.prototype.handleClick_ =
  1306. function(e) {
  1307. if (this.clickExpected_) {
  1308. // This is the end of a normal click sequence: mouse-down, mouse-up, click.
  1309. // Assume appropriate actions have already been performed.
  1310. this.clickExpected_ = false;
  1311. return;
  1312. }
  1313. // For click events not part of a normal sequence, similate the mouse-down and
  1314. // mouse-up events by creating synthetic events for each and directly invoke
  1315. // the corresponding event listeners in order.
  1316. var browserEvent = /** @type {goog.events.BrowserEvent} */ (e);
  1317. var event = /** @type {!MouseEvent} */ (browserEvent.getBrowserEvent());
  1318. var origEventButton = event.button;
  1319. var origEventType = event.type;
  1320. var down = goog.ui.Control.IeMouseEventSequenceSimulator_.makeLeftMouseEvent_(
  1321. event, goog.events.EventType.MOUSEDOWN);
  1322. this.control_.handleMouseDown(
  1323. new goog.events.BrowserEvent(down, browserEvent.currentTarget));
  1324. var up = goog.ui.Control.IeMouseEventSequenceSimulator_.makeLeftMouseEvent_(
  1325. event, goog.events.EventType.MOUSEUP);
  1326. this.control_.handleMouseUp(
  1327. new goog.events.BrowserEvent(up, browserEvent.currentTarget));
  1328. if (goog.ui.Control.IeMouseEventSequenceSimulator_.SYNTHETIC_EVENTS_) {
  1329. // This browser supports synthetic events. Avoid resetting the read only
  1330. // properties (type, button) as they were not overwritten and writing them
  1331. // results in an exception when running in ES5 strict mode.
  1332. return;
  1333. }
  1334. // Restore original values for click handlers that have not yet been invoked.
  1335. event.button = origEventButton;
  1336. event.type = origEventType;
  1337. };
  1338. /** @override */
  1339. goog.ui.Control.IeMouseEventSequenceSimulator_.prototype.disposeInternal =
  1340. function() {
  1341. this.control_ = null;
  1342. goog.ui.Control.IeMouseEventSequenceSimulator_.base(this, 'disposeInternal');
  1343. };