refactor(flow): export useNodesState and useEdgesState separately from useVueFlow

* bind vueFlow instance to currentInstance when useVueFlow is called multiple times in a single setup call

Signed-off-by: Braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
Braks
2021-12-20 19:29:52 +01:00
parent 63bf3b3a26
commit 39501d0bb0
7 changed files with 159 additions and 142 deletions
+8 -14
View File
@@ -1,34 +1,28 @@
import { getCurrentInstance } from 'vue'
import { useEdgesState, useNodesState } from './useElementState'
import { EdgeChange, FlowOptions, GraphEdge, GraphNode, NodeChange, UseVueFlow } from '~/types'
import { applyChanges } from '~/utils'
import { FlowOptions, UseVueFlow } from '~/types'
import { VueFlow } from '~/context'
import { useStore } from '~/store'
const applyNodeChanges = (changes: NodeChange[], nodes: GraphNode[]) => applyChanges(changes, nodes)
const applyEdgeChanges = (changes: EdgeChange[], edges: GraphEdge[]) => applyChanges(changes, edges)
let id = 0
export default (options?: FlowOptions): UseVueFlow => {
const currentInstance = getCurrentInstance()
let vueFlow: UseVueFlow | false | undefined = currentInstance ? inject(VueFlow, undefined) : false
let vueFlow: UseVueFlow | false | undefined = currentInstance
? inject(VueFlow, undefined) ?? (currentInstance.vueFlow as UseVueFlow)
: false
if (!vueFlow || (vueFlow && options?.id && options.id !== vueFlow.id)) {
const name = options?.id ?? `vue-flow-${id++}`
const store = reactive(useStore(name, options))
const applyNodes = (changes: NodeChange[]) => applyNodeChanges(changes, store.nodes)
const applyEdges = (changes: EdgeChange[]) => applyEdgeChanges(changes, store.edges)
vueFlow = {
id: name,
store,
...toRefs(store),
useNodesState: (nodes, applyDefault = true) => useNodesState(store, applyNodes)({ nodes, applyDefault }),
useEdgesState: (edges, applyDefault = true) => useEdgesState(store, applyEdges)({ edges, applyDefault }),
applyNodeChanges: applyNodes,
applyEdgeChanges: applyEdges,
...store.hooksOn,
}
}
if (currentInstance) provide(VueFlow, vueFlow)
if (currentInstance) {
provide(VueFlow, vueFlow)
currentInstance.vueFlow = vueFlow
}
return vueFlow
}