All files / src/mixins BaseKeyboardEventMixin.js

86.45% Statements 83/96
74.19% Branches 46/62
89.28% Functions 25/28
90.9% Lines 80/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348                  1x                               1x                       8x 8x 8x       8x                                       27x   27x   27x   27x   27x 27x             5x 5x 5x 5x             30x 5x                       104x 104x 104x   46x   46x       104x   104x     40x                       104x               2x                 114x                 48x 48x 48x 16x 16x   32x 4x 4x         48x                 46x 46x 46x 52x               8x   8x 8x   8x 8x 8x 8x 8x 8x   8x   8x   8x                         8x                                       7x                           30x             3x     30x 30x 30x 22x     8x 1x   8x     30x     30x       30x   41x   30x               44x   44x                   44x   44x                               1x   1x 1x   7x     1x   3x                              
/* eslint max-lines: ["error", 400] */
// @ts-check
 
import { bindAll, forEach, get, isArray, isEmpty, last, reduce, remove, set,
  split, union } from "lodash";
 
import { createStore } from "../store";
import { mixinMaker } from "../utils";
 
const KeyMap = {
  Enter: "enter",
  Escape: "esc",
  Shift: "shift",
  " ": "space",
  ArrowLeft: "left",
  ArrowRight: "right",
  ArrowUp: "up",
  ArrowDown: "down",
  Meta: "meta",
  Control: "ctrl",
  Alt: "alt",
  "+": "plus",
  "-": "minus"
};
 
const Mod = {
  ctrl: 0x01,
  alt: 0x02,
  shift: 0x04,
  meta: 0x08
};
 
/**
 * @param {Event?} event
 * @returns {boolean}
 */
function isInput(event) {
  Eif (event && event.target) {
    const tagName = /** @type string */(get(event.target, "tagName", ""));
    Iif (tagName === "INPUT" || tagName === "SELECT" || tagName === "TEXTAREA") {
      return !get(event.target, "readOnly", false);
    }
    else {
      return get(event.target, "isContentEditable", false);
    }
  }
  return false;
}
 
/**
 * @typedef {{[key: string]: function}} ListenerCallbacks
 */
 
/** @type KeyboardEventHandler */
export let _globalListener;
 
export class KeyboardEventHandler {
  /**
   * @param {Element | null} target
   * @param {boolean} checkOnInputs
   */
  constructor(target = null, checkOnInputs/*: boolean */ = true) {
    /** @type ListenerCallbacks */
    this.listeners = {};
    /** @type Element | Document */
    this.target = target || window.document;
    /** @type boolean */
    this.checkOnInputs = checkOnInputs;
    /** @type boolean */
    this._keyupAttached = false;
    /** @type boolean */
    this._keydownAttached = false;
    bindAll(this, [ "onKeyEvent" ]);
  }
 
  /**
   * @return {void}
   */
  release() {
    this.target.removeEventListener("keyup", /** @type EventListener */(this.onKeyEvent));
    this.target.removeEventListener("keydown", /** @type EventListener */(this.onKeyEvent));
    this._keyupAttached = false;
    this._keydownAttached = false;
  }
 
  /**
   * @return {void}
   */
  releaseIfEmpty() {
    if (isEmpty(this.listeners)) {
      this.release();
    }
  }
 
  /**
   * @param {string} key
   * @returns {{keyCode: string, modMask: number, eventType: string}}
   */
  // Doesn't make much sense having it here but it's useful for unittest
  parseKey(key /*: string */) {
    // Example key: ctrl-shift-s-keyup
    // last keyup/keydown is optional. Default is keyup
    const parts = split(key, "-");
    let eType = "keyup";
    if (last(parts) === "keyup" || last(parts) === "keydown") {
      // @ts-ignore undefined can't happen
      eType = last(parts);
      // remove eventType from parts
      parts.pop();
    }
    // Extract the last part as key
    // @ts-ignore undefined can't happen
    key = parts.pop();
    // Transform mods in a mask
    return {
      keyCode: key,
      // @ts-ignore
      modMask: reduce(parts, (ret, m) => (Mod[m] | ret), 0),
      eventType: eType
    };
  }
 
  /**
   * @param {string} keyCode
   * @param {number} mod
   * @param {string} eType
   * @returns {string}
   */
  genKeyHash(keyCode/*: string */, mod /*: number */, eType /*: string */) {
    return `${keyCode}-${mod}-${eType}`;
  }
 
  /**
   * @param {boolean} value
   * @return {void}
   */
  setCheckOnInput(value /*: boolean */) {
    this.checkOnInputs = value;
  }
 
  /**
   * @param {string} key
   * @returns {any}
   */
  getCallBacks(key /*: string */) {
    // return empty array if there are no callbacks
    return get(this.listeners, key, []);
  }
 
  /**
   * @param {string} key
   * @param {function} cb
   */
  addCallBack(key/*: string */, cb /*: function */) {
    // Attach event listener if there is the first time
    const { keyCode, modMask, eventType } = this.parseKey(key);
    const keyHash = this.genKeyHash(keyCode, modMask, eventType);
    if (eventType === "keyup" && !this._keyupAttached) {
      this.target.addEventListener("keyup", /** @type EventListener */(this.onKeyEvent));
      this._keyupAttached = true;
    }
    else if (eventType === "keydown" && !this._keydownAttached) {
      this.target.addEventListener("keydown", /** @type EventListener */(this.onKeyEvent));
      this._keydownAttached = true;
    }
 
    // If the same cb already exist for the same keyHash, the union
    // function will not duplicate it.
    set(this.listeners, keyHash,
      union(this.getCallBacks(keyHash), [ cb ]));
  }
 
  /**
     * @param {string} key
     * @param {function} cb
     */
  removeCallBack(key /*: string */, cb /*: function */) {
    const { keyCode, modMask, eventType } = this.parseKey(key);
    const keyHash = this.genKeyHash(keyCode, modMask, eventType);
    remove(this.getCallBacks(keyHash), function(/** @type {function} */callback) {
      return callback === cb;
    });
  }
 
  /**
   * @param {KeyboardEvent} event
   */
  onKeyEvent(event /*: KeyboardEvent */) {
    Iif (!event.key) { return; }
    /** @type string*/
    const keyCode = get(KeyMap, event.key, event.key.toLowerCase());
    const input = isInput(event);
    // Create mod mask
    let mod = 0;
    Iif (event.altKey) { mod |= Mod.alt; }
    if (event.ctrlKey) { mod |= Mod.ctrl; }
    Iif (event.metaKey) { mod |= Mod.meta; }
    Iif (this.checkOnInputs && this.checkInput(input, keyCode, mod)) { return; }
    if (event.shiftKey) { mod |= Mod.shift; }
 
    const keyHash = this.genKeyHash(keyCode, mod, event.type);
 
    forEach(this.getCallBacks(keyHash), (/** @type {function} */ cb) => {
      // NB: It will stop the cb chain if cb returns false!!
      return cb(event);
    });
  }
 
  /**
   * @param {boolean} isInput
   * @param {string} key
   * @param {number} modMask
   * @returns {boolean}
   */
  checkInput(isInput /*: boolean */, key /*: string */, modMask /*: number */) {
    /* on inputs only fire events when it has a modifier,
         with an exception for escape */
    return isInput && !((modMask !== 0) || (key === "esc"));
  }
}
 
/**
 * @typedef {{
 *   local?: boolean,
 *   checkOnInputs?: boolean
 * }} KeyboardEventMixinOptions
 *
 * @typedef {{
 *   k: string,
 *   cb: function
 * }} KeyEventCB
 *
 * @typedef {{
 *    _keyboardCBs: Array<KeyEventCB>
 * }} Options
 */
 
const BaseKeyboardEventMixin = (/** @type {KeyboardEventMixinOptions} */options) => mixinMaker({
  /**
  Supported options:
  {
    local: boolean (def false) // It will instantiate a local Keyboard event handler
                               // and not a global one
    checkOnInputs: boolean (def true) // It will check if focus is on input
                                      // and prevent of executing the event callback
  }
   */
  /**
   * @returns {{ _keyHandler: KeyboardEventHandler|undefined }}
   */
  data() {
    return {
      /* eslint-disable vue/no-reserved-keys */
      _keyHandler: undefined
    };
  },
  computed: {
    /** @return {boolean} */
    showKeyHints() { return get(createStore(), [ "state", "ui", "showKeyHints" ], false); }
  },
  mounted() {
    const local = get(options, "local", false);
    const checkOnInputs = get(options, "checkOnInputs", true);
    if (local) {
      this._keyHandler = new KeyboardEventHandler(this.$el, checkOnInputs);
    }
    else {
      if (!_globalListener) {
        _globalListener = new KeyboardEventHandler(null, checkOnInputs);
      }
      this._keyHandler = _globalListener;
    }
    // '_keyboardCBs' is used internally. Cast with extended fields
    /** @type {Options} */(this.$options)._keyboardCBs = [];
  },
  beforeDestroy() {
    Iif (!this._keyHandler) {
      return;
    }
    // Remove all the CBs registered to this component
    forEach(/** @type {Options} */(this.$options)._keyboardCBs, (obj) => {
      // @ts-ignore it is initialized
      this._keyHandler.removeCallBack(obj.k, obj.cb);
    });
    this._keyHandler.releaseIfEmpty();
  },
  methods: {
    /**
     * @param {string | string[]} key
     * @param {function} cb
     */
    onKey(key, cb) {
      const keyboardCBs = /** @type {Options} */(this.$options)._keyboardCBs;
 
      Iif (isArray(key)) {
        for (const sKey of key) {
          // @ts-ignore it is initialized
          this._keyHandler.addCallBack(sKey, cb);
          // Save also locally
          keyboardCBs.push({ k: sKey, cb: cb });
        }
      }
      else {
        // @ts-ignore it is initialized
        this._keyHandler.addCallBack(key, cb);
        // Save also locally
        keyboardCBs.push({ k: key, cb: cb });
      }
 
    },
    /**
     * @param {string} key
     * @param {string?} [signal=null]
     */
    onKeyEmit(key, signal = null) {
      this.onKey(key, (/** @type {KeyboardEvent} */event) => this.$emit(signal || key, event));
    },
    /**
     * @param {string} key
     * @param {function?} cb
     */
    removeKey(key, cb) {
      const keyboardCBs = /** @type {Options} */(this.$options)._keyboardCBs;
 
      Eif (keyboardCBs.length > 0) {
        const removedCbs = remove(keyboardCBs, (obj) => {
          // if cb not provided it will remove all the callbacks for that key
          return obj.k === key &&
            (cb ? obj.cb === cb : true);
        });
        forEach(removedCbs, (obj) => {
          // @ts-ignore it is initialized
          this._keyHandler.removeCallBack(obj.k, obj.cb);
        });
      }
    },
    /**
     * @param {boolean} value
     */
    setCheckOnInput(value) {
      // @ts-ignore it is initialized
      this._keyHandler.setCheckOnInput(value);
    }
  }
});
 
export default BaseKeyboardEventMixin;