# lib/goog/events/browserevent.js

    1// Copyright 2005 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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415/**16 * @fileoverview A patched, standardized event object for browser events.17 *18 * <pre>19 * The patched event object contains the following members:20 * - type           {string}    Event type, e.g. 'click'21 * - target         {Object}    The element that actually triggered the event22 * - currentTarget  {Object}    The element the listener is attached to23 * - relatedTarget  {Object}    For mouseover and mouseout, the previous object24 * - offsetX        {number}    X-coordinate relative to target25 * - offsetY        {number}    Y-coordinate relative to target26 * - clientX        {number}    X-coordinate relative to viewport27 * - clientY        {number}    Y-coordinate relative to viewport28 * - screenX        {number}    X-coordinate relative to the edge of the screen29 * - screenY        {number}    Y-coordinate relative to the edge of the screen30 * - button         {number}    Mouse button. Use isButton() to test.31 * - keyCode        {number}    Key-code32 * - ctrlKey        {boolean}   Was ctrl key depressed33 * - altKey         {boolean}   Was alt key depressed34 * - shiftKey       {boolean}   Was shift key depressed35 * - metaKey        {boolean}   Was meta key depressed36 * - defaultPrevented {boolean} Whether the default action has been prevented37 * - state          {Object}    History state object38 *39 * NOTE: The keyCode member contains the raw browser keyCode. For normalized40 * key and character code use {@link goog.events.KeyHandler}.41 * </pre>42 *43 */4445goog.provide('goog.events.BrowserEvent');46goog.provide('goog.events.BrowserEvent.MouseButton');4748goog.require('goog.events.BrowserFeature');49goog.require('goog.events.Event');50goog.require('goog.events.EventType');51goog.require('goog.reflect');52goog.require('goog.userAgent');53545556/**57 * Accepts a browser event object and creates a patched, cross browser event58 * object.59 * The content of this object will not be initialized if no event object is60 * provided. If this is the case, init() needs to be invoked separately.61 * @param {Event=} opt_e Browser event object.62 * @param {EventTarget=} opt_currentTarget Current target for event.63 * @constructor64 * @extends {goog.events.Event}65 */66goog.events.BrowserEvent = function(opt_e, opt_currentTarget) {67  goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');6869  /**70   * Target that fired the event.71   * @override72   * @type {Node}73   */74  this.target = null;7576  /**77   * Node that had the listener attached.78   * @override79   * @type {Node|undefined}80   */81  this.currentTarget = null;8283  /**84   * For mouseover and mouseout events, the related object for the event.85   * @type {Node}86   */87  this.relatedTarget = null;8889  /**90   * X-coordinate relative to target.91   * @type {number}92   */93  this.offsetX = 0;9495  /**96   * Y-coordinate relative to target.97   * @type {number}98   */99  this.offsetY = 0;100101  /**102   * X-coordinate relative to the window.103   * @type {number}104   */105  this.clientX = 0;106107  /**108   * Y-coordinate relative to the window.109   * @type {number}110   */111  this.clientY = 0;112113  /**114   * X-coordinate relative to the monitor.115   * @type {number}116   */117  this.screenX = 0;118119  /**120   * Y-coordinate relative to the monitor.121   * @type {number}122   */123  this.screenY = 0;124125  /**126   * Which mouse button was pressed.127   * @type {number}128   */129  this.button = 0;130131  /**132   * Keycode of key press.133   * @type {number}134   */135  this.keyCode = 0;136137  /**138   * Keycode of key press.139   * @type {number}140   */141  this.charCode = 0;142143  /**144   * Whether control was pressed at time of event.145   * @type {boolean}146   */147  this.ctrlKey = false;148149  /**150   * Whether alt was pressed at time of event.151   * @type {boolean}152   */153  this.altKey = false;154155  /**156   * Whether shift was pressed at time of event.157   * @type {boolean}158   */159  this.shiftKey = false;160161  /**162   * Whether the meta key was pressed at time of event.163   * @type {boolean}164   */165  this.metaKey = false;166167  /**168   * History state object, only set for PopState events where it's a copy of the169   * state object provided to pushState or replaceState.170   * @type {Object}171   */172  this.state = null;173174  /**175   * Whether the default platform modifier key was pressed at time of event.176   * (This is control for all platforms except Mac, where it's Meta.)177   * @type {boolean}178   */179  this.platformModifierKey = false;180181  /**182   * The browser event object.183   * @private {Event}184   */185  this.event_ = null;186187  if (opt_e) {188    this.init(opt_e, opt_currentTarget);189  }190};191goog.inherits(goog.events.BrowserEvent, goog.events.Event);192193194/**195 * Normalized button constants for the mouse.196 * @enum {number}197 */198goog.events.BrowserEvent.MouseButton = {199  LEFT: 0,200  MIDDLE: 1,201  RIGHT: 2202};203204205/**206 * Static data for mapping mouse buttons.207 * @type {!Array.<number>}208 */209goog.events.BrowserEvent.IEButtonMap = [210  1, // LEFT211  4, // MIDDLE212  2  // RIGHT213];214215216/**217 * Accepts a browser event object and creates a patched, cross browser event218 * object.219 * @param {Event} e Browser event object.220 * @param {EventTarget=} opt_currentTarget Current target for event.221 */222goog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {223  var type = this.type = e.type;224225  // TODO(nicksantos): Change this.target to type EventTarget.226  this.target = /** @type {Node} */ (e.target) || e.srcElement;227228  // TODO(nicksantos): Change this.currentTarget to type EventTarget.229  this.currentTarget = /** @type {Node} */ (opt_currentTarget);230231  var relatedTarget = /** @type {Node} */ (e.relatedTarget);232  if (relatedTarget) {233    // There's a bug in FireFox where sometimes, relatedTarget will be a234    // chrome element, and accessing any property of it will get a permission235    // denied exception. See:236    // https://bugzilla.mozilla.org/show_bug.cgi?id=497780237    if (goog.userAgent.GECKO) {238      if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {239        relatedTarget = null;240      }241    }242    // TODO(arv): Use goog.events.EventType when it has been refactored into its243    // own file.244  } else if (type == goog.events.EventType.MOUSEOVER) {245    relatedTarget = e.fromElement;246  } else if (type == goog.events.EventType.MOUSEOUT) {247    relatedTarget = e.toElement;248  }249250  this.relatedTarget = relatedTarget;251252  // Webkit emits a lame warning whenever layerX/layerY is accessed.253  // http://code.google.com/p/chromium/issues/detail?id=101733254  this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?255      e.offsetX : e.layerX;256  this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?257      e.offsetY : e.layerY;258259  this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;260  this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;261  this.screenX = e.screenX || 0;262  this.screenY = e.screenY || 0;263264  this.button = e.button;265266  this.keyCode = e.keyCode || 0;267  this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);268  this.ctrlKey = e.ctrlKey;269  this.altKey = e.altKey;270  this.shiftKey = e.shiftKey;271  this.metaKey = e.metaKey;272  this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;273  this.state = e.state;274  this.event_ = e;275  if (e.defaultPrevented) {276    this.preventDefault();277  }278};279280281/**282 * Tests to see which button was pressed during the event. This is really only283 * useful in IE and Gecko browsers. And in IE, it's only useful for284 * mousedown/mouseup events, because click only fires for the left mouse button.285 *286 * Safari 2 only reports the left button being clicked, and uses the value '1'287 * instead of 0. Opera only reports a mousedown event for the middle button, and288 * no mouse events for the right button. Opera has default behavior for left and289 * middle click that can only be overridden via a configuration setting.290 *291 * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.292 *293 * @param {goog.events.BrowserEvent.MouseButton} button The button294 *     to test for.295 * @return {boolean} True if button was pressed.296 */297goog.events.BrowserEvent.prototype.isButton = function(button) {298  if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {299    if (this.type == 'click') {300      return button == goog.events.BrowserEvent.MouseButton.LEFT;301    } else {302      return !!(this.event_.button &303          goog.events.BrowserEvent.IEButtonMap[button]);304    }305  } else {306    return this.event_.button == button;307  }308};309310311/**312 * Whether this has an "action"-producing mouse button.313 *314 * By definition, this includes left-click on windows/linux, and left-click315 * without the ctrl key on Macs.316 *317 * @return {boolean} The result.318 */319goog.events.BrowserEvent.prototype.isMouseActionButton = function() {320  // Webkit does not ctrl+click to be a right-click, so we321  // normalize it to behave like Gecko and Opera.322  return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&323      !(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);324};325326327/**328 * @override329 */330goog.events.BrowserEvent.prototype.stopPropagation = function() {331  goog.events.BrowserEvent.superClass_.stopPropagation.call(this);332  if (this.event_.stopPropagation) {333    this.event_.stopPropagation();334  } else {335    this.event_.cancelBubble = true;336  }337};338339340/**341 * @override342 */343goog.events.BrowserEvent.prototype.preventDefault = function() {344  goog.events.BrowserEvent.superClass_.preventDefault.call(this);345  var be = this.event_;346  if (!be.preventDefault) {347    be.returnValue = false;348    if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {349      /** @preserveTry */350      try {351        // Most keys can be prevented using returnValue. Some special keys352        // require setting the keyCode to -1 as well:353        //354        // In IE7:355        // F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)356        //357        // In IE8:358        // Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)359        //360        // We therefore do this for all function keys as well as when Ctrl key361        // is pressed.362        var VK_F1 = 112;363        var VK_F12 = 123;364        if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {365          be.keyCode = -1;366        }367      } catch (ex) {368        // IE throws an 'access denied' exception when trying to change369        // keyCode in some situations (e.g. srcElement is input[type=file],370        // or srcElement is an anchor tag rewritten by parent's innerHTML).371        // Do nothing in this case.372      }373    }374  } else {375    be.preventDefault();376  }377};378379380/**381 * @return {Event} The underlying browser event object.382 */383goog.events.BrowserEvent.prototype.getBrowserEvent = function() {384  return this.event_;385};386387388/** @override */389goog.events.BrowserEvent.prototype.disposeInternal = function() {390};