Within my sigma.js web application, I am dealing with two main types of events. The first type involves handling click events to open a node's URL, while the second type involves managing drag events to allow nodes to be moved around in the space.
const renderer = new Sigma(graph, container);
renderer.on("clickNode", ({ node }) => {
if (!graph.getNodeAttribute(node, "hidden")) {
window.open(graph.getNodeAttribute(node, "pageURL"), "_blank");
}
});
The code snippet above is responsible for triggering the click event. When we click on nodes, it opens the corresponding page URL:
let draggedNode: string | null = null;
let isDragging = false;
/* On mouse down on a node
- we enable the drag mode
- save the dragged node in the state
- highlight the node
- disable the camera to prevent updates */
renderer.on("downNode", (e) => {
isDragging = true;
draggedNode = e.node;
graph.setNodeAttribute(draggedNode, "highlighted", true);
});
// On mouse move, change the position of the draggedNode if drag mode is enabled
renderer.getMouseCaptor().on("mousemovebody", (e) => {
if (!isDragging || !draggedNode) return;
// Get new position of node
const pos = renderer.viewportToGraph(e);
graph.setNodeAttribute(draggedNode, "x", pos.x);
graph.setNodeAttribute(draggedNode, "y", pos.y);
// Prevent sigma from moving the camera:
e.preventSigmaDefault();
e.original.preventDefault();
e.original.stopPropagation();
});
// Disable autoscale at the initial interaction
renderer.getMouseCaptor().on("mousedown", () => {
if (!renderer.getCustomBBox()) renderer.setCustomBBox(renderer.getBBox());
});
// Reset autoscaling and dragging mode on mouse up
renderer.getMouseCaptor().on("mouseup", () => {
if (draggedNode) {
graph.removeNodeAttribute(draggedNode, "highlighted");
}
isDragging = false;
draggedNode = null;
});
}
A specific issue arises when dragging nodes and releasing the mouse button triggers the click event, causing the pageURL
to open unintentionally. This behavior should only occur when clicking on a node, not during dragging.
Is there a way to prevent the click event from being triggered while dragging? Despite attempting methods from Stack Overflow, none have been successful. You can experiment with the problem yourself by visiting this CodeSandbox link.