Class ConnectionHandler

Graph event handler that creates new connections. Uses TerminalMarker for finding and highlighting the source and target vertices and to create the edge instance. This handler is built-into Graph#connectionHandler and enabled using Graph#setConnectable.

Example:

new mxConnectionHandler(graph, (source, target, style)=>
{
edge = new mxCell('', new mxGeometry());
edge.setEdge(true);
edge.setStyle(style);
edge.geometry.relative = true;
return edge;
});

Here is an alternative solution that just sets a specific user object for new edges by overriding .

mxConnectionHandlerInsertEdge = insertEdge;
insertEdge = (parent, id, value, source, target, style)=>
{
value = 'Test';

return mxConnectionHandlerInsertEdge.apply(this, arguments);
};

Using images to trigger connections:

This handler uses mxTerminalMarker to find the source and target cell for the new connection and creates a new edge using . The new edge is created using which in turn uses or creates a new default edge.

The handler uses a "highlight-paradigm" for indicating if a cell is being used as a source or target terminal, as seen in other diagramming products. In order to allow both, moving and connecting cells at the same time, Constants#DEFAULT_HOTSPOT is used in the handler to determine the hotspot of a cell, that is, the region of the cell which is used to trigger a new connection. The constant is a value between 0 and 1 that specifies the amount of the width and height around the center to be used for the hotspot of a cell and its default value is 0.5. In addition, Constants#MIN_HOTSPOT_SIZE defines the minimum number of pixels for the width and height of the hotspot.

This solution, while standards compliant, may be somewhat confusing because there is no visual indicator for the hotspot and the highlight is seen to switch on and off while the mouse is being moved in and out. Furthermore, this paradigm does not allow to create different connections depending on the highlighted hotspot as there is only one hotspot per cell and it normally does not allow cells to be moved and connected at the same time as there is no clear indication of the connectable area of the cell.

To come across these issues, the handle has an additional hook with a default implementation that allows to create one icon to be used to trigger new connections. If this icon is specified, then new connections can only be created if the image is clicked while the cell is being highlighted. The hook may be overridden to create more than one ImageShape for creating new connections, but the default implementation supports one image and is used as follows:

In order to display the "connect image" whenever the mouse is over the cell, an DEFAULT_HOTSPOT of 1 should be used:

mxConstants.DEFAULT_HOTSPOT = 1;

In order to avoid confusion with the highlighting, the highlight color should not be used with a connect image:

mxConstants.HIGHLIGHT_COLOR = null;

To install the image, the connectImage field of the ConnectionHandler must be assigned a new Image instance:

connectImage = new ImageBox('images/green-dot.gif', 14, 14);

This will use the green-dot.gif with a width and height of 14 pixels as the image to trigger new connections. In createIcons the icon field of the handler will be set in order to remember the icon that has been clicked for creating the new connection. This field will be available under selectedIcon in the connect method, which may be overridden to take the icon that triggered the new connection into account. This is useful if more than one icon may be used to create a connection.

Group: Events

Event: mxEvent.START

Fires when a new connection is being created by the user. The state property contains the state of the source cell.

Event: mxEvent.CONNECT

Fires between begin- and endUpdate in . The cell property contains the inserted edge, the event and target properties contain the respective arguments that were passed to (where target corresponds to the dropTarget argument). Finally, the terminal property corresponds to the target argument in or the clone of the source terminal if is enabled.

Note that the target is the cell under the mouse where the mouse button was released. Depending on the logic in the handler, this doesn't necessarily have to be the target of the inserted edge. To print the source, target or any optional ports IDs that the edge is connected to, the following code can be used. To get more details about the actual connection point, Graph#getConnectionConstraint can be used. To resolve the port IDs, use <Transactions.getCell>.

graph.getPlugin('ConnectionHandler')?.addListener(mxEvent.CONNECT, (sender, evt) =>
{
let edge = evt.getProperty('cell');
let source = graph.getDataModel().getTerminal(edge, true);
let target = graph.getDataModel().getTerminal(edge, false);

let style = graph.getCellStyle(edge);
let sourcePortId = style[mxConstants.STYLE_SOURCE_PORT];
let targetPortId = style[mxConstants.STYLE_TARGET_PORT];

GlobalConfig.logger.show();
GlobalConfig.logger.debug('connect', edge, source.id, target.id, sourcePortId, targetPortId);
});

Event: mxEvent.RESET

Fires when the method is invoked.

Hierarchy (view full)

Implements

Constructors

  • Constructs an event handler that connects vertices using the specified factory method to create the new edges.

    Parameters

    • graph: Graph

      Reference to the enclosing Graph.

    • factoryMethod: null | FactoryMethod = null

      Optional function to create the edge. The function takes the source and target Cell as the first and second argument and an optional cell style from the preview as the third argument. It returns the Cell that represents the new edge.

    Returns ConnectionHandler

Properties

cell: null | Cell = null
changeHandler: ((sender: Listenable) => void)

Holds the change event listener for later removal.

connectIconOffset: Point = ...

Holds the offset for connect icons during connection preview. Default is mxPoint(0, Constants#TOOLTIP_VERTICAL_OFFSET). Note that placing the icon under the mouse pointer with an offset of (0,0) will affect hit detection.

connectImage: null | ImageBox = null

Image that is used to trigger the creation of a new connection. This is used in createIcons.

null
constraintHandler: ConstraintHandler

Holds the ConstraintHandler used for drawing and highlighting constraints.

createTarget: boolean = false

Specifies if should be called if no target was under the mouse for the new connection. Setting this to true means the connection will be drawn as valid if no target is under the mouse, and will be called before the connection is created between the source cell and the newly created vertex in , which can be overridden to create a new target. Default is false.

currentPoint: null | Point = null
currentState: null | CellState = null
cursor: null | string = null

Specifies the cursor to be used while the handler is active. Default is null.

drillHandler: ((sender: Listenable) => void)

Holds the drill event listener for later removal.

edgeState: null | CellState = null

Optional that represents the preview edge while the handler is active. This is created in .

enabled: boolean = false

Specifies if events are handled. Default is false.

error: null | string = null

Holds the current validation error while connections are being created.

escapeHandler: (() => void)
eventListeners: EventListenerObject[] = []

Holds the event names and associated listeners in an array. The array contains the event name followed by the respective listener for each registered listener.

eventsEnabled: boolean = true

Specifies if events can be fired. Default is true.

eventSource: null | EventTarget = null

Optional source for events. Default is null.

factoryMethod: null | FactoryMethod = null

Function that is used for creating new edges. The function takes the source and target as the first and second argument and returns a new that represents the edge. This is used in .

first: null | Point = null

Holds the Point where the mouseDown took place while the handler is active.

graph: Graph

Reference to the enclosing Graph.

icon: null | ImageShape = null
icons: ImageShape[] = []
iconState: null | CellState = null
ignoreMouseDown: boolean = false

Specifies if the connection handler should ignore the state of the mouse button when highlighting the source. Default is false, that is, the handler only highlights the source if no button is being pressed.

insertBeforeSource: boolean = false

Specifies if new edges should be inserted before the source vertex in the cell hierarchy. Default is false for backwards compatibility.

livePreview: boolean = false

Specifies if the actual shape of the edge state should be used for the preview. Default is false. (Ignored if no edge state is created in .)

marker: CellMarker

Holds the TerminalMarker used for finding source and target cells.

mouseDownCounter: number = 0

Counts the number of mouseDown events since the start. The initial mouse down event counts as 1.

moveIconBack: boolean = false

Specifies if icons should be moved to the back of the overlay pane. This can be set to true if the icons of the connection handler conflict with other handles, such as the vertex label move handle. Default is false.

moveIconFront: boolean = false

Specifies if icons should be displayed inside the graph container instead of the overlay pane. This is used for HTML labels on vertices which hide the connect icon. This has precedence over moveIconBack when set to true.

false

movePreviewAway: boolean = false

Switch to enable moving the preview away from the mousepointer. This is required in browsers where the preview cannot be made transparent to events and if the built-in hit detection on the HTML elements in the page should be used.

false
originalPoint: null | Point = null
outlineConnect: boolean = false

Specifies if connections to the outline of a highlighted target should be enabled. This will allow to place the connection point along the outline of the highlighted target.

false
previous: null | CellState = null
select: boolean = true

Specifies if new edges should be selected. Default is true.

selectedIcon: null | ImageShape = null
shape: null | Shape = null
sourceConstraint: null | ConnectionConstraint = null
targetConnectImage: boolean = false

Specifies if the connect icon should be centered on the target state while connections are being previewed. Default is false.

waypoints: Point[] = []
waypointsEnabled: boolean = false

Specifies if single clicks should add waypoints on the new edge. Default is false.

pluginId: string = 'ConnectionHandler'

Methods

  • Binds the specified function to the given event name. If no event name is given, then the listener is registered for all events.

    The parameters of the listener are the sender and an EventObject.

    Parameters

    • name: string
    • funct: Function

    Returns void

  • Connects the given source and target using a new edge. This implementation uses to create the edge.

    Parameters

    • source: null | Cell

      that represents the source terminal.

    • target: null | Cell

      that represents the target terminal.

    • evt: MouseEvent

      Mousedown event of the connect gesture.

    • dropTarget: null | Cell = null

      that represents the cell under the mouse when it was released.

    Returns void

  • Creates and returns a new edge using if one exists. If no factory method is defined, then a new default edge is returned. The source and target arguments are informal, the actual connection is setup later by the caller of this function.

    Parameters

    • value: any

      Value to be used for creating the edge.

    • source: null | Cell

      that represents the source terminal.

    • target: null | Cell

      that represents the target terminal.

    • style: CellStyle = {}

      Optional style from the preview edge.

    Returns Cell

  • Hook to return an which may be used during the preview. This implementation returns null.

    Use the following code to create a preview for an existing edge style:

    graph.getPlugin('ConnectionHandler').createEdgeState(me)
    {
    var edge = graph.createEdge(null, null, null, null, null, 'edgeStyle=elbowEdgeStyle');

    return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
    };

    Parameters

    Returns null | CellState

  • Hook method for creating new vertices on the fly if no target was under the mouse. This is only called if is true and returns null.

    Parameters

    • evt: MouseEvent

      Mousedown event of the connect gesture.

    • source: Cell

      that represents the source terminal.

    Returns Cell

  • Dispatches the given event to the listeners which are registered for the event. The sender argument is optional. The current execution scope ("this") is used for the listener invocation (see Utils#bind).

    Example:

    fireEvent(new mxEventObject("eventName", key1, val1, .., keyN, valN))
    

    Parameters

    • evt: EventObject

      EventObject that represents the event.

    • sender: null | EventTarget = null

      Optional sender to be passed to the listener. Default value is the return value of .

    Returns void

  • Returns the tolerance for aligning new targets to sources. This returns the grid size / 2.

    Parameters

    • Optionalevt: MouseEvent

    Returns number

  • Returns the color used to draw the preview edge. This returns green if there is no edge validation error and red otherwise.

    Parameters

    • valid: boolean

      Boolean indicating if the color for a valid edge should be returned.

    Returns "#00FF00" | "#FF0000"

  • Returns the width used to draw the preview edge. This returns 3 if there is no edge validation error and 1 otherwise.

    Parameters

    • valid: boolean

      Boolean indicating if the width for a valid edge should be returned.

    Returns number

  • Hook to update the icon position(s) based on a mouseOver event. This is an empty implementation.

    Parameters

    • state: CellState

      that represents the target cell state.

    • next: Point

      Point that represents the next point along the previewed edge.

    • me: InternalMouseEvent

      MouseEvent that represents the mouse move.

    Returns null | Point

  • Returns true if the given cell is connectable. This is a hook to disable floating connections. This implementation returns true.

    Parameters

    Returns boolean

  • Returns true if the source terminal has been clicked and a new connection is currently being previewed.

    Returns boolean

  • Returns true if a tap on the given source state should immediately start connecting. This implementation returns true if the state is not movable in the graph.

    Parameters

    Returns boolean

  • Returns for non-loops and false for loops.

    Parameters

    • edge: Cell

      that represents the edge to be inserted.

    • source: null | Cell

      that represents the source terminal.

    • target: null | Cell

      that represents the target terminal.

    • evt: MouseEvent

      Mousedown event of the connect gesture.

    • dropTarget: null | Cell

      that represents the cell under the mouse when it was released.

    Returns boolean

  • Returns true if the state has a HTML label in the graph's container, otherwise it returns oveIconFront.

    Parameters

    • state: CellState

      whose connect icons should be returned.

    Returns boolean

  • Returns true if the given mouse down event should start this handler. The This implementation returns true if the event does not force marquee selection, and the currentConstraint and currentFocus of the are not null, or and are not null and is null or and are not null.

    Parameters

    Returns boolean

  • Returns true if the given mouse up event should stop this handler. The connection will be created if is null. Note that this is only called if is true. This implemtation returns true if there is a cell state in the given event.

    Parameters

    Returns boolean

  • Selects the given edge after adding a new connection. The target argument contains the target vertex if one has been inserted.

    Parameters

    Returns void

  • Enables or disables event handling. This implementation updates .

    Parameters

    • enabled: boolean

      Boolean that specifies the new enabled state.

    Returns void

  • Returns the color used to draw the preview edge. This returns green if there is no edge validation error and red otherwise.

    Parameters

    • valid: boolean

      Boolean indicating if the color for a valid edge should be returned.

    Returns void

  • Returns the error message or an empty string if the connection for the given source target pair is not valid. Otherwise it returns null. This implementation uses Graph#getEdgeValidationError.

    Parameters

    • source: Cell

      that represents the source terminal.

    • target: Cell

      that represents the target terminal.

    Returns null | string