Skip to content
大纲

交互事件

事件监听

事件层次

  • 全局事件: 在画布范围内发生的事件
  • canvas 事件: 在 canvas 空白处发生的事件,事件名增加前缀 canvas:
  • 图的元素事件: 在图的元素上触发的事件,事件名增加对应的前缀 node:edge:combo:
  • 图形上的事件: 细化到 Shape 上的事件,事件名增加对应的前缀 [shapeName]:
    • 具体的 shapeName 可以通过 graph.on('node:click', ev => ev.target.get('name')) 获取
    • text-shaperect-keyShapecircle-keyShape
  • 时机事件: 与元素操作、布局渲染、数据变动、动画交互 等触发, 具体见 文档
  • 自定义事件: 通过 graph.emit(evName: string, evt: IG6GraphEvent) 触发, 通过 graph.on(evName: string, (evt: IG6GraphEvent) => void) 响应
js
// 示例
graph.on("click", ev => {}); // 全局
graph.on("canvas:click", ev => {}); // canvas
graph.on("node:click", ev => {}); // 元素
graph.on("circle-keyShape:click", ev => {}); // shape
graph.on("afterrender", ev => {}); // 时机
ts
// event 常用属性
interface IG6GraphEvent {
  type: string; // 事件类型
  name: string; // 事件名称
  shape: IShape; // 触发事件的图形
  fromShape: IShape; // 开始触发事件的图形
  toShape: IShape; // 事件结束时的触发图形
  item: Item | null; // 触发事件的元素
  target: IShapeBase & ICanvas; // 触发对象
  originalEvent: Event; // 触发时的事件对象
  // ... 其他略
}

交互模式

Behavior 是对特定场景的事件监听的封装, 不同场景下 graph 可能需要不同的 Behavior 支持, 因而采用 Mode 对交互进行管理

ts
type ModeType = string | ModeOption;
interface Modes {
  default?: ModeType[]; // 默认的 模式
  [key: string]: ModeType[]; // 自定义 模式
}
interface AbstractGraph {
  // ... 其他略
  /**
   * 切换模式, 将执行以下操作
   * - 解绑当前 `Mode` 下的事件监听
   * - 生成新的 `Behavior`, 进行事件初始化
   * - 绑定新的行为对应的事件监听
   */
  setMode(mode: string): AbstractGraph;
}
js
// 示例, 假设有 'default' 和 'edit' 两种模式
const graph = new G6.Graph({
  // ...
  modes: {
    default: ["zoom-canvas", "drag-canvas"],
    edit: ["click-select", "drag-node"],
  },
});
// 默认使用 default 模式
// 可通过 `.setMode()` 手动切换
graph.setMode("edit");

配置 Behavior

一般在 modes 中指定支持的 Behavior 类型名称即可, 也可进行具体的配置(参见 文档)

ts
interface ModeOption {
  type: string;
  delegate?: boolean;
  delegateStyle?: object;
  updateEdge?: boolean;
  trigger?: string;
  combinedKey?: string;
  enableDelegate?: boolean;
  maxZoom?: number;
  minZoom?: number;
  enableOptimize?: boolean;
  enableDebounce?: boolean;
  allowDragOnItem?:
    | boolean
    | { node?: boolean; edge?: boolean; combo?: boolean };
  optimizeZoom?: number;
  multiple?: boolean;
  activeState?: string;
  inactiveState?: string;
  comboActiveState?: string;
  selectedState?: string;
  resetSelected?: boolean;
  onlyChangeComboSize?: boolean;
  includeEdges?: boolean;
  includeCombos?: boolean;
  direction?: "x" | "y";
  scalableRange?: number;
  offset?: number;
  sensitivity?: number;
  fixSelectedItems?: Partial<{
    fixAll: boolean;
    fixLineWidth: boolean;
    fixLabel: boolean;
    fixState: string;
  }>;
  key?: string | undefined;
  edgeConfig?: EdgeConfig;
  functionName?: string;
  functionParams?: any[];
  relayout?: boolean;
  brushStyle?: object;
  zoomKey?: ZoomKeyType | ZoomKeyType[];
  selectNode?: boolean;
  selectEdge?: boolean;
  selectCombo?: boolean;
  shouldUpdate?: (e: IG6GraphEvent) => boolean;
  shouldBegin?: (e: IG6GraphEvent) => boolean;
  shouldEnd?: (e: IG6GraphEvent) => boolean;
  onChange?: (item?: Item, judge?: boolean) => unknown;
  onSelect?: (selectedNodes?: Item[], selectedEdges?: Item[]) => unknown;
  onDeselect?: (selectedNodes?: Item[], selectedEdges?: Item[]) => unknown;
  formatText?: (data: { [key: string]: unknown }) => string;
}

管理 Behavior

ts
interface AbstractGraph {
  // ... 其他略
  /**
   * 新增行为
   * @param {string | ModeOption | ModeType[]} behaviors 添加的行为
   * @param {string | string[]} modes 添加到对应的模式
   * @return {Graph} Graph
   */
  addBehaviors(
    behaviors: string | ModeOption | ModeType[],
    modes: string | string[]
  ): AbstractGraph;
  /**
   * 移除行为
   * @param {string | ModeOption | ModeType[]} behaviors 移除的行为
   * @param {string | string[]} modes 从指定的模式中移除
   * @return {Graph} Graph
   */
  removeBehaviors(
    behaviors: string | ModeOption | ModeType[],
    modes: string | string[]
  ): AbstractGraph;
  /**
   * 更新行为参数
   * @param {string | ModeOption | ModeType} behavior 需要更新的行为
   * @param {string | string[]} modes 指定的模式中的行为,不指定则为 default
   * @return {Graph} Graph
   */
  updateBehavior(
    behavior: string,
    newCfg: object,
    mode?: string
  ): AbstractGraph;
}

// 示例
graph.addBehaviors(["new-behavior", "del-behavior"], "default");
graph.removeBehaviors("del-behavior", "default");
graph.updateBehavior("new-behavior", { field: "value" }, "default");

管理状态

G6 状态分为交互状态和业务状态,使用时不做区分,通常配合样式使用

  • 交互状态:与交互行为相关的,通常是事件触发的
  • 业务状态:与业务数据相关的,通常是数据驱动的
ts
interface AbstractGraph {
  /**
   * 设置元素状态
   * @param {Item} item 元素id或元素实例
   * @param {string} state 状态名称
   * @param {string | boolean} value 是否启用状态 或 状态值
   */
  setItemState(
    item: Item | string,
    state: string,
    value: string | boolean
  ): void;
  /**
   * 清理元素多个状态
   * @param {string|Item} item 元素id或元素实例
   * @param {string[]} states 状态
   */
  clearItemStates(item: Item | string, states?: string[] | string): void;
}
graph.setItemState(item, stateName, stateVal);
ts
// 状态样式
// 实例化时通过 `nodeStateStyles`、`edgeStateStyles`、`comboStateStyles` 配置
interface GraphOptions {
  nodeStateStyles?: StateStyles;
  edgeStateStyles?: StateStyles;
  comboStateStyles?: StateStyles;
}

// 元素数据中配置 `stateStyles`
// item.hasState(stateName) 可以判断状态是否处于激活状态
const data = {
  nodes: [{ id: "demo", stateStyles: { "1激活": { fill: "blue" } } }],
};
graph.on("node:click", ev => {
  const item = ev.item;
  if (!item) return;
  graph.setItemState(item, "1激活", !item.hasState("1激活"));
});

内置 Behavior

内置 Behavior 配置见 文档

交互描述
drag-combo拖动 combo
collapse-expand-combo展开或收缩 combo
drag-canvas拖拽 canvas
scroll-canvas滚动 canvas
zoom-canvas缩放 canvas
drag-node拖动 node 或 combo 中的 node
click-select点击选中, 再次点击或点击 canvas 取消选中
tooltip节点文本提示, tooltip 为 HTML, 默认 class="g6-tooltip g6-node-tooltip"
edge-tooltip边文本提示, tooltip 为 HTML, 默认 class="g6-tooltip g6-edge-tooltip"
activate-relations鼠标经过节点时, 高亮节点及直接相连的节点和边
brush-select框选节点, 按住 shift 可以框选节点及边
lasso-select自由圈选
collapse-expand仅树图,展开或收起子树
create-edge分别点击两个节点可以创建连接的边
shortcuts-call激活快捷键