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
+7 -5
View File
@@ -16,13 +16,15 @@ const props = withDefaults(defineProps<EdgeProps>(), {})
const store = useStore()
const type = computed(() => {
const edgeType = props.edge.type || 'default'
const t = store.getEdgeTypes[edgeType] || store.getEdgeTypes.default
if (!store.getEdgeTypes[edgeType]) {
console.warn(`Edge type "${edgeType}" not found. Using fallback type "default".`)
const t = props.edge.type ?? 'default'
let edge = store.getEdgeTypes[t]
if (!edge) {
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 onEdgeClick = (event: MouseEvent) => {
+6 -6
View File
@@ -21,12 +21,13 @@ provide(NodeId, props.node.id)
const nodeElement = templateRef<HTMLDivElement>('node-element', null)
const type = computed(() => {
const nodeType = props.node.type ?? 'default'
const t = store.getNodeTypes[nodeType] || store.getNodeTypes.default
if (!store.getNodeTypes[nodeType]) {
console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`)
const t = props.node.type ?? 'default'
let node = store.getNodeTypes[t]
if (!node) {
node = store.getNodeTypes.default
console.warn(`Node type "${t}" not found. Using fallback type "default".`)
}
return t
return node
})
const selectable = computed(() =>
@@ -192,7 +193,6 @@ onMounted(() => {
>
<component
:is="type"
v-if="typeof type !== 'boolean'"
v-bind="{
id: props.node.id,
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)
preloadedState.transform = [storedState.value.position[0], storedState.value.position[1], storedState.value.zoom]
}
console.log(storedState.value)
}
store = useStateStore(storageKey, preloadedState)()
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" />
<g :transform="transform">
<Edge
v-for="edge of store.getEdges"
:key="edge.id"
v-for="(edge, i) of store.getEdges"
:key="`${edge.id}-${i}`"
:edge="edge"
:marker-end-id="props.markerEndId"
:edge-updater-radius="props.edgeUpdaterRadius"
+10 -31
View File
@@ -30,7 +30,6 @@ export interface FlowProps extends Partial<FlowOptions> {
id?: string
store?: FlowStore
modelValue?: Elements
elements?: Elements
nodeTypes?: NodeTypes
edgeTypes?: EdgeTypes
connectionMode?: ConnectionMode
@@ -72,7 +71,6 @@ const emit = defineEmits([...Object.keys(createHooks()), 'update:elements', 'upd
const props = withDefaults(defineProps<FlowProps>(), {
modelValue: () => [],
elements: () => [],
connectionMode: ConnectionMode.Loose,
connectionLineType: ConnectionLineType.Bezier,
selectionKeyCode: 'Shift',
@@ -111,18 +109,18 @@ const props = withDefaults(defineProps<FlowProps>(), {
worker: false,
})
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 options = Object.assign({}, props, store.$state)
const elements = useVModel(props, 'modelValue', emit)
// if there are preloaded elements we overwrite the current elements with the stored ones
if (store.elements.length) elements.value = store.elements
const options = Object.assign({}, store.$state, props)
const init = (state: FlowState) => {
// set state variables
for (const opt of Object.keys(state)) {
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)) {
;(store as any)[opt] = { ...(store as any)[opt], ...val }
} else (store as any)[opt] = val
@@ -157,32 +155,13 @@ invoke(async () => {
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(() => {
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(
() => props,
(val, oldVal) => {
const hasDiff = diff(val, oldVal)
// when props changed we want to update state variables
if (hasDiff.length > 0) init({ ...store.$state, ...props } as FlowState)
},
() => init({ ...store.$state, ...props } as FlowState),
{ flush: 'post', deep: true },
)
})
@@ -252,8 +231,8 @@ const transitionName = computed(() => {
<slot name="zoom-pane" v-bind="zoomPaneProps"></slot>
</template>
</ZoomPane>
<template #fallback>
<slot v-if="store.loading" key="loading-indicator" name="loading-indicator">
<template v-if="store.loading" #fallback>
<slot key="loading-indicator" name="loading-indicator">
<LoadingIndicator key="default-loading-indicator" v-bind="store.loading">
<slot name="loading-label" />
</LoadingIndicator>
+19 -11
View File
@@ -1,7 +1,7 @@
import { setActivePinia, createPinia, defineStore, StoreDefinition } from 'pinia'
import diff from 'microdiff'
import { parseElements, defaultNodeTypes, defaultEdgeTypes, deepUnref } from './utils'
import { FlowState, Node, FlowActions, Elements, FlowGetters, Edge, EdgeTypes, NodeTypes } from '~/types'
import { parseElements, defaultNodeTypes, defaultEdgeTypes, deepUnref, NextElements } from './utils'
import { FlowState, Node, FlowActions, Elements, FlowGetters, Edge } from '~/types'
import { clampPosition, getDimensions, getConnectedEdges, getNodesInside, getRectOfNodes, isNode } from '~/utils'
import { getHandleBounds } from '~/components/Nodes/utils'
import parseElementsWorker from '~/workers/parseElements'
@@ -20,11 +20,19 @@ export default function flowStore(
...preloadedState,
}),
getters: {
getEdgeTypes(): EdgeTypes {
return { ...defaultEdgeTypes, ...this.edgeTypes }
getEdgeTypes() {
const edgeTypes: Record<string, any> = {
...defaultEdgeTypes,
}
this.edgeTypes?.forEach((n) => (edgeTypes[n] = n))
return edgeTypes
},
getNodeTypes(): NodeTypes {
return { ...defaultNodeTypes, ...this.nodeTypes }
getNodeTypes() {
const nodeTypes: Record<string, any> = {
...defaultNodeTypes,
}
this.nodeTypes?.forEach((n) => (nodeTypes[n] = n))
return nodeTypes
},
getNodes(): Node[] {
const n = this.onlyRenderVisibleElements
@@ -50,12 +58,12 @@ export default function flowStore(
},
actions: {
async setElements(elements) {
let next: any = {
let next: NextElements = {
nextEdges: [],
nextNodes: [],
}
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) {
const { workerFn, workerTerminate } = parseElementsWorker()
const res = await workerFn(
@@ -70,7 +78,7 @@ export default function flowStore(
if (res) {
workerTerminate('SUCCESS')
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) {
this.elements = elements ?? []
@@ -255,8 +263,8 @@ export default function flowStore(
this.nodesConnectable = isInteractive
this.elementsSelectable = isInteractive
},
addElements(elements: Elements) {
const { nextNodes, nextEdges } = parseElements(elements, this.nodes, this.edges, this.nodeExtent)
async addElements(elements: Elements) {
const { nextNodes, nextEdges } = await parseElements(elements, this.nodes, this.edges, this.nodeExtent)
this.elements = [...this.elements, ...elements]
this.nodes = [...this.nodes, ...nextNodes]
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 { DefaultNode, InputNode, OutputNode } from '~/components/Nodes'
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge } from '~/components/Edges'
import { createHooks } from '~/composables'
type NextElements = {
export type NextElements = {
nextNodes: Node[]
nextEdges: Edge[]
}
export const defaultNodeTypes: NodeTypes = {
input: markRaw(InputNode),
default: markRaw(DefaultNode),
output: markRaw(OutputNode),
export const defaultNodeTypes: Record<string, Component<NodeProps>> = {
input: InputNode,
default: DefaultNode,
output: OutputNode,
}
export const defaultEdgeTypes: EdgeTypes = {
default: markRaw(BezierEdge),
straight: markRaw(StraightEdge),
step: markRaw(StepEdge),
smoothstep: markRaw(SmoothStepEdge),
export const defaultEdgeTypes: Record<string, Component<EdgeProps>> = {
default: BezierEdge,
straight: StraightEdge,
step: StepEdge,
smoothstep: SmoothStepEdge,
}
export const initialState = (): FlowState => ({
@@ -93,52 +94,52 @@ export const initialState = (): FlowState => ({
vueFlowVersion: typeof __VUE_FLOW_VERSION__ !== 'undefined' ? __VUE_FLOW_VERSION__ : '-',
})
export const parseElements = (elements: Elements, nodes: Node[], edges: Edge[], nodeExtent: NodeExtent) => {
const nextElements: NextElements = {
nextNodes: [],
nextEdges: [],
}
for (const element of elements) {
if (isNode(element)) {
const storeNode = nodes[nodes.map((x) => x.id).indexOf(element.id)]
export const parseElements = async (elements: Elements, nodes: Node[], edges: Edge[], nodeExtent: NodeExtent) =>
new Promise<NextElements>((resolve) => {
const nextElements: NextElements = {
nextNodes: [],
nextEdges: [],
}
for (const element of elements) {
if (isNode(element)) {
const storeNode = nodes[nodes.map((x) => x.id).indexOf(element.id)]
if (storeNode) {
const updatedNode: Node = {
...storeNode,
...element,
if (storeNode) {
const updatedNode: Node = {
...storeNode,
...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) {
updatedNode.__rf.position = element.position
if (storeEdge) {
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))
}
}
}
return nextElements
}
resolve(nextElements)
})
const isObject = (val: any) => val !== null && typeof val === 'object'
const isArray = Array.isArray
+4 -4
View File
@@ -14,8 +14,8 @@ export interface Edge<T = any> {
label?:
| string
| {
component: any
props?: any
component: Component | DefineComponent
props?: Record<string, any>
}
labelStyle?: any
labelShowBg?: boolean
@@ -48,8 +48,8 @@ export interface EdgeSmoothStepProps<T = any> extends EdgeProps<T> {
borderRadius?: number
}
export type EdgeType = Component<EdgeProps> | DefineComponent<EdgeSmoothStepProps, any, any, any, any, any> | boolean
export type EdgeTypes = Record<string, EdgeType>
export type EdgeComponent = Component<EdgeProps> | DefineComponent<EdgeSmoothStepProps, any, any, any, any, any> | string
export type EdgeTypes = string[]
export interface EdgePositions {
sourceX: number
+2 -2
View File
@@ -58,5 +58,5 @@ export interface NodeProps<T = any> {
dragging?: boolean
}
export type NodeType = Component<NodeProps> | DefineComponent<NodeProps, any, any, any, any> | boolean
export type NodeTypes = Record<string, NodeType>
export type NodeComponent = Component<NodeProps> | DefineComponent<NodeProps, any, any, any, any> | string
export type NodeTypes = string[]
+4 -4
View File
@@ -13,8 +13,8 @@ import {
} from './types'
import { HandleType } from './handle'
import { ConnectionMode, OnConnectEndFunc, OnConnectFunc, OnConnectStartFunc, OnConnectStopFunc } from './connection'
import { Edge, EdgeTypes } from './edge'
import { Node, NodeExtent, NodeTypes, TranslateExtent } from './node'
import { Edge, EdgeComponent } from './edge'
import { Node, NodeComponent, NodeExtent, TranslateExtent } from './node'
import { FlowActions } from './actions'
import { D3Selection, D3Zoom, D3ZoomHandler } from './panel'
import { FlowHooks } from './hooks'
@@ -67,8 +67,8 @@ export interface FlowState extends FlowOptions {
}
export interface FlowGetters {
getEdgeTypes: () => EdgeTypes
getNodeTypes: () => NodeTypes
getEdgeTypes: () => Record<string, EdgeComponent>
getNodeTypes: () => Record<string, NodeComponent>
getNodes: () => Node[]
getEdges: () => Edge[]
}