Maya Jane
Maya Jane

Reputation: 21

How to place node to mouse position after drag and drop from outside editor with Rete.js

I am currently working with rete.js. I am kinda new to it. I have an application with the editor on one side and then a list of button on the other side. The list of button is not part of the editor but when i drag and drop elements from it, it triggers a function I have made that creates a node in the editor. My issue is with the positionning of the node after the drop. The editor's (0,0) coordinates are in the middle of the editor plus the issue of being able to zoom in and out that expends the amount of coordinates. And what I have access to in order to position nodes are the coordinates from my mouse in the overall screen when dropping.

I have tried to use

const { x, y, k } = area.area.transform

But I am not really sure on how to use it to translate my coordinates. So far I have been twiking coordinates here and there to try and find a correlation but my brain is not braining.

Thanks in advance for any help

Upvotes: 0

Views: 204

Answers (1)

vinod bavisetti
vinod bavisetti

Reputation: 1

I faced the same problem. and I did the following.

function dragAndDropToAddNode(
  areaPlugin: AreaPlugin<Schemes, AreaExtra>,
  editor: NodeEditor<Schemes>
){
  const containerEle = areaPlugin.container;
  containerEle.addEventListener('drop',async (e) => {
    const nodeName = e.dataTransfer.getData('node');
    let newNode: Schemes['Node'];
    if(nodeName == 'message'){
      newNode = new Message('vinod');
    } else{
      return;
    }
    await editor.addNode(newNode);
    // translating the node to the drop location.----------------s
    const {x, y, k} = areaPlugin.area.transform;
    const box = containerEle.getBoundingClientRect();
    await areaPlugin.translate(newNode.id, {
      x: (e.clientX - box.left - x)/k - newNode.width/2,
      y: (e.clientY - box.top - y)/k,
    });
    //   ------------------------------------------------------------
  })
  containerEle.addEventListener('dragover',(e) => {
    e.preventDefault();
    e.dataTransfer!.dropEffect = 'copy';
  })
}

and ofcourse you need to add a draggable element in the element to drop.

Upvotes: 0

Related Questions