HTMLGraph logo HTMLGraph

Connectable Ports

In some use cases, allowing users to modify graph topology is crucial. Essential feature for this functionality is providing the ability to add new connections to the graph.

To enable ports, connectable via dragging, call the enableUserConnectablePorts method on CanvasBuilder instance:

    
const element = document.getElementById('canvas');

const canvas = new CanvasBuilder(element)
  .enableUserConnectablePorts()
  .build();

  
Connectable ports

It is crusial for port to have “grabable” area big enough to actually be grabbed by user, as shown in the example above.

enableUserConnectablePorts method accepts optional configuration.

Configuration Parameters

NameTypeDescriptionRequiredDefault
connectionTypeResolver(portId) => “direct” | “reverse” | nullResolves connection type, when edge creation has been initiated. null means that connection is disallowedno() => “direct”
connectionPreprocessor(request: AddEdgeRequest) => AddEdgeRequest | nullApplies modification to the edge about to be created. null means that connection is disallowed.no(request) => request
mouseDownEventVerifier(event) => booleanFunction to verify if mouse event should initiate connection creation processno(event) => event.button === 0
mouseUpEventVerifier(event) => booleanFunction to verify if mouse event should create connectionno(event) => event.button === 0
dragPortDirectionnumber | undefinedDirection of dragging portnoundefined
eventsEventsConfigHandlers for available eventsno{}

Events Configuration

NameTypeDescriptionRequiredDefault
onAfterEdgeCreated(edgeId: any) => voidFunction to call after a new edge has been addedno() => void
onEdgeCreationInterrupted(staticPortId: any, isDirect: boolean) => voidFunction to call when edge creation is interrupted in the processno() => void
onEdgeCreationPrevented(addEdgeRequest: AddEdgeRequest) => voidFunction to call when an attepmt to create edge is preventedno() => void

There is a good example of reasonable connection type resolver, which resolves direct connection when “out” port gets grabbed, and reverses connection when “in” port gets grabbed:

    
const connectionTypeResolver = (portId) => {
  return portId.endsWith("-out") ? "direct" : "reverse";
};

  

As for connection preprocessor, you can start with the one, which forbids duplicated connections:

    
const connectionPreprocessor = (request) => {
  const existingEdge = canvas.graph.getAllEdgeIds().find((edgeId) => {
    const edge = canvas.graph.getEdge(edgeId);

    return edge.from === request.from && edge.to === request.to;
  });

  return existingEdge === undefined ? request : null;
};