Skip to content

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

@Homeuh

Description

@Homeuh
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions