首页
/ LogicFlow自定义连接边(Connection)实现详解

LogicFlow自定义连接边(Connection)实现详解

2025-07-06 06:49:51作者:宣利权Counsellor

LogicFlow是一款优秀的流程图编辑框架,它提供了丰富的节点和边类型供开发者使用。本文将深入解析如何通过继承PolylineEdge和PolylineEdgeModel来实现自定义的连接边(Connection)组件。

自定义连接边概述

在LogicFlow中,自定义边需要实现两个核心部分:

  1. 视图(View):负责边的渲染和交互表现
  2. 模型(Model):负责边的数据逻辑和行为控制

ConnectionView视图实现

1. 调整点(AdjustPoint)样式

getAdjustPointShape(x: number, y: number): h.JSX.Element {
  return h('g', {}, [
    h('image', {
      x: x - 9,
      y: y - 9,
      width: 18,
      height: 18,
      cursor: 'move',
      href: 'data:image/svg+xml;base64,...',
    }),
  ])
}

这段代码重写了调整点的显示样式,使用了一个Base64编码的SVG图像作为调整点的视觉表现。这个SVG是一个蓝色的圆形标记,中间有一个白色的小圆环,提供了良好的视觉反馈。

2. 文本样式定制

getTextStyle() {
  return {
    background: {
      fill: 'white',
      height: 20,
      stroke: 'transparent',
      radius: 0,
    },
  }
}

这里定义了边上的文本样式,为文本添加了白色背景,使文本在各种背景下都能清晰可见。

3. 箭头样式定制

getEndArrow() {
  const { model } = this.props
  const {
    properties: { arrowType },
  } = model
  const { stroke, strokeWidth } = model.getArrowStyle()
  const pathAttr = {
    stroke,
    strokeWidth,
  }
  // 空心箭头
  if (arrowType === 'empty') {
    return h('path', {
      ...pathAttr,
      fill: '#FFF',
      d: 'M -10 0  -20 -5 -30 0 -20 5 z',
    })
  } else if (arrowType === 'half') {
    // 半箭头
    return h('path', {
      ...pathAttr,
      d: 'M 0 0 -10 5',
    })
  }
  return h('path', {
    ...pathAttr,
    fill: stroke,
    d: 'M 0 0 -10 -5 -10 5 z',
  })
}

这段代码实现了三种箭头样式:

  1. 默认实心箭头
  2. 空心箭头(当arrowType为'empty'时)
  3. 半箭头(当arrowType为'half'时)

ConnectionModel模型实现

1. 属性设置

setAttributes() {
  this.textWidth = 200
  const { properties } = this
  if (properties.isActived) {
    this.stroke = 'red'
  }
  if (properties.arrow) {
    this.arrowConfig.markerEnd = (properties.arrow as ArrowConfig).markerEnd
  }
}

在模型初始化时设置了一些默认属性:

  • 文本宽度设置为200像素
  • 当边被激活时(isActived为true),边颜色变为红色
  • 如果properties中有arrow配置,则应用到箭头配置中

2. 箭头样式

getArrowStyle() {
  const style = super.getArrowStyle()
  style.stroke = 'green'
  return style
}

重写了箭头样式,将箭头描边颜色设置为绿色。

导出配置

export default {
  type: 'connection',
  view: ConnectionView,
  model: ConnectionModel,
}

最后将自定义边导出,指定类型为'connection',并关联对应的视图和模型类。

实际应用建议

  1. 自定义调整点:可以根据业务需求替换调整点的SVG图像,使其更符合产品风格
  2. 箭头扩展:可以继续扩展更多箭头类型,如圆形箭头、菱形箭头等
  3. 动态样式:可以根据边的状态(如选中、禁用等)动态改变边的样式
  4. 性能优化:对于复杂的自定义边,可以考虑使用缓存策略优化渲染性能

通过这种自定义方式,开发者可以灵活地创建符合业务需求的流程图边类型,满足各种复杂场景下的可视化需求。