projectstorm / react-diagrams

a super simple, no-nonsense diagramming library written in react that just works
https://projectstorm.cloud/react-diagrams
MIT License
8.51k stars 1.17k forks source link

Is there a way to drag node on link and auto-connect to that link? #836

Open narendra-sabhani opened 3 years ago

narendra-sabhani commented 3 years ago

First of all thanks for this superb project!

I am working on a use case, let's say I have two nodes Node1 and Node2, and both the node are connected with the link (link1). Now I also have another node named Node3, which is not connected to any link.

When dragging Node3 and dropping on link1 (that connects Node1 (In port) and Node2 (Out port), It should be placed between Node1 and Node2 and connected to link1.

How can I achieve this use case. Is there a way to make it possible?

renato-bohler commented 3 years ago

I think this is possible.

It would probably involve creating a custom DragDiagramItemsState to detect when a node is dragged. You would then have to somehow identify if the node is being dropped near a link, and in this case, you would need to edit this link (connect it to Node3 instead of Node2) and then create another link and connect it from Node3 to Node2.

You can probably identify if the node is being dropped near a link by using something like:

const droppedNearTheseLinks = this.engine.getMouseElement(event.event).filter(item => item instanceof LinkModel)

You could also add more logic to check if the link has a source and a target:

const droppedNearThisConnectedLinks = this.engine.getMouseElement(event.event).filter(item => {
  if (!item instanceof LinkModel) return false;
  if (!this.getSourcePort()) return false;
  if (!item.getTargetPort()) return false;
  return true;
})

But I suspect that this would only work if the user drops the node with the mouse right on top of the link, which would not be a great user experience, since links are usually so thin.