MoveCanvas.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import {
  2. set as cursorSet,
  3. unset as cursorUnset
  4. } from '../../util/Cursor';
  5. import {
  6. install as installClickTrap
  7. } from '../../util/ClickTrap';
  8. import {
  9. delta as deltaPos
  10. } from '../../util/PositionUtil';
  11. import {
  12. event as domEvent,
  13. closest as domClosest
  14. } from 'min-dom';
  15. import {
  16. toPoint
  17. } from '../../util/Event';
  18. var THRESHOLD = 15;
  19. /**
  20. * Move the canvas via mouse.
  21. *
  22. * @param {EventBus} eventBus
  23. * @param {Canvas} canvas
  24. */
  25. export default function MoveCanvas(eventBus, canvas) {
  26. var context;
  27. // listen for move on element mouse down;
  28. // allow others to hook into the event before us though
  29. // (dragging / element moving will do this)
  30. eventBus.on('element.mousedown', 500, function(e) {
  31. return handleStart(e.originalEvent);
  32. });
  33. function handleMove(event) {
  34. var start = context.start,
  35. button = context.button,
  36. position = toPoint(event),
  37. delta = deltaPos(position, start);
  38. if (!context.dragging && length(delta) > THRESHOLD) {
  39. context.dragging = true;
  40. if (button === 0) {
  41. installClickTrap(eventBus);
  42. }
  43. cursorSet('grab');
  44. }
  45. if (context.dragging) {
  46. var lastPosition = context.last || context.start;
  47. delta = deltaPos(position, lastPosition);
  48. canvas.scroll({
  49. dx: delta.x,
  50. dy: delta.y
  51. });
  52. context.last = position;
  53. }
  54. // prevent select
  55. event.preventDefault();
  56. }
  57. function handleEnd(event) {
  58. domEvent.unbind(document, 'mousemove', handleMove);
  59. domEvent.unbind(document, 'mouseup', handleEnd);
  60. context = null;
  61. cursorUnset();
  62. }
  63. function handleStart(event) {
  64. // event is already handled by '.djs-draggable'
  65. if (domClosest(event.target, '.djs-draggable')) {
  66. return;
  67. }
  68. var button = event.button;
  69. // reject right mouse button or modifier key
  70. if (button >= 2 || event.ctrlKey || event.shiftKey || event.altKey) {
  71. return;
  72. }
  73. context = {
  74. button: button,
  75. start: toPoint(event)
  76. };
  77. domEvent.bind(document, 'mousemove', handleMove);
  78. domEvent.bind(document, 'mouseup', handleEnd);
  79. // we've handled the event
  80. return true;
  81. }
  82. this.isActive = function() {
  83. return !!context;
  84. };
  85. }
  86. MoveCanvas.$inject = [
  87. 'eventBus',
  88. 'canvas'
  89. ];
  90. // helpers ///////
  91. function length(point) {
  92. return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
  93. }