All files / src/utils makeNodeDraggable.ts

4.88% Statements 2/41
0% Branches 0/14
0% Functions 0/5
5% Lines 2/40

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 731x   1x                                                                                                                                            
import { eventDispatcher } from "../utils";
 
export const makeNodeDraggable = (el: SVGGraphicsElement): void => {
  let lastX = 0;
  let lastY = 0;
 
  const move = (target: SVGGraphicsElement, dx: number, dy: number): void => {
    if (!target) {
      return;
    }
 
    if (target.tagName === "g") {
      for (let i = 0; i < target.childElementCount; i++) {
        move(target.childNodes[i] as SVGGraphicsElement, dx, dy);
      }
    } else if (target.tagName === "circle") {
      const x = parseFloat(target.getAttributeNS(null, "cx") || "0");
 
      target.setAttributeNS(null, "cx", `${x + dx}`);
 
      const y = parseFloat(target.getAttributeNS(null, "cy") || "0");
 
      target.setAttributeNS(null, "cy", `${y + dy}`);
    } else {
      const x = parseFloat(target.getAttributeNS(null, "x") || "0");
 
      target.setAttributeNS(null, "x", `${x + dx}`);
 
      const y = parseFloat(target.getAttributeNS(null, "y") || "0");
 
      target.setAttributeNS(null, "y", `${y + dy}`);
    }
  };
 
  const drag = (evt: MouseEvent): void => {
    const dx = evt.clientX - lastX;
    const dy = evt.clientY - lastY;
 
    lastX = evt.clientX;
    lastY = evt.clientY;
 
    move(el, dx, dy);
 
    const bbox = el.getBBox();
 
    eventDispatcher.trigger("node.dragmove", {
      nodeId: el.dataset.nodeId,
      pos: { x: bbox.x, y: bbox.y }
    });
  };
 
  const endDrag = (evt: MouseEvent) => {
    evt.preventDefault();
 
    window.removeEventListener("mousemove", drag);
    window.removeEventListener("mouseup", endDrag);
  };
 
  const startDrag = (evt: MouseEvent): void => {
    eventDispatcher.trigger("node.dragstart");
 
    evt.preventDefault();
    evt.stopPropagation();
 
    lastX = evt.clientX;
    lastY = evt.clientY;
 
    window.addEventListener("mousemove", drag);
    window.addEventListener("mouseup", endDrag);
  };
  el.addEventListener("mousedown", startDrag);
};