222
schangxiang@126.com
2025-04-30 9bec4dcae002f36aa23231da11cb03a156b40110
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import {
  defineComponent,
  onMounted,
  ref,
  nextTick,
  watch,
  computed,
  SetupContext,
  Fragment,
  onUnmounted,
} from 'vue'
import styles from './Renderer.module.scss'
import { ConditionType, NODES } from '../../core/enum'
import G6, { Graph } from '@antv/g6'
import { behaviorMap } from '../../core/behavior'
import StartNode from '../Nodes/StartNode'
import EndNode from '../Nodes/EndNode'
import OrdinaryNode from '../Nodes/OrdinaryNode'
import Core from '../../core/Core'
import { injectStore } from '../../core/store'
import { fontSize, nodeFontSize } from '../Nodes'
import Menu from '../Menu/Menu'
import { cloneDeep } from 'lodash'
import ToolBar from '../ToolBar/ToolBarDefine'
import Tooltip from '../Tooltip/Tooltip'
 
interface PropsType {
  graphData: Record<string, any>
  [key: string]: any
  style: Record<string, any>
}
 
export default defineComponent<PropsType>({
  // @ts-ignore
  name: 'G6FlowRenderer',
  props: {
    graphData: {
      type: Object,
      required: true,
    },
    style: { type: Object, default: () => ({}) },
    minimap: { type: [Boolean, Object], default: false },
    isEdgeAnimation: { type: Boolean, default: false },
    dragCanvas: { type: Boolean, default: false },
    dragNode: { type: Boolean, default: false },
    activateRelations: { type: Boolean, default: false },
    zoomCanvas: { type: Boolean, default: false },
    clickSelect: { type: Boolean, default: false },
    createEdge: { type: Boolean, default: false },
    flowName: { type: String, default: '流程图' },
    editing: {
      type: Boolean,
      default: false,
    },
    contextMenu: {
      type: Array,
    },
    edgeContextMenu: {
      type: Array,
    },
  },
  // emits: Object.keys(behaviorMap),
  emits: [],
  setup(props: PropsType, { expose, attrs, slots, emit }: SetupContext) {
    const { graphEvent, flowMap, flowNodeMap } = injectStore()
    const core = new Core()
 
    const canvasConfig = computed(() => {
      return {
        ...attrs,
      }
    })
    let graph: Graph | null = null
    const graphConfig = {
      width: 0,
      height: 0,
    }
    /**
     * 注册边与节点
     */
    const batchRegister = () => {
      G6.registerNode(NODES.END_ACTIVITY, EndNode.options, 'single-node')
      G6.registerNode(NODES.ACTIVITIES, OrdinaryNode.options, 'single-node')
    }
    /**
     * 自动布局
     */
    const autoLayout = () => {
      if (graph) {
        const layout = canvasConfig.value?.layout || {}
        graph.updateLayout({ ...layout })
      }
    }
 
    /**
     * 自动布局
     */
    const render = () => {
      if (graph) {
        if (!props.graphData?.nodes?.length) return
        const isEdit = props.graphData?.nodes?.[0]?.isEdit
        if (isEdit) {
          graph.destroyLayout()
          graph.changeData(props.graphData)
        }
        graph.render()
 
        setTimeout(zoomCanvas)
      }
    }
    /**
     * 缩放到中间
     */
    const zoomCanvas = (x?: number, y?: number) => {
      if (graph) {
        const { width, height } = graphConfig
        graph?.zoomTo(0.7, {
          x: x || width / 2 - 33,
          y: y || 0,
          // duration: 1000,
        })
      }
    }
 
    const getTools = () => {
      const toolBarInstance = new ToolBar({
        className: styles.toolBar,
        format: autoLayout,
        downName: props.flowName,
      })
      const g6ToolInstance = toolBarInstance.instanceToolBar()
      return g6ToolInstance
    }
 
    const getMiniMap = () => {
      const container = document.querySelector(
        `.${styles.miniMap}`
      ) as HTMLDivElement
      if (!container) return
      const minimap = new G6.Minimap({
        container,
      })
      return minimap
    }
    /**
     * 渲染逻辑流
     * @param graphData
     */
    const renderG6Graph = () => {
      if (!Object.keys(props.graphData).length) return
      if (graph) {
        graph.data(props.graphData)
      }
      render()
    }
    /**
     * 获取功能事件配置
     * @returns
     */
    const getBaseBehaviorConfig = () => {
      const events: string[] = []
      Object.entries(props || {}).forEach(([key, value]: any[]) => {
        if (behaviorMap[key] && value) {
          events.push(behaviorMap[key])
        }
      })
      return events
    }
    /**
     * 初始化渲染
     */
    const initializeRenderer = async () => {
      batchRegister()
      await renderG6Graph()
    }
    /**
     * 实例化LogicFlow
     */
    const instanceG6Graph = () => {
      const container = document.querySelector(
        `.${styles.renderer}`
      ) as HTMLElement
      if (!container) return
      const width = container.scrollWidth
      const height = container.scrollHeight || 500
      graphConfig.width = width
      graphConfig.height = height
      const defaultProps = core.setDefaultProps()
      const behavior = getBaseBehaviorConfig()
      const minimap = getMiniMap()
      const toolBar = props.editing ? getTools() : null
      const toolTip = Tooltip()
      const plugins = [minimap, toolBar, toolTip].filter((v) => v)
      graph = new G6.Graph({
        container,
        width,
        height,
        modes: {
          default: [...behavior],
        },
        // 设置为true,启用 redo & undo 栈功能
        enabledStack: true,
        plugins,
        ...defaultProps,
        ...canvasConfig.value,
      })
 
      graphEvent.init(graph, canvasConfig.value.layout)
      initializeRenderer()
    }
    /**
     * 获取当前LogicFlow实例
     * @returns
     */
    const getCurrentInstance = () => {
      return graph
    }
 
    const currentHeight = computed(() => {
      const height = canvasConfig.value?.height
      if (height) {
        return height + 'px'
      }
      return window.innerHeight + 'px'
    })
 
    const addNode = (node: any, position: any) => {
      if (!graph) return
      const point = graph?.getPointByClient(position.x, position.y)
      const config = {
        label: node.name,
        type: node.category,
      }
      const model = core.createNode(config, {
        x: point.x,
        y: point.y,
        properties: {
          Name: node.name,
          type: node.type,
          [ConditionType]: node.type,
        },
      })
      if (flowMap.get(model.Name)) {
        const v = parseInt(String(Math.random() * 10000))
        const newName = model.Name + '_' + v
        model.Name = newName
        model.label = newName
        model.name = newName
        model.properties.Name = newName
      }
      flowNodeMap.set(model.id, model)
      flowMap.set(model.name, model)
      graph?.addItem('node', model)
    }
 
    const getGraph = () => {
      return graph
    }
 
    watch(
      () => props.graphData,
      (v, oldV) => {
        if (v !== oldV && v) {
          instanceG6Graph()
        }
      }
    )
 
    watch(
      () => props.createEdge,
      () => {
        if (!props.createEdge) {
          graph?.removeBehaviors('create-edge', 'default')
        } else {
          graph?.addBehaviors('create-edge', 'default')
        }
      }
    )
 
    onMounted(() => {
      instanceG6Graph()
    })
 
    onUnmounted(() => {
      graph?.destroy()
      graphEvent?.onUnmounted()
    })
 
    expose({
      getGraph,
      render,
      autoLayout,
      getCurrentInstance,
      zoomCanvas,
      addNode,
    })
    return () => {
      let contextMenu =
        graphEvent.type.value === 'edge'
          ? props.edgeContextMenu
          : props.contextMenu
      if (graphEvent.model.value?.isRoot) {
        contextMenu = contextMenu.filter(
          (item: any) => !['copy', 'del'].includes(item.type)
        )
      }
      return (
        <div
          class={styles.renderer}
          // onClick={(event: Event) => onCancelSelect(event)}
          style={{
            width: '100%',
            height: currentHeight.value,
            ...props.style,
          }}
        >
          <div class={styles.miniMap}></div>
          <div class={styles.toolBar}></div>
          {contextMenu && contextMenu.length > 0 && (
            <Menu
              contextMenu={contextMenu}
              visible={true}
              v-model:isShow={graphEvent.isShow.value}
              options={graphEvent.position.value}
              model={graphEvent.model.value}
            />
          )}
        </div>
      )
    }
  },
})