Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When there are multiple nodes, sometimes the parent node is not in the center position of the child node #471

Open
Homeuh opened this issue Feb 26, 2025 · 1 comment

Comments

@Homeuh
Copy link

Homeuh commented Feb 26, 2025

import Dagre from '@dagrejs/dagre';
import { Position } from '@xyflow/react';

export const useLayout = (
  nodes,
  edges,
  options: {
    direction: 'LR' | 'TB';
    toggleNodeId: string | null;
  },
) => {
  const isHorizontal = options.direction === 'LR';
  const dagreGraph = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
  dagreGraph.setGraph({
    rankdir: options.direction,
    nodesep: 10,
    ranksep: 55,
  });

  edges.forEach(edge => dagreGraph.setEdge(edge.source, edge.target, { width: 15 }));
  nodes.forEach(node =>
    dagreGraph.setNode(node.id, {
      ...node,
      width: node.measured?.width ?? 0,
      height: node.measured?.height ?? 0,
    }),
  );

  Dagre.layout(dagreGraph);

  let offsetY = 0;

  return {
    nodes: nodes.map(node => {
      const position = dagreGraph.node(node.id);
      const { x, y } = position;
      if (node.id === options.toggleNodeId) {
        offsetY = y - node.position.y;
      }
      return {
        ...node,
        targetPosition: isHorizontal ? Position.Left : Position.Top,
        sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
        position: { x, y },
      };
    }),
    edges,
    offsetY: offsetY,
  };
};

As you can see, when there are many nodes, the x and y coordinates calculated by the dark calculation method may deviate. If setGraph ({align:'UL '}) is set, this problem will not occur, but the parent node is not in the center position relative to all direct child nodes. What enhancement solutions are there, such as adding align attribute values like center? I have tried adjusting the coordinates to be in the center position based on existing algorithms, but there may be node overlap issues. Wishing to receive a response
Image

@kitiho
Copy link

kitiho commented Mar 7, 2025

same question

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants