let draggingBox = null; let draggingCamera = false; let lastMousePos = {x: 0, y: 0}; class Mouse { static position = {x: 0, y: 0}; static lastPosition = {x: 0, y: 0}; static updatePosition(x, y) { this.lastPosition = this.position; this.position = {x: x, y: y}; } static getDelta() { return {x : this.position.x - this.lastPosition.x, y : this.position.y - this.lastPosition.y}; } } document.addEventListener("mousedown", (e) => { Mouse.updatePosition(e.clientX, e.clientY); if (e.button == 0) { if (e.target.classList.contains("boxDeleteButton")) return; for (let box of Box.instances) { let topBarRect = box.element.getElementsByClassName("boxTopBar")[0].getBoundingClientRect(); box.element.classList.remove("dragging"); if (isPointInRect(Mouse.position.x, Mouse.position.y, topBarRect.x, topBarRect.y, topBarRect.width, topBarRect.height)) { draggingBox = box; box.element.classList.add("dragging"); e.preventDefault(); break; } } if (e.target == document.getElementById("playground")) { ConnectionController.unselect(); } } if (e.button == 1 || e.button == 2) { draggingCamera = true; document.body.style.cursor = "grabbing"; e.preventDefault(); } }); document.addEventListener("contextmenu", (e) => { e.preventDefault(); }); document.addEventListener("mouseup", (e) => { if (e.button == 0 && draggingBox != null) { draggingBox.element.classList.remove("dragging"); draggingBox = null; } if (e.button == 1 || e.button == 2) { draggingCamera = false; document.body.style.cursor = ""; } }); document.addEventListener("mousemove", (e) => { Mouse.updatePosition(e.clientX, e.clientY); let delta = Mouse.getDelta(); delta.x *= 1/Camera.zoom; delta.y *= 1/Camera.zoom; if (draggingBox != null) { draggingBox.x += delta.x; draggingBox.y += delta.y; draggingBox.updatePosition(); e.preventDefault(); } if (draggingCamera) { Camera.movePosition(-delta.x, -delta.y); e.preventDefault(); } }); document.addEventListener("wheel", (e) => { let lastZoom = Camera.zoom; Camera.zoom = Math.min(1, Math.max(0.25, Camera.zoom - e.deltaY / 2000)); document.body.style.setProperty("--zoom", Camera.zoom); Camera.movePosition( (Mouse.position.x / lastZoom - Mouse.position.x / Camera.zoom), (Mouse.position.y / lastZoom - Mouse.position.y / Camera.zoom), ); }); function isPointInRect(px, py, rx, ry, rw, rh) { return px >= rx && px <= rx + rw && py >= ry && py <= ry + rh; }