all files / Github/diagram-js/lib/navigation/keyboard-move/ KeyboardMove.js

16.22% Statements 6/37
10% Branches 2/20
33.33% Functions 1/3
16.22% Lines 6/37
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                                              58×   58×   58×                                                                                                             58×                                                                        
import { assign } from 'min-dash';
 
 
var DEFAULT_CONFIG = {
  moveSpeed: 50,
  moveSpeedAccelerated: 200
};
 
 
/**
 * A feature that allows users to move the canvas using the keyboard.
 *
 * @param {Object} config
 * @param {Number} [config.moveSpeed=50]
 * @param {Number} [config.moveSpeedAccelerated=200]
 * @param {Keyboard} keyboard
 * @param {Canvas} canvas
 */
export default function KeyboardMove(
    config,
    keyboard,
    canvas
) {
 
  var self = this;
 
  this._config = assign({}, DEFAULT_CONFIG, config || {});
 
  keyboard.addListener(arrowsListener);
 
 
  function arrowsListener(context) {
 
    var event = context.keyEvent,
        config = self._config;
 
    if (!keyboard.isCmd(event)) {
      return;
    }
 
    if (keyboard.isKey([
      'ArrowLeft', 'Left',
      'ArrowUp', 'Up',
      'ArrowDown', 'Down',
      'ArrowRight', 'Right'
    ], event)) {
 
      var speed = (
        keyboard.isShift(event) ?
          config.moveSpeedAccelerated :
          config.moveSpeed
      );
 
      var direction;
 
      switch (event.key) {
      case 'ArrowLeft':
      case 'Left':
        direction = 'left';
        break;
      case 'ArrowUp':
      case 'Up':
        direction = 'up';
        break;
      case 'ArrowRight':
      case 'Right':
        direction = 'right';
        break;
      case 'ArrowDown':
      case 'Down':
        direction = 'down';
        break;
      }
 
      self.moveCanvas({
        speed: speed,
        direction: direction
      });
 
      return true;
    }
  }
 
  this.moveCanvas = function(opts) {
 
    var dx = 0,
        dy = 0,
        speed = opts.speed;
 
    var actualSpeed = speed / Math.min(Math.sqrt(canvas.viewbox().scale), 1);
 
    switch (opts.direction) {
    case 'left': // Left
      dx = actualSpeed;
      break;
    case 'up': // Up
      dy = actualSpeed;
      break;
    case 'right': // Right
      dx = -actualSpeed;
      break;
    case 'down': // Down
      dy = -actualSpeed;
      break;
    }
 
    canvas.scroll({
      dx: dx,
      dy: dy
    });
  };
 
}
 
 
KeyboardMove.$inject = [
  'config.keyboardMove',
  'keyboard',
  'canvas'
];