I was experimenting with sigma.js with the help of AI,and I had a need to click a node and make it show me a info box of information. I added the info box and two nodes so I could test, but I can’t seem to make the info box stay put right below the node, it appears on the top left corner when I click, and nothing I did changed that. Here is the code:
import Graph from "graphology";
import Sigma from "sigma";
// Create a new graph instance
const graph = new Graph();
// Add nodes and an edge to the graph
graph.addNode("1", { label: "Node 1", x: 0, y: 0, size: 10, color: "blue" });
graph.addNode("2", { label: "Node 2", x: 1, y: 1, size: 20, color: "red" });
graph.addEdge("1", "2", { size: 5, color: "purple" });
// Get the container element from the HTML
const container = document.getElementById("container");
if (!container) {
console.error("Container element not found. Make sure #container exists in the HTML.");
} else {
// Initialize Sigma renderer
const renderer = new Sigma(graph, container);
// Create a div to act as the info box
const infoBox = document.createElement("div");
infoBox.style.position = "absolute";
infoBox.style.border = "1px solid #ccc";
infoBox.style.backgroundColor = "#fff";
infoBox.style.padding = "10px";
infoBox.style.zIndex = "1000";
infoBox.style.display = "none"; // Initially hidden
document.body.appendChild(infoBox);
// Add event listener for node clicks
renderer.on("clickNode", (event) => {
const nodeId = event.node;
const nodeAttributes = graph.getNodeAttributes(nodeId);
// Populate the info box with node details
infoBox.innerHTML = `
<h3>Node Details</h3>
<strong>${nodeAttributes.label}</strong>
<p>This node has a size of ${nodeAttributes.size} and is colored ${nodeAttributes.color}.</p>
<p>Feel free to explore the graph!</p>
`;
// Get the screen coordinates of the node
const nodeDisplayData = renderer.getNodeDisplayData(nodeId);
if (nodeDisplayData) {
// Offset the coordinates to position the info box correctly in the viewport
const containerRect = container.getBoundingClientRect();
const adjustedX = containerRect.left + nodeDisplayData.x - infoBox.offsetWidth / 2;
const adjustedY = containerRect.top + nodeDisplayData.y - infoBox.offsetHeight - 10; // Position above the node
// Set the info box position
infoBox.style.left = `${adjustedX}px`;
infoBox.style.top = `${adjustedY}px`;
infoBox.style.display = "block";
// Log the final coordinates of the text box to the console
console.log(`InfoBox Coordinates: X = ${adjustedX}, Y = ${adjustedY}`);
}
});
// Add event listener to hide the info box when clicking on the stage
renderer.on("clickStage", () => {
infoBox.style.display = "none";
});
}
I tried to change the way it calculated the screen coordinates, but no matter what I changed, the info box continues to appear on the top left corner of my screen.