fix!: props and composable not merging together properly

* Add getter for node/edge types
* change nodeTypes prop type to only Record<string, NodeType> - same for edges
* Add rgb example
* remove v-model for elements

Signed-off-by: Braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
Braks
2021-11-19 01:19:36 +01:00
parent c8d3ff6a29
commit 70b077a1f5
12 changed files with 286 additions and 157 deletions

View File

@@ -11,7 +11,7 @@ import {
Edge,
Elements,
ConnectionMode,
useStore,
useVueFlow,
} from '~/index'
import './provider.css'
@@ -28,7 +28,7 @@ const initialElements: Elements = [
{ id: 'e1-3', source: '1', target: '3' },
]
useStore()
useVueFlow()
const elements = ref<Elements>(initialElements)
const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value))
const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value))

View File

@@ -0,0 +1,52 @@
<script lang="ts" setup>
import { templateRef } from '@vueuse/core'
import RGBNode from './RGBNode.vue'
import RGBOutputNode from './RGBOutputNode.vue'
import { Elements, FlowInstance, VueFlow, useVueFlow } from '~/index'
type Colors = {
red: number
green: number
blue: number
}
const elements = ref<Elements>([
{ id: '1', type: 'rgb', data: { color: 'r' }, position: { x: -25, y: 50 } },
{ id: '2', type: 'rgb', data: { color: 'g' }, position: { x: 50, y: -100 } },
{ id: '3', type: 'rgb', data: { color: 'b' }, position: { x: 0, y: 200 } },
{ id: '4', type: 'rgb-output', data: { label: 'RGB' }, position: { x: 400, y: 50 } },
{ id: 'e1-4', data: { color: 'red' }, source: '1', target: '4', animated: true },
{ id: 'e2-4', data: { color: 'green' }, source: '2', target: '4', animated: true },
{ id: 'e3-4', data: { color: 'blue' }, source: '3', target: '4', animated: true },
])
const el = templateRef<HTMLDivElement>('page', null)
const onLoad = (flowInstance: FlowInstance) => {
flowInstance.setTransform({ x: el.value?.clientWidth / 2.2, y: el.value?.clientHeight / 3, zoom: 1.25 })
}
const color = ref<Colors>({
red: 100,
green: 150,
blue: 100,
})
const onChange = ({ color: c, val }: { color: keyof Colors; val: number }) => (color.value[c] = Number(val))
const { store } = useVueFlow({
nodeTypes: {
'rgb': true,
'rgb-output': true,
},
zoomOnScroll: false,
})
</script>
<template>
<div ref="page" class="flex demo-flow justify-center items-center h-[80vh] w-full gap-4" style="height: 100%; border-radius: 0">
<VueFlow class="relative font-mono" :elements="elements" @load="onLoad">
<template #node-rgb="props">
<RGBNode v-bind="props" :amount="color" @change="onChange" />
</template>
<template #node-rgb-output="props">
<RGBOutputNode :v-bind="props" :rgb="`rgb(${color.red}, ${color.green}, ${color.blue})`" />
</template>
</VueFlow>
</div>
</template>

View File

@@ -0,0 +1,64 @@
<script lang="ts" setup>
import { Handle, NodeProps, Position } from '~/index'
interface RGBNodeProps extends NodeProps {
data: {
color: 'r' | 'g' | 'b'
}
amount: {
red: number
green: number
blue: number
}
}
const props = defineProps<RGBNodeProps>()
const emit = defineEmits(['change'])
let color = 'red'
switch (props.data.color) {
case 'r':
color = 'red'
break
case 'g':
color = 'green'
break
case 'b':
color = 'blue'
break
}
const onChange = (e: any) => emit('change', { color, val: e.target.value })
console.log('rgb')
</script>
<template>
<div class="px-4 py-2 bg-white rounded-md border-2 border-solid border-black text-left transform scale-75 lg:scale-100">
<div class="text-md" :style="{ color }">{{ `${color} Amount`.toUpperCase() }}</div>
<input
v-model="props.amount[color]"
class="slider nodrag"
:style="{ '--color': color }"
type="range"
min="0"
max="255"
@input="onChange"
/>
<Handle type="source" :position="Position.Right" :style="{ backgroundColor: color }" />
</div>
</template>
<style>
.slider {
--color: red;
@apply bg-gray-200 w-full h-[10px] outline-none rounded-full;
-webkit-appearance: none;
appearance: none;
&::-moz-range-thumb {
@apply w-[15px] h-[15px] cursor-pointer border-1 border-solid border-white rounded-full;
-webkit-appearance: none;
background: var(--color);
}
&::-webkit-slider-thumb {
@apply w-[15px] h-[15px] cursor-pointer border-1 border-solid border-white rounded-full;
-webkit-appearance: none;
background: var(--color);
}
}
</style>

View File

@@ -0,0 +1,15 @@
<script lang="ts" setup>
import { Handle, NodeProps, Position } from '~/index'
interface RBGOutputNodeProps extends NodeProps {
rgb: string
}
const props = defineProps<RBGOutputNodeProps>()
</script>
<template>
<div :style="{ backgroundColor: props.rgb }" class="p-3 rounded-xl text-left text-white">
<div class="text-md uppercase">{{ props.rgb }}</div>
<Handle type="source" :position="Position.Left" />
</div>
</template>

View File

@@ -5,6 +5,10 @@ export const routes: RouterOptions['routes'] = [
path: '/',
redirect: '/overview',
},
{
path: '/rgb',
component: () => import('./RGBFlow/RGBFlow.vue'),
},
{
path: '/basic',
component: () => import('./Basic/Basic.vue'),

View File

@@ -1,13 +1,12 @@
<script lang="ts" setup>
import { CSSProperties } from 'vue'
import { ConnectionLineType, EdgeType } from '../../types'
import { ConnectionLineType, Edge as TEdge } from '../../types'
import { useStore } from '../../composables'
import Edge from '../../components/Edges/Edge.vue'
import ConnectionLine from '../../components/ConnectionLine/ConnectionLine.vue'
import MarkerDefinitions from './MarkerDefinitions.vue'
interface EdgeRendererProps {
edgeTypes: Record<string, EdgeType>
connectionLineType?: ConnectionLineType
connectionLineStyle?: CSSProperties
arrowHeadColor?: string
@@ -27,21 +26,23 @@ const sourceNode = computed(() => store.nodes.find((n) => n.id === store.connect
const connectionLineVisible = computed(
() => !!(store.nodesConnectable && sourceNode.value && store.connectionNodeId && store.connectionHandleType),
)
const edges = computed(() => store.edges.filter((edge) => !edge.isHidden))
const dimensions = computed(() => store.dimensions)
const transform = computed(() => `translate(${store.transform[0]},${store.transform[1]}) scale(${store.transform[2]})`)
const type = (edge: TEdge) => {
const edgeType = edge.type || 'default'
const type = store.getEdgeTypes[edgeType] || store.getEdgeTypes.default
if (!store.getEdgeTypes[edgeType]) {
console.warn(`Edge type "${edgeType}" not found. Using fallback type "default".`)
}
return type
}
</script>
<template>
<svg :width="dimensions.width" :height="dimensions.height" class="vue-flow__edges">
<MarkerDefinitions :color="props.arrowHeadColor" />
<g :transform="transform">
<template v-for="edge of edges" :key="edge.id">
<Edge
:edge="edge"
:type="props.edgeTypes[edge.type || 'default']"
:marker-end-id="props.markerEndId"
:edge-updater-radius="props.edgeUpdaterRadius"
>
<template v-for="edge of store.getEdges" :key="edge.id">
<Edge :edge="edge" :type="type(edge)" :marker-end-id="props.markerEndId" :edge-updater-radius="props.edgeUpdaterRadius">
<template #default="edgeProps">
<slot :name="`edge-${edge.type}`" v-bind="edgeProps"></slot>
</template>

View File

@@ -1,11 +1,9 @@
<script lang="ts" setup>
import { NodeType, Node as TNode } from '../../types'
import { Node as TNode } from '../../types'
import { useStore } from '../../composables'
import Node from '../../components/Nodes/Node.vue'
import { getNodesInside } from '~/utils'
interface NodeRendererProps {
nodeTypes: Record<string, NodeType>
selectNodesOnDrag?: boolean
}
@@ -15,31 +13,13 @@ const props = withDefaults(defineProps<NodeRendererProps>(), {
const store = useStore()
const nodes = computed(() => {
const n = store.onlyRenderVisibleElements
? store.nodes &&
getNodesInside(
store.nodes,
{
x: 0,
y: 0,
width: store.dimensions.width,
height: store.dimensions.height,
},
store.transform,
true,
)
: store.nodes
return n.filter((node) => !node.isHidden)
})
const transform = computed(() => `translate(${store.transform[0]}px,${store.transform[1]}px) scale(${store.transform[2]})`)
const snapGrid = computed(() => (store.snapToGrid ? store.snapGrid : undefined))
const type = (node: TNode) => {
const nodeType = node.type || 'default'
const type = props.nodeTypes[nodeType] || props.nodeTypes.default
if (!props.nodeTypes[nodeType]) {
const type = store.getNodeTypes[nodeType] || store.getNodeTypes.default
if (!store.getNodeTypes[nodeType]) {
console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`)
}
return type
@@ -49,7 +29,7 @@ const selected = (nodeId: string) => store.selectedElements?.some(({ id }) => id
<template>
<div class="vue-flow__nodes" :style="{ transform }">
<Suspense>
<template v-for="node of nodes" :key="node.id">
<template v-for="node of store.getNodes" :key="node.id">
<Node
:node="node"
:type="type(node)"

View File

@@ -18,14 +18,12 @@ import ZoomPane from '../../container/ZoomPane/ZoomPane.vue'
import SelectionPane from '../../container/SelectionPane/SelectionPane.vue'
import NodeRenderer from '../../container/NodeRenderer/NodeRenderer.vue'
import EdgeRenderer from '../../container/EdgeRenderer/EdgeRenderer.vue'
import { DefaultNode, InputNode, OutputNode } from '../../components/Nodes'
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge } from '../../components/Edges'
import { createHooks, initFlow } from '../../composables'
export interface FlowProps extends FlowOptions {
elements: Elements
nodeTypes?: Record<string, NodeType> | string[]
edgeTypes?: Record<string, EdgeType> | string[]
nodeTypes?: Record<string, NodeType>
edgeTypes?: Record<string, EdgeType>
connectionMode?: ConnectionMode
connectionLineType?: ConnectionLineType
connectionLineStyle?: CSSProperties
@@ -58,7 +56,7 @@ export interface FlowProps extends FlowOptions {
edgeUpdaterRadius?: number
edgeTypesId?: string
nodeTypesId?: string
storage?: string
storageKey?: string
}
const props = withDefaults(defineProps<FlowProps>(), {
@@ -103,30 +101,19 @@ const props = withDefaults(defineProps<FlowProps>(), {
const emit = defineEmits(Object.keys(createHooks()))
const defaultNodeTypes: Record<string, NodeType> = {
input: InputNode as NodeType,
default: DefaultNode as NodeType,
output: OutputNode as NodeType,
}
const defaultEdgeTypes: Record<string, EdgeType> = {
default: BezierEdge as EdgeType,
straight: StraightEdge as EdgeType,
step: StepEdge as EdgeType,
smoothstep: SmoothStepEdge as EdgeType,
}
const { store, hooks } = initFlow(emit, props)
const init = (opts: typeof props) => {
store.$state = { ...store.$state, ...(props as any) }
store.elements = opts.elements
for (const opt of Object.keys(opts)) {
const val = opts[opt as keyof FlowProps]
if (val && typeof val !== 'undefined') (store.$state as any)[opt] = val
}
store.setElements(store.elements)
store.setMinZoom(opts.minZoom)
store.setMaxZoom(opts.maxZoom)
store.setTranslateExtent(opts.translateExtent)
store.setNodeExtent(opts.nodeExtent)
}
const elements = useVModel(props, 'elements', emit)
onBeforeUnmount(() => store?.$dispose())
watch(
@@ -141,32 +128,6 @@ invoke(async () => {
await until(props.elements).toMatch((y) => y.length > 0)
init(props)
})
watch(
elements,
(val, oldVal) => {
nextTick(() => {
const hasDiff = diff(val, oldVal)
if (hasDiff.length > 0) store.setElements(val)
})
},
{ flush: 'post', deep: true },
)
const nodeTypes = computed(() => {
let types = defaultNodeTypes
if (Array.isArray(props.nodeTypes)) props.nodeTypes.forEach((type) => (types[type] = true))
else types = { ...types, ...props.nodeTypes }
store.$state.nodeTypes = types
return types
})
const edgeTypes = computed(() => {
let types = defaultEdgeTypes
if (Array.isArray(props.edgeTypes)) props.edgeTypes.forEach((type) => (types[type] = true))
else types = { ...types, ...props.edgeTypes }
store.$state.edgeTypes = types
return types
})
</script>
<template>
<div class="vue-flow">
@@ -190,8 +151,8 @@ const edgeTypes = computed(() => {
:multi-selection-key-code="props.multiSelectionKeyCode"
:selection-key-code="props.selectionKeyCode"
>
<NodeRenderer :node-types="nodeTypes" :select-nodes-on-drag="props.selectNodesOnDrag">
<template v-for="nodeName of Object.keys(nodeTypes)" #[`node-${nodeName}`]="nodeProps">
<NodeRenderer :select-nodes-on-drag="props.selectNodesOnDrag">
<template v-for="nodeName of Object.keys(store.getNodeTypes)" #[`node-${nodeName}`]="nodeProps">
<slot :name="`node-${nodeName}`" v-bind="nodeProps"></slot>
</template>
</NodeRenderer>
@@ -200,9 +161,8 @@ const edgeTypes = computed(() => {
:connection-line-style="props.connectionLineStyle"
:arrow-head-color="props.arrowHeadColor"
:marker-end-id="props.markerEndId"
:edge-types="edgeTypes"
>
<template v-for="edgeName of Object.keys(edgeTypes)" #[`edge-${edgeName}`]="edgeProps">
<template v-for="edgeName of Object.keys(store.getEdgeTypes)" #[`edge-${edgeName}`]="edgeProps">
<slot :name="`edge-${edgeName}`" v-bind="edgeProps"></slot>
</template>
<template #custom-connection-line="customConnectionLineProps">

View File

@@ -1,73 +1,31 @@
import { setActivePinia, createPinia, defineStore, StoreDefinition } from 'pinia'
import diff from 'microdiff'
import { Edge, FlowState, Node, FlowActions, Elements, NodeExtent } from '~/types'
import {
clampPosition,
getDimensions,
getConnectedEdges,
getNodesInside,
getRectOfNodes,
isEdge,
isNode,
parseEdge,
parseNode,
} from '~/utils'
import { parseElements } from './utils'
import { FlowState, Node, FlowActions, Elements, NodeType, EdgeType, FlowGetters, Edge } from '~/types'
import { clampPosition, getDimensions, getConnectedEdges, getNodesInside, getRectOfNodes, isNode } from '~/utils'
import { getHandleBounds } from '~/components/Nodes/utils'
import { DefaultNode, InputNode, OutputNode } from '~/components/Nodes'
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge } from '~/components/Edges'
type NextElements = {
nextNodes: Node[]
nextEdges: Edge[]
const defaultNodeTypes: Record<string, NodeType> = {
input: InputNode as NodeType,
default: DefaultNode as NodeType,
output: OutputNode as NodeType,
}
const defaultEdgeTypes: Record<string, EdgeType> = {
default: BezierEdge as EdgeType,
straight: StraightEdge as EdgeType,
step: StepEdge as EdgeType,
smoothstep: SmoothStepEdge as EdgeType,
}
const pinia = createPinia()
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.find((node) => node.id === element.id)
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))
}
} else if (isEdge(element)) {
const storeEdge = edges.find((se) => se.id === element.id)
if (storeEdge) {
nextElements.nextEdges.push({
...storeEdge,
...element,
})
} else {
nextElements.nextEdges.push(parseEdge(element))
}
}
}
return nextElements
}
export default function flowStore(id: string, preloadedState: FlowState): StoreDefinition<string, FlowState, any, FlowActions> {
export default function flowStore(
id: string,
preloadedState: FlowState,
): StoreDefinition<string, FlowState, FlowGetters, FlowActions> {
setActivePinia(pinia)
const { nextEdges, nextNodes } = parseElements(preloadedState.elements, [], [], preloadedState.nodeExtent)
preloadedState.nodes = nextNodes
@@ -78,7 +36,41 @@ export default function flowStore(id: string, preloadedState: FlowState): StoreD
state: () => ({
...preloadedState,
}),
getters: {},
getters: {
getEdgeTypes() {
let edgeTypes = defaultEdgeTypes
if (Array.isArray(this.edgeTypes)) this.edgeTypes.forEach((type) => (edgeTypes[type] = true))
else edgeTypes = { ...edgeTypes, ...this.edgeTypes }
return edgeTypes
},
getNodeTypes() {
let nodeTypes = defaultNodeTypes
if (Array.isArray(this.nodeTypes)) this.nodeTypes.forEach((type) => (nodeTypes[type] = true))
else nodeTypes = { ...nodeTypes, ...this.nodeTypes }
return nodeTypes
},
getNodes() {
const n: Node[] = this.onlyRenderVisibleElements
? this.nodes &&
getNodesInside(
this.nodes,
{
x: 0,
y: 0,
width: this.dimensions.width,
height: this.dimensions.height,
},
this.transform,
true,
)
: this.nodes
return n.filter((node) => !node.isHidden)
},
getEdges(): Edge[] {
return this.edges.filter((edge) => !edge.isHidden)
},
},
actions: {
setElements(elements) {
const { nextNodes, nextEdges } = parseElements(elements, this.nodes, this.edges, this.nodeExtent)

54
src/store/utils.ts Normal file
View File

@@ -0,0 +1,54 @@
import { Edge, Elements, Node, NodeExtent } from '~/types'
import { isEdge, isNode, parseEdge, parseNode } from '~/utils'
type NextElements = {
nextNodes: Node[]
nextEdges: Edge[]
}
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.find((node) => node.id === element.id)
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))
}
} else if (isEdge(element)) {
const storeEdge = edges.find((se) => se.id === element.id)
if (storeEdge) {
nextElements.nextEdges.push({
...storeEdge,
...element,
})
} else {
nextElements.nextEdges.push(parseEdge(element))
}
}
}
return nextElements
}

View File

@@ -13,9 +13,9 @@ export interface FlowState extends FlowOptions {
transform: Transform
elements: Elements
nodes: Node[]
nodeTypes: Record<string, NodeType> | string[]
nodeTypes: Record<string, NodeType>
edges: Edge[]
edgeTypes: Record<string, EdgeType> | string[]
edgeTypes: Record<string, EdgeType>
selectedElements?: Elements
selectedNodesBbox: Rect
@@ -59,4 +59,11 @@ export interface FlowState extends FlowOptions {
storageKey?: string
}
export type FlowStore = Store<string, FlowState, any, FlowActions>
export interface FlowGetters {
getEdgeTypes: () => Record<string, EdgeType>
getNodeTypes: () => Record<string, NodeType>
getNodes: () => Node[]
getEdges: () => Edge[]
}
export type FlowStore = Store<string, FlowState, FlowGetters, FlowActions>

View File

@@ -90,8 +90,8 @@ export type FlowInstance<T = any> = {
export interface FlowOptions extends Omit<HTMLAttributes, 'onLoad'> {
elements: Elements
nodeTypes?: Record<string, NodeType> | string[]
edgeTypes?: Record<string, EdgeType> | string[]
nodeTypes?: Record<string, NodeType>
edgeTypes?: Record<string, EdgeType>
connectionMode?: ConnectionMode
connectionLineType?: ConnectionLineType
connectionLineStyle?: CSSProperties