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();
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
Name | Type | Description | Required | Default |
---|---|---|---|---|
connectionTypeResolver | (portId) => “direct” | “reverse” | null | Resolves connection type, when edge creation has been initiated. null means that connection is disallowed | no | () => “direct” |
connectionPreprocessor | (request: AddEdgeRequest) => AddEdgeRequest | null | Applies modification to the edge about to be created. null means that connection is disallowed. | no | (request) => request |
mouseDownEventVerifier | (event) => boolean | Function to verify if mouse event should initiate connection creation process | no | (event) => event.button === 0 |
mouseUpEventVerifier | (event) => boolean | Function to verify if mouse event should create connection | no | (event) => event.button === 0 |
dragPortDirection | number | undefined | Direction of dragging port | no | undefined |
events | EventsConfig | Handlers for available events | no | {} |
Events Configuration
Name | Type | Description | Required | Default |
---|---|---|---|---|
onAfterEdgeCreated | (edgeId: any) => void | Function to call after a new edge has been added | no | () => void |
onEdgeCreationInterrupted | (staticPortId: any, isDirect: boolean) => void | Function to call when edge creation is interrupted in the process | no | () => void |
onEdgeCreationPrevented | (addEdgeRequest: AddEdgeRequest) => void | Function to call when an attepmt to create edge is prevented | no | () => 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; };