swimlane / ngx-graph

Graph visualization library for angular

Home Page:https://swimlane.github.io/ngx-graph

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Centering with custom layout doesn't work as intended

PyHahiro opened this issue · comments

Describe the bug
Hi, the bug is the following, when I use the programmaticaly implemented Center$ subject in order to center, it doesn't center the intended way

To Reproduce
I Implemented a customDagreNodesOnly custom Layout template available in the repo and, using custom nodes size, I implemented a function to open/close nodes.
When the function is called, I want to center my graph around the selected node, until I added this portion of code before updating my edge

// INSIDE customDagreNodesOnly.ts 

const rootNode = graph.nodes.find(n => n.id === "0");
if (!rootNode) {
  return;
}

const canvasWidth = document.getElementById('graph').offsetWidth;
const canvasHeight = document.getElementById('graph').offsetHeight

const offsetX = canvasWidth / 2 - ((rootNode.position.x + rootNode.dimension.width) / 2);
const offsetY = canvasHeight / 2 - ((rootNode.position.y + rootNode.dimension.height) / 2);


for (const node of graph.nodes) {
  node.position.x += offsetX;
  node.position.y += offsetY;

I believe this is working because every nodes has the same position and only transition so changing the position is the issue, but using translate also doesn't work
the Center$ subject worked as intended, but now it does not anymore, and I believe this has to do with how is the calculation made after these changes

What I have tried

const rootNode = graph.nodes.find(n => n.id === "0");
if (!rootNode) {
  return;
}

const canvasWidth = document.getElementById('graph').offsetWidth;
const canvasHeight = document.getElementById('graph').offsetHeight

let [_, transformX, transformY] = rootNode.transform?.match(/translate\(([0-9]+),\s*([0-9]+)\)/) ?? ["",0,0]

const offsetX = canvasWidth / 2 - ((rootNode.position.x + rootNode.dimension.width + +transformX) / 2);
const offsetY = canvasHeight / 2 - ((rootNode.position.y + rootNode.dimension.height + +transformY) / 2);

for (const node of graph.nodes) {
  node.transform = `translate(${offsetX},${offsetY})`;
    }

moving +transformX/+transformY around my calcul hasn't changed anything

Expected behavior
I want to my center function to center the whole graph while keeping the intended code above that works

Screenshots
graph not being centered, offset is wrong, but deploying/hidding then centering on clicked node is working
image

ngx-graph version
"^7.2.0"