refactor(types)!: Remove elements prop, change EdgeTypes/NodeTypes prop to string[]

* no more elements prop - v-model instead!
* Instead of passing an object map to components just pass in an array of strings as nodeTypes/edgeTypes object
* the string name will either be resolved to a dynamic component with :is="type" or a slot with the type-name
* update all examples

Signed-off-by: Braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
Braks
2021-11-20 22:10:25 +01:00
parent 0a1c2d4ede
commit 39b21faa5b
34 changed files with 169 additions and 200 deletions
+1 -1
View File
@@ -58,8 +58,8 @@ const toggleclasss = () => {
</script> </script>
<template> <template>
<VueFlow <VueFlow
v-model="elements"
class="vue-flow-basic-example" class="vue-flow-basic-example"
:elements="elements"
:default-zoom="1.5" :default-zoom="1.5"
:min-zoom="0.2" :min-zoom="0.2"
:max-zoom="4" :max-zoom="4"
@@ -14,7 +14,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value)) const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value))
</script> </script>
<template> <template>
<VueFlow :elements="elements" @elements-remove="onElementsRemove" @connect="onConnect"> <VueFlow v-model="elements" @elements-remove="onElementsRemove" @connect="onConnect">
<template #custom-connection-line="props"> <template #custom-connection-line="props">
<ConnectionLine v-bind="props" /> <ConnectionLine v-bind="props" />
</template> </template>
+4 -4
View File
@@ -22,9 +22,6 @@ const elements = ref<Elements>([])
const bgColor = ref('#1A192B') const bgColor = ref('#1A192B')
const connectionLineStyle = { stroke: '#fff' } const connectionLineStyle = { stroke: '#fff' }
const snapGrid: SnapGrid = [16, 16] const snapGrid: SnapGrid = [16, 16]
const nodeTypes = {
selectorNode: markRaw(ColorSelectorNode),
}
const onLoad = (flowInstance: FlowInstance) => { const onLoad = (flowInstance: FlowInstance) => {
flowInstance.fitView() flowInstance.fitView()
@@ -114,7 +111,7 @@ const onConnect = (params: Connection | Edge) =>
<VueFlow <VueFlow
v-model="elements" v-model="elements"
:style="`background: ${bgColor}`" :style="`background: ${bgColor}`"
:node-types="nodeTypes" :node-types="['selectorNode']"
:connection-mode="ConnectionMode.Loose" :connection-mode="ConnectionMode.Loose"
:connection-line-style="connectionLineStyle" :connection-line-style="connectionLineStyle"
:snap-to-grid="true" :snap-to-grid="true"
@@ -126,6 +123,9 @@ const onConnect = (params: Connection | Edge) =>
@node-drag-stop="onNodeDragStop" @node-drag-stop="onNodeDragStop"
@load="onLoad" @load="onLoad"
> >
<template #node-selectorNode="props">
<ColorSelectorNode v-bind="props" />
</template>
<MiniMap :node-stroke-color="nodeStroke" :node-color="nodeColor" /> <MiniMap :node-stroke-color="nodeStroke" :node-color="nodeColor" />
<Controls /> <Controls />
</VueFlow> </VueFlow>
+1 -1
View File
@@ -23,7 +23,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value)) const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value))
</script> </script>
<template> <template>
<VueFlow :elements="elements" :min-zoom="0.2" @load="onLoad" @elements-remove="onElementsRemove" @connect="onConnect"> <VueFlow v-model="elements" :min-zoom="0.2" @load="onLoad" @elements-remove="onElementsRemove" @connect="onConnect">
<MiniMap /> <MiniMap />
<Controls /> <Controls />
</VueFlow> </VueFlow>
+6 -7
View File
@@ -7,15 +7,11 @@ import {
Connection, Connection,
Controls, Controls,
Edge, Edge,
EdgeType,
Elements, Elements,
MiniMap, MiniMap,
FlowInstance, FlowInstance,
removeElements, removeElements,
} from '~/index' } from '~/index'
const edgeTypes = {
buttonedge: ButtonEdge as EdgeType,
}
const elements = ref<Elements>([ const elements = ref<Elements>([
{ {
@@ -29,7 +25,7 @@ const elements = ref<Elements>([
id: 'edge-1-2', id: 'edge-1-2',
source: 'ewb-1', source: 'ewb-1',
target: 'ewb-2', target: 'ewb-2',
type: 'buttonedge', type: 'button',
}, },
]) ])
@@ -41,13 +37,16 @@ const onConnect = (params: Connection | Edge) =>
<template> <template>
<VueFlow <VueFlow
key="edge-with-button" key="edge-with-button"
:elements="elements" v-model="elements"
:snap-to-grid="true" :snap-to-grid="true"
:edge-types="edgeTypes" :edge-types="['button']"
@load="onLoad" @load="onLoad"
@elementsRemove="onElementsRemove" @elementsRemove="onElementsRemove"
@connect="onConnect" @connect="onConnect"
> >
<template #edge-button="props">
<ButtonEdge v-bind="props" />
</template>
<MiniMap /> <MiniMap />
<Controls /> <Controls />
<Background /> <Background />
+8 -7
View File
@@ -75,11 +75,6 @@ const initialElements: Elements = [
}, },
] ]
const edgeTypes: Record<string, any> = {
custom: CustomEdge,
custom2: CustomEdge2,
}
const elements = ref<Elements>(initialElements) const elements = ref<Elements>(initialElements)
const onLoad = (flowInstance: FlowInstance) => flowInstance.fitView() const onLoad = (flowInstance: FlowInstance) => flowInstance.fitView()
@@ -90,15 +85,21 @@ const onConnect = (params: Connection | Edge) => (elements.value = addEdge(param
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:snap-to-grid="true" :snap-to-grid="true"
:edge-types="edgeTypes" :edge-types="['custom', 'custom2']"
@element-click="onElementClick" @element-click="onElementClick"
@elements-remove="onElementsRemove" @elements-remove="onElementsRemove"
@connect="onConnect" @connect="onConnect"
@node-drag-stop="onNodeDragStop" @node-drag-stop="onNodeDragStop"
@load="onLoad" @load="onLoad"
> >
<template #edge-custom="props">
<CustomEdge v-bind="props" />
</template>
<template #edge-custom2="props">
<CustomEdge2 v-bind="props" />
</template>
<MiniMap /> <MiniMap />
<Controls /> <Controls />
<Background /> <Background />
+1 -1
View File
@@ -23,7 +23,7 @@ watchEffect(() => {
}) })
</script> </script>
<template> <template>
<VueFlow :elements="elements" @connect="onConnect"> <VueFlow v-model="elements" @connect="onConnect">
<MiniMap /> <MiniMap />
<Controls /> <Controls />
+1 -1
View File
@@ -48,7 +48,7 @@ const captureElementClick = ref(false)
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:elements-selectable="isSelectable" :elements-selectable="isSelectable"
:nodes-connectable="isConnectable" :nodes-connectable="isConnectable"
:nodes-draggable="isDraggable" :nodes-draggable="isDraggable"
+1 -1
View File
@@ -59,7 +59,7 @@ const onLayout = (direction: string) => {
<template> <template>
<div class="layoutflow"> <div class="layoutflow">
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:node-extent="nodeExtent" :node-extent="nodeExtent"
:connection-mode="ConnectionMode.Loose" :connection-mode="ConnectionMode.Loose"
@connect="onConnect" @connect="onConnect"
+1 -1
View File
@@ -14,7 +14,7 @@ const onConnect = (params: Connection | Edge) => (elements.value = addEdge(param
const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value)) const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value))
</script> </script>
<template> <template>
<VueFlow :elements="elements" @elements-remove="onElementsRemove" @connect="onConnect"> <VueFlow v-model="elements" @elements-remove="onElementsRemove" @connect="onConnect">
<Background /> <Background />
</VueFlow> </VueFlow>
</template> </template>
@@ -41,7 +41,7 @@ const changeType = () => {
} }
</script> </script>
<template> <template>
<VueFlow :elements="elements" @connect="onConnect" @load="onLoad"> <VueFlow v-model="elements" @connect="onConnect" @load="onLoad">
<button :style="buttonStyle" @click="changeType">change type</button> <button :style="buttonStyle" @click="changeType">change type</button>
</VueFlow> </VueFlow>
</template> </template>
@@ -27,12 +27,8 @@ const buttonStyle: CSSProperties = { position: 'absolute', right: 10, top: 30, z
const nodeStyles: CSSProperties = { padding: '10px 15px', border: '1px solid #ddd' } const nodeStyles: CSSProperties = { padding: '10px 15px', border: '1px solid #ddd' }
const nodeTypesObjects: Record<string, NodeTypes> = { const nodeTypesObjects: Record<string, NodeTypes> = {
a: { a: ['a'],
a: NodeA, b: ['b'],
},
b: {
b: NodeB,
},
} }
const elements = ref(initialElements) const elements = ref(initialElements)
+1 -1
View File
@@ -137,7 +137,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:connection-line-style="connectionLineStyle" :connection-line-style="connectionLineStyle"
:snap-to-grid="true" :snap-to-grid="true"
:snap-grid="snapGrid" :snap-grid="snapGrid"
+1 -1
View File
@@ -38,7 +38,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
<Sidebar /> <Sidebar />
<div class="vue-flow-wrapper"> <div class="vue-flow-wrapper">
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:connection-mode="ConnectionMode.Loose" :connection-mode="ConnectionMode.Loose"
@element-click="onElementClick" @element-click="onElementClick"
@connect="onConnect" @connect="onConnect"
+2 -7
View File
@@ -31,13 +31,8 @@ const color = ref<Colors>({
}) })
const onChange = ({ color: c, val }: { color: keyof Colors; val: number }) => (color.value[c] = Number(val)) const onChange = ({ color: c, val }: { color: keyof Colors; val: number }) => (color.value[c] = Number(val))
const store = useVueFlow({ const store = useVueFlow({
nodeTypes: { nodeTypes: ['rgb', 'rgb-output'],
'rgb': true, edgeTypes: ['pathfinding'],
'rgb-output': true,
},
edgeTypes: {
pathfinding: true,
},
zoomOnScroll: false, zoomOnScroll: false,
}) })
</script> </script>
+1
View File
@@ -51,6 +51,7 @@ const updateElements = () => {
<template> <template>
<VueFlow <VueFlow
v-model="elements" v-model="elements"
:worker="true"
:loading="{ label: 'Loading...', transition: { name: 'fade', mode: 'out-in' } }" :loading="{ label: 'Loading...', transition: { name: 'fade', mode: 'out-in' } }"
@load="onLoad" @load="onLoad"
@elementsRemove="onElementsRemove" @elementsRemove="onElementsRemove"
+1 -1
View File
@@ -33,7 +33,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
@element-click="onElementClick" @element-click="onElementClick"
@elements-remove="onElementsRemove" @elements-remove="onElementsRemove"
@connect="onConnect" @connect="onConnect"
@@ -2,7 +2,6 @@
import CustomNode from './CustomNode.vue' import CustomNode from './CustomNode.vue'
import { import {
VueFlow, VueFlow,
NodeType,
addEdge, addEdge,
useZoomPanHelper, useZoomPanHelper,
Elements, Elements,
@@ -14,7 +13,6 @@ import {
ConnectionMode, ConnectionMode,
updateEdge, updateEdge,
ArrowHeadType, ArrowHeadType,
NodeTypes,
} from '~/index' } from '~/index'
const initialElements: Elements = [ const initialElements: Elements = [
@@ -173,10 +171,6 @@ const initialElements: Elements = [
}, },
] ]
const nodeTypes: NodeTypes = {
custom: CustomNode,
}
let id = 4 let id = 4
const getId = (): ElementId => `${id++}` const getId = (): ElementId => `${id++}`
@@ -195,12 +189,16 @@ const onPaneClick = (evt: MouseEvent) =>
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:node-types="nodeTypes" :node-types="['custom']"
:connection-line-type="ConnectionLineType.SmoothStep" :connection-line-type="ConnectionLineType.SmoothStep"
:connection-mode="ConnectionMode.Loose" :connection-mode="ConnectionMode.Loose"
@connect="onConnect" @connect="onConnect"
@pane-click="onPaneClick" @pane-click="onPaneClick"
@edge-pdate="onEdgeUpdate" @edge-pdate="onEdgeUpdate"
/> >
<template #node-custom="props">
<CustomNode v-bind="props" />
</template>
</VueFlow>
</template> </template>
@@ -51,7 +51,7 @@ const onElementsRemove = (elementsToRemove: Elements) => (elements.value = remov
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:snap-to-grid="true" :snap-to-grid="true"
:connection-mode="ConnectionMode.Loose" :connection-mode="ConnectionMode.Loose"
@load="onLoad" @load="onLoad"
+1 -1
View File
@@ -35,7 +35,7 @@ watchEffect(() => {
}) })
</script> </script>
<template> <template>
<VueFlow :elements="elements" :default-zoom="1.5" :min-zoom="0.2" :max-zoom="4"> <VueFlow v-model="elements" :default-zoom="1.5" :min-zoom="0.2" :max-zoom="4">
<div class="updatenode__controls"> <div class="updatenode__controls">
<label>label:</label> <label>label:</label>
<input v-model="nodeName" /> <input v-model="nodeName" />
+4 -1
View File
@@ -3,7 +3,10 @@ import { CSSProperties } from 'vue'
import { Handle, Position, NodeProps } from '~/index' import { Handle, Position, NodeProps } from '~/index'
interface CustomNodeProps extends NodeProps { interface CustomNodeProps extends NodeProps {
data: any data: {
handleCount: number
handlePosition: number
}
} }
const nodeStyles: CSSProperties = { padding: 10, border: '1px solid #ddd' } const nodeStyles: CSSProperties = { padding: 10, border: '1px solid #ddd' }
@@ -3,7 +3,6 @@ import { CSSProperties } from 'vue'
import CustomNode from './CustomNode.vue' import CustomNode from './CustomNode.vue'
import { import {
VueFlow, VueFlow,
NodeType,
addEdge, addEdge,
useZoomPanHelper, useZoomPanHelper,
Node, Node,
@@ -14,7 +13,6 @@ import {
Position, Position,
isEdge, isEdge,
FlowInstance, FlowInstance,
NodeTypes,
} from '~/index' } from '~/index'
const initialHandleCount = 1 const initialHandleCount = 1
@@ -30,10 +28,6 @@ const initialElements: Elements = [
const buttonWrapperStyles: CSSProperties = { position: 'absolute', right: 10, top: 10, zIndex: 10 } const buttonWrapperStyles: CSSProperties = { position: 'absolute', right: 10, top: 10, zIndex: 10 }
const nodeTypes: NodeTypes = {
custom: CustomNode,
}
let id = 5 let id = 5
const getId = (): ElementId => `${id++}` const getId = (): ElementId => `${id++}`
@@ -72,7 +66,10 @@ const onLoad = (instance: FlowInstance) => {
} }
</script> </script>
<template> <template>
<VueFlow :elements="elements" :node-types="nodeTypes" @connect="onConnect" @pane-click="onPaneClick" @load="onLoad"> <VueFlow v-model="elements" :node-types="['custom']" @connect="onConnect" @pane-click="onPaneClick" @load="onLoad">
<template #node-custom="props">
<CustomNode v-bind="props" />
</template>
<div :style="buttonWrapperStyles"> <div :style="buttonWrapperStyles">
<button @click="toggleHandleCount">toggle handle count</button> <button @click="toggleHandleCount">toggle handle count</button>
<button @click="toggleHandlePosition">toggle handle position</button> <button @click="toggleHandlePosition">toggle handle position</button>
+11 -21
View File
@@ -1,20 +1,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import CustomInput from './CustomInput.vue' import CustomInput from './CustomInput.vue'
import CustomNode from './CustomNode.vue' import CustomNode from './CustomNode.vue'
import { import { VueFlow, addEdge, Connection, Elements, Edge, OnConnectStartParams, FlowInstance } from '~/index'
VueFlow,
addEdge,
Handle,
Connection,
Position,
Elements,
Edge,
OnConnectStartParams,
NodeProps,
FlowInstance,
NodeType,
NodeTypes,
} from '~/index'
import './validation.css' import './validation.css'
@@ -35,21 +22,24 @@ const onConnect = (params: Connection | Edge) => {
console.log('on connect', params) console.log('on connect', params)
elements.value = addEdge(params, elements.value) elements.value = addEdge(params, elements.value)
} }
const nodeTypes: NodeTypes = {
custominput: CustomInput,
customnode: CustomNode,
}
</script> </script>
<template> <template>
<VueFlow <VueFlow
:elements="elements" v-model="elements"
:select-nodes-on-drag="false" :select-nodes-on-drag="false"
:node-types="['custominput', 'customnode']"
class="validationflow" class="validationflow"
:node-types="nodeTypes"
@connect="onConnect" @connect="onConnect"
@oad="onLoad" @oad="onLoad"
@connect-start="onConnectStart" @connect-start="onConnectStart"
@connect-stop="onConnectStop" @connect-stop="onConnectStop"
@connect-end="onConnectEnd" @connect-end="onConnectEnd"
/> >
<template #node-custominput="props">
<CustomInput v-bind="props" />
</template>
<template #node-customnode="props">
<CustomNode v-bind="props" />
</template>
</VueFlow>
</template> </template>
@@ -44,7 +44,7 @@ const onConnect = (params: Connection | Edge) => (elements.value = addEdge(param
const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value)) const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value))
</script> </script>
<template> <template>
<VueFlow :elements="elements" @elements-remove="onElementsRemove" @connect="onConnect" @pane-click="onPaneClick"> <VueFlow v-model="elements" @elements-remove="onElementsRemove" @connect="onConnect" @pane-click="onPaneClick">
<Background /> <Background />
<MiniMap /> <MiniMap />
</VueFlow> </VueFlow>
+7 -5
View File
@@ -16,13 +16,15 @@ const props = withDefaults(defineProps<EdgeProps>(), {})
const store = useStore() const store = useStore()
const type = computed(() => { const type = computed(() => {
const edgeType = props.edge.type || 'default' const t = props.edge.type ?? 'default'
const t = store.getEdgeTypes[edgeType] || store.getEdgeTypes.default let edge = store.getEdgeTypes[t]
if (!store.getEdgeTypes[edgeType]) { if (!edge) {
console.warn(`Edge type "${edgeType}" not found. Using fallback type "default".`) edge = store.getEdgeTypes.default
console.warn(`Edge type "${t}" not found. Using fallback type "default".`)
} }
return t return edge
}) })
const updating = ref<boolean>(false) const updating = ref<boolean>(false)
const onEdgeClick = (event: MouseEvent) => { const onEdgeClick = (event: MouseEvent) => {
+6 -6
View File
@@ -21,12 +21,13 @@ provide(NodeId, props.node.id)
const nodeElement = templateRef<HTMLDivElement>('node-element', null) const nodeElement = templateRef<HTMLDivElement>('node-element', null)
const type = computed(() => { const type = computed(() => {
const nodeType = props.node.type ?? 'default' const t = props.node.type ?? 'default'
const t = store.getNodeTypes[nodeType] || store.getNodeTypes.default let node = store.getNodeTypes[t]
if (!store.getNodeTypes[nodeType]) { if (!node) {
console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`) node = store.getNodeTypes.default
console.warn(`Node type "${t}" not found. Using fallback type "default".`)
} }
return t return node
}) })
const selectable = computed(() => const selectable = computed(() =>
@@ -192,7 +193,6 @@ onMounted(() => {
> >
<component <component
:is="type" :is="type"
v-if="typeof type !== 'boolean'"
v-bind="{ v-bind="{
id: props.node.id, id: props.node.id,
data: props.node.data, data: props.node.data,
-1
View File
@@ -24,7 +24,6 @@ export default (options?: Partial<FlowOptions>, key?: string) => {
if (storedState.value.position && storedState.value.zoom) if (storedState.value.position && storedState.value.zoom)
preloadedState.transform = [storedState.value.position[0], storedState.value.position[1], storedState.value.zoom] preloadedState.transform = [storedState.value.position[0], storedState.value.position[1], storedState.value.zoom]
} }
console.log(storedState.value)
} }
store = useStateStore(storageKey, preloadedState)() store = useStateStore(storageKey, preloadedState)()
if (withStorage && storageKey === store.$id) { if (withStorage && storageKey === store.$id) {
+2 -2
View File
@@ -34,8 +34,8 @@ const transform = computed(() => `translate(${store.transform[0]},${store.transf
<MarkerDefinitions :color="props.arrowHeadColor" /> <MarkerDefinitions :color="props.arrowHeadColor" />
<g :transform="transform"> <g :transform="transform">
<Edge <Edge
v-for="edge of store.getEdges" v-for="(edge, i) of store.getEdges"
:key="edge.id" :key="`${edge.id}-${i}`"
:edge="edge" :edge="edge"
:marker-end-id="props.markerEndId" :marker-end-id="props.markerEndId"
:edge-updater-radius="props.edgeUpdaterRadius" :edge-updater-radius="props.edgeUpdaterRadius"
+10 -31
View File
@@ -30,7 +30,6 @@ export interface FlowProps extends Partial<FlowOptions> {
id?: string id?: string
store?: FlowStore store?: FlowStore
modelValue?: Elements modelValue?: Elements
elements?: Elements
nodeTypes?: NodeTypes nodeTypes?: NodeTypes
edgeTypes?: EdgeTypes edgeTypes?: EdgeTypes
connectionMode?: ConnectionMode connectionMode?: ConnectionMode
@@ -72,7 +71,6 @@ const emit = defineEmits([...Object.keys(createHooks()), 'update:elements', 'upd
const props = withDefaults(defineProps<FlowProps>(), { const props = withDefaults(defineProps<FlowProps>(), {
modelValue: () => [], modelValue: () => [],
elements: () => [],
connectionMode: ConnectionMode.Loose, connectionMode: ConnectionMode.Loose,
connectionLineType: ConnectionLineType.Bezier, connectionLineType: ConnectionLineType.Bezier,
selectionKeyCode: 'Shift', selectionKeyCode: 'Shift',
@@ -111,18 +109,18 @@ const props = withDefaults(defineProps<FlowProps>(), {
worker: false, worker: false,
}) })
const store = initFlow(emit, typeof props.storageKey === 'string' ? props.storageKey : props.id, props.store) const store = initFlow(emit, typeof props.storageKey === 'string' ? props.storageKey : props.id, props.store)
const elements = useVModel(props, props.elements.length ? 'elements' : 'modelValue', emit) const elements = useVModel(props, 'modelValue', emit)
const options = Object.assign({}, props, store.$state)
// if there are preloaded elements we overwrite the current elements with the stored ones // if there are preloaded elements we overwrite the current elements with the stored ones
if (store.elements.length) elements.value = store.elements if (store.elements.length) elements.value = store.elements
const options = Object.assign({}, store.$state, props)
const init = (state: FlowState) => { const init = (state: FlowState) => {
// set state variables // set state variables
for (const opt of Object.keys(state)) { for (const opt of Object.keys(state)) {
const val = state[opt as keyof FlowState] const val = state[opt as keyof FlowState]
if (typeof val !== 'undefined') { if (typeof val !== 'undefined' && opt !== 'modelValue' && opt !== 'elements') {
if (typeof val === 'object' && !Array.isArray(val)) { if (typeof val === 'object' && !Array.isArray(val)) {
;(store as any)[opt] = { ...(store as any)[opt], ...val } ;(store as any)[opt] = { ...(store as any)[opt], ...val }
} else (store as any)[opt] = val } else (store as any)[opt] = val
@@ -157,32 +155,13 @@ invoke(async () => {
store.instance = instance store.instance = instance
}) })
throttledWatch(elements, (val) => store.setElements(val), { flush: 'post', deep: true, throttle: 10 })
throttledWatch(store.elements, (val) => (elements.value = val), { flush: 'post', deep: true, throttle: 10 })
onMounted(() => { onMounted(() => {
watch(
elements,
(val) => {
// if new elements are added or elements have been removed, we want to re-parse the elements
if (val.length !== store.elements.length) store.setElements(val)
},
{ flush: 'post', deep: true },
)
watch(
store.elements,
(val) => {
// if stored elements change we want to update the v-model to notify parent about changes, i.e. there was a state manipulation
const hasDiff = diff(val, elements.value)
if (hasDiff.length > 0) elements.value = val
},
{ flush: 'post', deep: true },
)
watch( watch(
() => props, () => props,
(val, oldVal) => { () => init({ ...store.$state, ...props } as FlowState),
const hasDiff = diff(val, oldVal)
// when props changed we want to update state variables
if (hasDiff.length > 0) init({ ...store.$state, ...props } as FlowState)
},
{ flush: 'post', deep: true }, { flush: 'post', deep: true },
) )
}) })
@@ -252,8 +231,8 @@ const transitionName = computed(() => {
<slot name="zoom-pane" v-bind="zoomPaneProps"></slot> <slot name="zoom-pane" v-bind="zoomPaneProps"></slot>
</template> </template>
</ZoomPane> </ZoomPane>
<template #fallback> <template v-if="store.loading" #fallback>
<slot v-if="store.loading" key="loading-indicator" name="loading-indicator"> <slot key="loading-indicator" name="loading-indicator">
<LoadingIndicator key="default-loading-indicator" v-bind="store.loading"> <LoadingIndicator key="default-loading-indicator" v-bind="store.loading">
<slot name="loading-label" /> <slot name="loading-label" />
</LoadingIndicator> </LoadingIndicator>
+19 -11
View File
@@ -1,7 +1,7 @@
import { setActivePinia, createPinia, defineStore, StoreDefinition } from 'pinia' import { setActivePinia, createPinia, defineStore, StoreDefinition } from 'pinia'
import diff from 'microdiff' import diff from 'microdiff'
import { parseElements, defaultNodeTypes, defaultEdgeTypes, deepUnref } from './utils' import { parseElements, defaultNodeTypes, defaultEdgeTypes, deepUnref, NextElements } from './utils'
import { FlowState, Node, FlowActions, Elements, FlowGetters, Edge, EdgeTypes, NodeTypes } from '~/types' import { FlowState, Node, FlowActions, Elements, FlowGetters, Edge } from '~/types'
import { clampPosition, getDimensions, getConnectedEdges, getNodesInside, getRectOfNodes, isNode } from '~/utils' import { clampPosition, getDimensions, getConnectedEdges, getNodesInside, getRectOfNodes, isNode } from '~/utils'
import { getHandleBounds } from '~/components/Nodes/utils' import { getHandleBounds } from '~/components/Nodes/utils'
import parseElementsWorker from '~/workers/parseElements' import parseElementsWorker from '~/workers/parseElements'
@@ -20,11 +20,19 @@ export default function flowStore(
...preloadedState, ...preloadedState,
}), }),
getters: { getters: {
getEdgeTypes(): EdgeTypes { getEdgeTypes() {
return { ...defaultEdgeTypes, ...this.edgeTypes } const edgeTypes: Record<string, any> = {
...defaultEdgeTypes,
}
this.edgeTypes?.forEach((n) => (edgeTypes[n] = n))
return edgeTypes
}, },
getNodeTypes(): NodeTypes { getNodeTypes() {
return { ...defaultNodeTypes, ...this.nodeTypes } const nodeTypes: Record<string, any> = {
...defaultNodeTypes,
}
this.nodeTypes?.forEach((n) => (nodeTypes[n] = n))
return nodeTypes
}, },
getNodes(): Node[] { getNodes(): Node[] {
const n = this.onlyRenderVisibleElements const n = this.onlyRenderVisibleElements
@@ -50,12 +58,12 @@ export default function flowStore(
}, },
actions: { actions: {
async setElements(elements) { async setElements(elements) {
let next: any = { let next: NextElements = {
nextEdges: [], nextEdges: [],
nextNodes: [], nextNodes: [],
} }
if (!this.worker || import.meta.env.SSR || typeof window === 'undefined') { if (!this.worker || import.meta.env.SSR || typeof window === 'undefined') {
next = parseElements(elements, this.nodes, this.edges, this.nodeExtent) next = await parseElements(elements, this.nodes, this.edges, this.nodeExtent)
} else if (this.worker) { } else if (this.worker) {
const { workerFn, workerTerminate } = parseElementsWorker() const { workerFn, workerTerminate } = parseElementsWorker()
const res = await workerFn( const res = await workerFn(
@@ -70,7 +78,7 @@ export default function flowStore(
if (res) { if (res) {
workerTerminate('SUCCESS') workerTerminate('SUCCESS')
next = res next = res
} else next = parseElements(elements, this.nodes, this.edges, this.nodeExtent) } else next = await parseElements(elements, this.nodes, this.edges, this.nodeExtent)
} }
if (next) { if (next) {
this.elements = elements ?? [] this.elements = elements ?? []
@@ -255,8 +263,8 @@ export default function flowStore(
this.nodesConnectable = isInteractive this.nodesConnectable = isInteractive
this.elementsSelectable = isInteractive this.elementsSelectable = isInteractive
}, },
addElements(elements: Elements) { async addElements(elements: Elements) {
const { nextNodes, nextEdges } = parseElements(elements, this.nodes, this.edges, this.nodeExtent) const { nextNodes, nextEdges } = await parseElements(elements, this.nodes, this.edges, this.nodeExtent)
this.elements = [...this.elements, ...elements] this.elements = [...this.elements, ...elements]
this.nodes = [...this.nodes, ...nextNodes] this.nodes = [...this.nodes, ...nextNodes]
this.edges = [...this.edges, ...nextEdges] this.edges = [...this.edges, ...nextEdges]
+52 -51
View File
@@ -1,25 +1,26 @@
import { ConnectionMode, Edge, EdgeTypes, Elements, FlowState, Node, NodeExtent, NodeTypes, PanOnScrollMode } from '~/types' import { Component } from 'vue'
import { ConnectionMode, Edge, EdgeProps, Elements, FlowState, Node, NodeExtent, NodeProps, PanOnScrollMode } from '~/types'
import { isEdge, isNode, parseEdge, parseNode } from '~/utils' import { isEdge, isNode, parseEdge, parseNode } from '~/utils'
import { DefaultNode, InputNode, OutputNode } from '~/components/Nodes' import { DefaultNode, InputNode, OutputNode } from '~/components/Nodes'
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge } from '~/components/Edges' import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge } from '~/components/Edges'
import { createHooks } from '~/composables' import { createHooks } from '~/composables'
type NextElements = { export type NextElements = {
nextNodes: Node[] nextNodes: Node[]
nextEdges: Edge[] nextEdges: Edge[]
} }
export const defaultNodeTypes: NodeTypes = { export const defaultNodeTypes: Record<string, Component<NodeProps>> = {
input: markRaw(InputNode), input: InputNode,
default: markRaw(DefaultNode), default: DefaultNode,
output: markRaw(OutputNode), output: OutputNode,
} }
export const defaultEdgeTypes: EdgeTypes = { export const defaultEdgeTypes: Record<string, Component<EdgeProps>> = {
default: markRaw(BezierEdge), default: BezierEdge,
straight: markRaw(StraightEdge), straight: StraightEdge,
step: markRaw(StepEdge), step: StepEdge,
smoothstep: markRaw(SmoothStepEdge), smoothstep: SmoothStepEdge,
} }
export const initialState = (): FlowState => ({ export const initialState = (): FlowState => ({
@@ -93,52 +94,52 @@ export const initialState = (): FlowState => ({
vueFlowVersion: typeof __VUE_FLOW_VERSION__ !== 'undefined' ? __VUE_FLOW_VERSION__ : '-', vueFlowVersion: typeof __VUE_FLOW_VERSION__ !== 'undefined' ? __VUE_FLOW_VERSION__ : '-',
}) })
export const parseElements = (elements: Elements, nodes: Node[], edges: Edge[], nodeExtent: NodeExtent) => { export const parseElements = async (elements: Elements, nodes: Node[], edges: Edge[], nodeExtent: NodeExtent) =>
const nextElements: NextElements = { new Promise<NextElements>((resolve) => {
nextNodes: [], const nextElements: NextElements = {
nextEdges: [], nextNodes: [],
} nextEdges: [],
for (const element of elements) { }
if (isNode(element)) { for (const element of elements) {
const storeNode = nodes[nodes.map((x) => x.id).indexOf(element.id)] if (isNode(element)) {
const storeNode = nodes[nodes.map((x) => x.id).indexOf(element.id)]
if (storeNode) { if (storeNode) {
const updatedNode: Node = { const updatedNode: Node = {
...storeNode, ...storeNode,
...element, ...element,
}
if (!updatedNode.__rf) updatedNode.__rf = {}
if (storeNode.position.x !== element.position.x || storeNode.position.y !== element.position.y) {
updatedNode.__rf.position = element.position
}
if (typeof element.type !== 'undefined' && element.type !== storeNode.type) {
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
updatedNode.__rf.width = undefined
}
nextElements.nextNodes.push(updatedNode)
} else {
nextElements.nextNodes.push(parseNode(element, nodeExtent))
} }
if (!updatedNode.__rf) updatedNode.__rf = {} } else if (isEdge(element)) {
const storeEdge = edges[edges.map((x) => x.id).indexOf(element.id)]
if (storeNode.position.x !== element.position.x || storeNode.position.y !== element.position.y) { if (storeEdge) {
updatedNode.__rf.position = element.position nextElements.nextEdges.push({
...storeEdge,
...element,
})
} else {
nextElements.nextEdges.push(parseEdge(element))
} }
if (typeof element.type !== 'undefined' && element.type !== storeNode.type) {
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
updatedNode.__rf.width = undefined
}
nextElements.nextNodes.push(updatedNode)
} else {
nextElements.nextNodes.push(parseNode(element, nodeExtent))
}
} else if (isEdge(element)) {
const storeEdge = edges[edges.map((x) => x.id).indexOf(element.id)]
if (storeEdge) {
nextElements.nextEdges.push({
...storeEdge,
...element,
})
} else {
nextElements.nextEdges.push(parseEdge(element))
} }
} }
} resolve(nextElements)
})
return nextElements
}
const isObject = (val: any) => val !== null && typeof val === 'object' const isObject = (val: any) => val !== null && typeof val === 'object'
const isArray = Array.isArray const isArray = Array.isArray
+4 -4
View File
@@ -14,8 +14,8 @@ export interface Edge<T = any> {
label?: label?:
| string | string
| { | {
component: any component: Component | DefineComponent
props?: any props?: Record<string, any>
} }
labelStyle?: any labelStyle?: any
labelShowBg?: boolean labelShowBg?: boolean
@@ -48,8 +48,8 @@ export interface EdgeSmoothStepProps<T = any> extends EdgeProps<T> {
borderRadius?: number borderRadius?: number
} }
export type EdgeType = Component<EdgeProps> | DefineComponent<EdgeSmoothStepProps, any, any, any, any, any> | boolean export type EdgeComponent = Component<EdgeProps> | DefineComponent<EdgeSmoothStepProps, any, any, any, any, any> | string
export type EdgeTypes = Record<string, EdgeType> export type EdgeTypes = string[]
export interface EdgePositions { export interface EdgePositions {
sourceX: number sourceX: number
+2 -2
View File
@@ -58,5 +58,5 @@ export interface NodeProps<T = any> {
dragging?: boolean dragging?: boolean
} }
export type NodeType = Component<NodeProps> | DefineComponent<NodeProps, any, any, any, any> | boolean export type NodeComponent = Component<NodeProps> | DefineComponent<NodeProps, any, any, any, any> | string
export type NodeTypes = Record<string, NodeType> export type NodeTypes = string[]
+4 -4
View File
@@ -13,8 +13,8 @@ import {
} from './types' } from './types'
import { HandleType } from './handle' import { HandleType } from './handle'
import { ConnectionMode, OnConnectEndFunc, OnConnectFunc, OnConnectStartFunc, OnConnectStopFunc } from './connection' import { ConnectionMode, OnConnectEndFunc, OnConnectFunc, OnConnectStartFunc, OnConnectStopFunc } from './connection'
import { Edge, EdgeTypes } from './edge' import { Edge, EdgeComponent } from './edge'
import { Node, NodeExtent, NodeTypes, TranslateExtent } from './node' import { Node, NodeComponent, NodeExtent, TranslateExtent } from './node'
import { FlowActions } from './actions' import { FlowActions } from './actions'
import { D3Selection, D3Zoom, D3ZoomHandler } from './panel' import { D3Selection, D3Zoom, D3ZoomHandler } from './panel'
import { FlowHooks } from './hooks' import { FlowHooks } from './hooks'
@@ -67,8 +67,8 @@ export interface FlowState extends FlowOptions {
} }
export interface FlowGetters { export interface FlowGetters {
getEdgeTypes: () => EdgeTypes getEdgeTypes: () => Record<string, EdgeComponent>
getNodeTypes: () => NodeTypes getNodeTypes: () => Record<string, NodeComponent>
getNodes: () => Node[] getNodes: () => Node[]
getEdges: () => Edge[] getEdges: () => Edge[]
} }