antv/g6 interaction and events and custom Behavior

Listening and binding events

In G6, direct stand-alone events and monitoring timing methods are provided. You can monitor the canvas, nodes, edges, and the timing of each function being called:

1. Binding events

To bind an event, you first need to obtain a graph instance (Graph instance), and then use the on method to bind the event.
Divided into three categories: global events, canvas events, node/edge/combo events;

graph.on(eventName, handler);
// Take click event as an example
// global
graph.on('click', ev=>{<!-- -->});
//canvas event
graph.on('canvas:click', ev=>{<!-- -->});
//Point edge and combo events
graph.on('node/edge/combo:click',ev=>{<!-- -->});
  • eventName is the event name, which can be a G6 built-in event or a custom event.
  • handler is an event handler, a function used to handle the logic when an event occurs.

2. Built-in events

G6 provides some built-in events for handling various interactions with charts. For example, some common built-in events:

  • 'node:click': Triggered when the node is clicked.
  • 'node:mouseenter': Triggered when the mouse enters a node.
  • 'node:mouseleave': Triggered when the mouse leaves the node.
  • 'edge:click': Triggered when the edge is clicked.
  • 'edge:mouseenter': Triggered when the mouse enters the edge.
  • 'edge:mouseleave': Triggered when the mouse leaves the edge.
  • 'canvas:click': Triggered when the canvas is clicked.
  • 'canvas:mouseenter': Triggered when the mouse enters the canvas.
  • 'canvas:mouseleave': Triggered when the mouse leaves the canvas.
    Here are just a few of them

3. Event handler

An event handler is a function that defines the logic when an event is triggered. It usually takes two parameters:

  • e: Event object, containing event details.
  • item: The graph element associated with the event, such as a node or edge.

Here is an example showing how to bind a 'node:click' event and corresponding handler:

graph.on('node:click', (e, item) => {<!-- -->
  //Print the ID of the node in the console
  console.log('Node Clicked:', item.getModel().id);
});

4. Unbinding event

To unbind an event, you can use the off method. The general syntax for unbinding events is as follows:

graph.off(eventName, handler);
  • eventName is the name of the event to be unbound.
  • handler is the event handler to be unbound.

5. Timing monitoring

Timing events refer to timings such as rendering, viewport transformation, element addition, deletion and modification, data transformation, etc.
For example, the following example binds the monitoring of the rendering completion time. Events such as afterrender and afterlayout must be bound before graph.render() or graph.read() in order to monitor the related events after the first rendering and layout completion.

graph.on('afterrender', (ev) => {<!-- -->
  // ... do sth
});

Built-in behaviorBehavior

In AntV G6, Behavior is a behavior that is used to define interaction and interactive behavior on the chart. Behavior allows you to customize mouse interaction, dragging, zooming, selection and other operations to change the status and display of the chart. G6 currently provides 14 built-in Behaviors.

G6 provides some built-in Behaviors that can be configured when creating a chart instance, for example:
AntV G6 provides some built-in behaviors (Behaviors) for handling user interactions and operations in charts. Here are some common behaviors built into G6 and what they do:

  1. drag-canvas: Allows users to drag the entire canvas.
  2. zoom-canvas: Allows the user to zoom the canvas.
  3. drag-node: Allows users to drag nodes.
  4. drag-combo: Allows users to drag groups (Combo).
  5. collapse-expand-combo: Allows users to collapse/expand groups.
  6. scroll-canvas: Use the scroll wheel to scroll the canvas, supported since v4.2.6.
  7. click-select: Click to select a node or edge.
  8. lasso-select: Use the Lasso tool to select nodes or edges.
  9. brush-select: Use the Brush tool to select nodes or edges.
  10. tooltip-edge: The usage is basically the same as tooltip, but it is triggered when it moves to the edge.
  11. tooltip: Node text tip.
  12. activate-relations: When a node is selected, highlight related edges.
  13. shortcuts-call: Allows end users to call Graph functions using keyboard key combinations, such as pressing control and 1 on the keyboard, to adapt the graph to the canvas.
  14. collapse-expand: Only applicable to tree diagrams, expand or collapse subtrees.

use:

const graph = new G6.Graph({<!-- -->
  container: 'container',
  width: 800,
  height: 600,
  modes: {<!-- -->
    default: [
    {<!-- -->
      type:'drag-canvas',
      direction: 'both' //Allow dragging direction, support 'x', 'y', 'both', the default direction is 'both';
      enableOptimize: true // Whether to enable optimization. After enabling it, all non-keyShape parts of edges and nodes will be hidden during dragging the canvas. It is disabled by default.
    },
    {<!-- -->
      type:'tooltip',
      offset: 10,
      formatText: model=>{<!-- -->
       //Formatting function, can return text or HTML, here returns the label field
        return model.label;
      }
    },
    {<!-- -->
      type:'brush-select', // Frame selection
      brushStyle:{<!-- --> // Set the frame selection style, fill color, fill color transparency, border color, and border width
        fill:'',
        fillOpacity:'',
        stroke:'',
        lineWidth:1
      },
      selectedState: '', // The selected state, the default is selected, you can set the style according to your own needs
      trigger:'' // Trigger the box selection action
    },
    'scroll-canvas', 'zoom-canvas', 'drag-node','click-select','tooltip','create-edge','edge- tooltip'],
  },
  // ...other configurations...
});
  //Event triggered when the node starts to be dragged
  graph.on('node:dragstart', ev=>{<!-- -->});
  // Triggered when the node is dragged again
  graph.on('node:drag', ev=>{<!-- -->});
  // Triggered when the node is dragged again
  graph.on('node:dragend', ev=>{<!-- -->});
  // This event is triggered when 'brush-select' , 'click-select' or 'lasso-select' Behavior is used and the selected element changes.
  graph.on('nodeselectchange', ev=>{<!-- -->
    const {<!-- --> nodes, edges } = ev.selectedItems; //Get the selected data
  });
  // Triggered after creating an edge
  graph.on('aftercreateedge', ev=>{<!-- -->
    const edge = ev.edge.getModel(); // Created edge
    // Get the starting point and end point of the edge and perform other operations
    const source = edge.source;
    const target = edge.target;
  });

In the above code, the modes attribute defines the built-in behavior. And it monitors some behavioral events. This is how it is used.

Custom interaction (Behavior)

In addition to built-in behaviors, you can also create custom Behaviors to implement specific interaction needs. Pass G6.registerBehavior(name, config). Create, name is the name of the behavior. After creating the custom behavior, you need to reference it in the legend, and then use the interactive behavior in modes.
Custom Behavior can include the following main parts:

getDefaultCfg(): Returns the default configuration options.
getEvents(): Returns the event listening configuration, specifying which events will trigger the Behavior.
shouldBegin(e): Defines the conditions under which Behavior starts.
shouldUpdate(e): Defines the conditions for Behavior update.
shouldEnd(e): Defines the conditions under which Behavior ends.
bind(graph): Bind to the chart instance to make Behavior effective.
unbind(): Unbind Behavior.

The following is a simple implementation of a custom interaction that double-clicks the canvas to create a point:

import G6 from "@antv/g6";
import _ from "lodash";
export const RegisterAddNode = () => {<!-- -->
  G6.registerBehavior("create-node", {<!-- -->
    getEvents() {<!-- -->
      return {<!-- -->
        // Listen to the createOn event and trigger the createNode method
        "canvas:dblclick": "createNode",
      };
    },
    createNode(e: any) {<!-- -->
      const graph: any = this.graph;
      // Get the mouse position
      const point = graph.getPointByClient(e.clientX, e.clientY);
      //Create new node
      graph.addItem("node", {<!-- -->
        x: point.x,
        y: point.y,
        size: 32,
        id: _.uniqueId("_node"),
        label: "New node",
        // group: true,
      });
    },
  });
};

use:

import React, {<!-- --> useEffect, useRef } from "react";
import G6 from "@antv/g6";
import _ from "lodash";
import {<!-- --> RegisterAddNode } from "./registerAddNode";


const Beheaviors: React.FC<any> = (props: any) => {<!-- -->
  const containerRef = useRef<HTMLDivElement>(null);
  const graphRef = useRef<any>();

  useEffect(() => {<!-- -->
    initDraw();
  }, []);

  const initDraw = () => {<!-- -->
    RegisterAddNode(); // Initialize canvas reference custom interaction
    graphRef.current = new G6.Graph({<!-- -->
      linkCenter: true,
      container: containerRef.current || "",
      height: 800,
      width: 800,
      modes: {<!-- --> default: ["create-node", "drag-canvas", "drag-node", "custom-tooltip"] },
      defaultNode: {<!-- -->
        size: 20,
        style: {<!-- -->
          fill: "#C6E5FF",
          stroke: "#5B8FF9",
          lineWidth: 0.3,
        },
        labelCfg: {<!-- -->
          style: {<!-- -->
            fontSize: 12,
          },
          position: "bottom",
          offset: 1,
        },
      },
      defaultEdge: {<!-- -->
        style: {<!-- -->
          lineWidth: 2,
          color: "#000",
          labelCfg: {<!-- -->
            autoRotate: true,
            refY: 5,
            style: {<!-- -->
              fill: "#000",
            },
          },
          endArrow: {<!-- -->
            fill: "#000",
            path: G6.Arrow.triangle(10, 12, 25),
            d: 25,
          },
        },
      },
    });

    const data = {<!-- -->
      nodes: [
        {<!-- --> id: "node1", x: 100, y: 100, label: "Node 1" },
        {<!-- --> id: "node2", x: 300, y: 100, label: "Node 2" },
      ],
      edges: [{<!-- --> source: "node1", target: "node2", label: "Edge 1" }],
    };

    // Render chart
    graphRef.current.data(data);
    graphRef.current.render();
  };

  return (
    <>
      <div
        className="ModalgraphContainer"
        ref={<!-- -->containerRef}
        id="graphContainer"
      ></div>
    </>
  );
};
export default Behaviors;

The above code creates a custom Behavior named create-node, which listens to the mouse’s canvas:dblclick event and creates a new node when triggered. Then reference it when initializing the legend. Add the interaction name ‘create-node’ in modes. This will add a point by default when you double-click the canvas.