All files / src/inputType WheelInput.ts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226        2x 2x     2x 2x                                                                                                             2x   76x 76x     76x 76x 76x           76x 76x               76x     2x   76x 76x     2x 75x 75x 75x     2x 149x 149x             2x 76x 76x               2x 2x 2x               2x 1x 1x               2x 4x     71x 71x 1x     70x               70x 6x   64x   64x 58x 58x     64x           64x   64x 54x 54x 54x         2x 70x 70x 70x                           2x 75x 75x     75x 75x 75x     2x 224x 224x 224x   224x 224x   224x 58x 58x     2x  
/*
 * Copyright (c) 2015 NAVER Corp.
 * egjs projects are licensed under the MIT license
 */
import { $, getDirection, useDirection } from "../utils";
import { ANY, DIRECTION_HORIZONTAL, DIRECTION_VERTICAL } from "../const";
import { ElementType } from "../types";
 
import { toAxis, InputType, InputTypeObserver } from "./InputType";
import { isValidKey } from "../eventInput/EventInput";
 
export interface WheelInputOption {
  inputKey?: string[];
  scale?: number;
  releaseDelay?: number;
  useNormalized?: boolean;
  useAnimation?: boolean;
}
 
/**
 * @typedef {Object} WheelInputOption The option object of the eg.Axes.WheelInput module
 * @ko eg.Axes.WheelInput 모듈의 옵션 객체
 * @param {String[]} [inputKey=["any"]] List of key combinations to allow input
 * - any: any key
 * - shift: shift key
 * - ctrl: ctrl key and pinch gesture on the trackpad
 * - alt: alt key
 * - meta: meta key
 * - none: none of these keys are pressed <ko>입력을 허용할 키 조합 목록
 * - any: 아무 키
 * - shift: shift 키
 * - ctrl: ctrl 키 및 트랙패드의 pinch 제스쳐
 * - alt: alt 키
 * - meta: meta 키
 * - none: 아무 키도 눌리지 않은 상태 </ko>
 * @param {Number} [scale=1] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
 * @param {Number} [releaseDelay=300] Millisecond that trigger release event after last input<ko>마지막 입력 이후 release 이벤트가 트리거되기까지의 밀리초</ko>
 * @param {Boolean} [useNormalized=true] Whether to calculate scroll speed the same in all browsers<ko>모든 브라우저에서 스크롤 속도를 동일하게 처리할지 여부</ko>
 * @param {Boolean} [useAnimation=false] Whether to process coordinate changes through the mouse wheel as a continuous animation<ko>마우스 휠을 통한 좌표 변화를 연속적인 애니메이션으로 처리할지 여부</ko>
 **/
 
/**
 * A module that passes the amount of change to eg.Axes when the mouse wheel is moved. use one axis.
 * @ko 마우스 휠이 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 두개 이하의 축을 사용한다.
 *
 * @example
 * ```js
 * const wheel = new eg.Axes.WheelInput("#area", {
 *     scale: 1
 * });
 *
 * // Connect only one 'something1' axis to the vertical mouse wheel.
 * axes.connect(["something1"], wheel); // or axes.connect("something1", wheel);
 *
 * // Connect only one 'something2' axis to the horizontal mouse wheel.
 * axes.connect(["", "something2"], wheel); // or axes.connect(" something2", pan);
 *
 * // Connect the 'something1' axis to the vertical mouse wheel.
 * // Connect the 'something2' axis to the horizontal mouse wheel.
 * axes.connect(["something1", "something2"], wheel);
 * ```
 * @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.WheelInput module <ko>eg.Axes.WheelInput 모듈을 사용할 엘리먼트</ko>
 * @param {WheelInputOption} [options] The option object of the eg.Axes.WheelInput module<ko>eg.Axes.WheelInput 모듈의 옵션 객체</ko>
 */
export class WheelInput implements InputType {
  public options: WheelInputOption;
  public axes: string[] = [];
  public element: HTMLElement = null;
  private _observer: InputTypeObserver;
  private _direction: number;
  private _enabled = false;
  private _holding = false;
  private _timer: NodeJS.Timeout = null;
 
  /**
   *
   */
  public constructor(el: ElementType, options?: WheelInputOption) {
    this.element = $(el);
    this.options = {
      inputKey: [ANY],
      scale: 1,
      releaseDelay: 300,
      useNormalized: true,
      useAnimation: false,
      ...options,
    };
    this._onWheel = this._onWheel.bind(this);
  }
 
  public mapAxes(axes: string[]) {
    // vertical mouse wheel is mapped into axes[0]
    this._direction = getDirection(!!axes[1], !!axes[0]);
    this.axes = axes;
  }
 
  public connect(observer: InputTypeObserver): InputType {
    this._detachEvent();
    this._attachEvent(observer);
    return this;
  }
 
  public disconnect() {
    this._detachEvent();
    return this;
  }
 
  /**
   * Destroys elements, properties, and events used in a module.
   * @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
   */
  public destroy() {
    this.disconnect();
    this.element = null;
  }
 
  /**
   * Enables input devices
   * @ko 입력 장치를 사용할 수 있게 한다
   * @return {WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
   */
  public enable() {
    this._enabled = true;
    return this;
  }
 
  /**
   * Disables input devices
   * @ko 입력 장치를 사용할 수 없게 한다.
   * @return {WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
   */
  public disable() {
    this._enabled = false;
    return this;
  }
 
  /**
   * Returns whether to use an input device
   * @ko 입력 장치를 사용 여부를 반환한다.
   * @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
   */
  public isEnabled() {
    return this._enabled;
  }
 
  private _onWheel(event: WheelEvent) {
    if (!this._enabled || !isValidKey(event, this.options.inputKey)) {
      return;
    }
 
    const offset = this._getOffset(
      [event.deltaY, event.deltaX],
      [
        useDirection(DIRECTION_VERTICAL, this._direction),
        useDirection(DIRECTION_HORIZONTAL, this._direction),
      ]
    );
 
    if (offset[0] === 0 && offset[1] === 0) {
      return;
    }
    event.preventDefault();
 
    if (!this._holding) {
      this._observer.hold(this, event);
      this._holding = true;
    }
 
    this._observer.change(
      this,
      event,
      toAxis(this.axes, offset),
      this.options.useAnimation
    );
    clearTimeout(this._timer);
 
    this._timer = setTimeout(() => {
      Eif (this._holding) {
        this._holding = false;
        this._observer.release(this, event, [0]);
      }
    }, this.options.releaseDelay);
  }
 
  private _getOffset(properties: number[], direction: boolean[]): number[] {
    const scale = this.options.scale;
    const useNormalized = this.options.useNormalized;
    return [
      direction[0] && properties[0]
        ? (properties[0] > 0 ? -1 : 1) *
          (useNormalized ? 1 : Math.abs(properties[0])) *
          scale
        : 0,
      direction[1] && properties[1]
        ? (properties[1] > 0 ? -1 : 1) *
          (useNormalized ? 1 : Math.abs(properties[1])) *
          scale
        : 0,
    ];
  }
 
  private _attachEvent(observer: InputTypeObserver) {
    const element = this.element;
    Iif (!element) {
      throw new Error("Element to connect input does not exist.");
    }
    this._observer = observer;
    element.addEventListener("wheel", this._onWheel);
    this._enabled = true;
  }
 
  private _detachEvent() {
    const element = this.element;
    Eif (element) {
      this.element.removeEventListener("wheel", this._onWheel);
    }
    this._enabled = false;
    this._observer = null;
 
    if (this._timer) {
      clearTimeout(this._timer);
      this._timer = null;
    }
  }
}