javascriptcytoscape.js

Cytoscape JS - Create a node by drag and drop from outside palette


Is there a way to create new nodes by drag & drop something from outside the graph, such as a palette or whatever. I think there is no such extension, the only one I've found is this one : https://github.com/ayushkr19/cytoscape.js-nodeadd which is 9 years old and use jQuery.

If there is no extension, how can I approach this using event listeners maybe ?

Thanks.


Solution

  • Ok I've found a way, here's my solution ;)

    ref

    const graphRef = useRef<Core>()
    

    button for UI

    <div draggable="true">
        <button>Add toto node</button>
    </div>
    

    Cytoscape wrapper

    <div onDrop={(e) => handleCreateNode(e)} onDragOver={(e) => e.preventDefault()}>
      <CytoscapeComponent
        cy={(cy) => (graphRef.current = cy)}
      />
    </div>
    

    And the key, the function to create a node at the right place

    const handleCreateNode = (e: DragEvent<HTMLDivElement>) => {
      if (!graphRef.current) return;
    
      e.preventDefault();
    
      const pan = graphRef.current.pan();
      const zoom = graphRef.current.zoom();
      const x = e.nativeEvent.offsetX
      const y = e.nativeEvent.offsetY
    
      graphRef.current.add({
        data: { id: String(Math.random()), label: addType },
        position: {
          x: (x - pan.x) / zoom,
          y: (y - pan.y) / zoom,
        },
      });
    };
    

    This is a React working version.