refactor(flow)!: properly nest components

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 6bdea72b20
commit c96f62f622
12 changed files with 121 additions and 149 deletions
+6 -8
View File
@@ -25,13 +25,11 @@ const sourceHandleStyleB: CSSProperties = { ...targetHandleStyle, bottom: '10px'
const onConnect = (params: Connection | Edge) => console.log('handle onConnect', params) const onConnect = (params: Connection | Edge) => console.log('handle onConnect', params)
</script> </script>
<template> <template>
<div class="vue-flow__node-color-selector"> <Handle type="target" :position="Position.Left" :style="targetHandleStyle" :on-connect="onConnect" />
<Handle type="target" :position="Position.Left" :style="targetHandleStyle" :on-connect="onConnect" /> <div>
<div> Custom Color Picker Node: <strong>{{ data.color }}</strong>
Custom Color Picker Node: <strong>{{ data.color }}</strong>
</div>
<input class="nodrag" type="color" :value="data.color" @input="props.data.onChange" />
<Handle id="a" type="source" :position="Position.Right" :style="sourceHandleStyleA" />
<Handle id="b" type="source" :position="Position.Right" :style="sourceHandleStyleB" />
</div> </div>
<input class="nodrag" type="color" :value="data.color" @input="props.data.onChange" />
<Handle id="a" type="source" :position="Position.Right" :style="sourceHandleStyleA" />
<Handle id="b" type="source" :position="Position.Right" :style="sourceHandleStyleB" />
</template> </template>
+3 -3
View File
@@ -63,7 +63,7 @@ onMounted(() => {
{ {
id: '1', id: '1',
type: 'input', type: 'input',
data: { label: 'An input node' }, label: 'An input node',
position: { x: 0, y: 50 }, position: { x: 0, y: 50 },
sourcePosition: Position.Right, sourcePosition: Position.Right,
}, },
@@ -77,14 +77,14 @@ onMounted(() => {
{ {
id: '3', id: '3',
type: 'output', type: 'output',
data: { label: 'Output A' }, label: 'Output A',
position: { x: 650, y: 25 }, position: { x: 650, y: 25 },
targetPosition: Position.Left, targetPosition: Position.Left,
}, },
{ {
id: '4', id: '4',
type: 'output', type: 'output',
data: { label: 'Output B' }, label: 'Output B',
position: { x: 650, y: 100 }, position: { x: 650, y: 100 },
targetPosition: Position.Left, targetPosition: Position.Left,
}, },
+1 -1
View File
@@ -17,7 +17,7 @@ interface CustomEdgeProps<T = any> extends EdgeProps<T> {
const props = defineProps<CustomEdgeProps>() const props = defineProps<CustomEdgeProps>()
const store = useVueFlow() const store = useVueFlow()
const onEdgeClick = (evt: Event, id: string) => { const onEdgeClick = (evt: Event, id: string) => {
const edge = store.getEdges.find((edge) => edge.id === id) const edge = store.getEdge(id)
if (edge) { if (edge) {
store.hooks.elementsRemove.trigger([edge]) store.hooks.elementsRemove.trigger([edge])
} }
+3 -3
View File
@@ -29,10 +29,10 @@ const addRandomNode = () => {
const nodeId = (elements.value.length + 1).toString() const nodeId = (elements.value.length + 1).toString()
const newNode: Node = { const newNode: Node = {
id: nodeId, id: nodeId,
data: { label: `Node: ${nodeId}` }, label: `Node: ${nodeId}`,
position: { x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight }, position: { x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight },
} as Node } as Node
elements.value = [...elements.value, newNode] elements.value.push(newNode)
} }
</script> </script>
<template> <template>
@@ -41,7 +41,7 @@ const addRandomNode = () => {
@load="onLoad" @load="onLoad"
@element-click="onElementClick" @element-click="onElementClick"
@elements-remove="onElementsRemove" @elements-remove="onElementsRemove"
@connect="(p) => onConnect(p)" @connect="onConnect"
@node-drag-stop="onNodeDragStop" @node-drag-stop="onNodeDragStop"
> >
<MiniMap /> <MiniMap />
+3 -58
View File
@@ -1,21 +1,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import { CSSProperties } from 'vue'
import { getElements } from './utils' import { getElements } from './utils'
import { import { VueFlow, FlowInstance } from '~/index'
VueFlow,
removeElements,
addEdge,
MiniMap,
isNode,
Controls,
Background,
FlowInstance,
Elements,
Connection,
Edge,
} from '~/index'
const buttonWrapperStyles: CSSProperties = { position: 'absolute', right: 10, top: 10, zIndex: 4 }
const instance = ref<FlowInstance>() const instance = ref<FlowInstance>()
const onLoad = (flowInstance: FlowInstance) => { const onLoad = (flowInstance: FlowInstance) => {
@@ -24,50 +9,10 @@ const onLoad = (flowInstance: FlowInstance) => {
console.log(flowInstance.getNodes()) console.log(flowInstance.getNodes())
} }
const initialElements: Elements = getElements(50, 20) const { nodes, edges } = getElements(5, 5)
const elements = ref(initialElements)
const onConnect = (params: Connection | Edge) => (elements.value = addEdge(params, elements.value))
const onElementsRemove = (elementsToRemove: Elements) => (elements.value = removeElements(elementsToRemove, elements.value))
const updatePos = () => {
elements.value = elements.value.map((el) => {
if (isNode(el)) {
return {
...el,
position: {
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight,
},
}
}
return el
})
}
const updateElements = () => {
const grid = Math.ceil(Math.random() * 10)
elements.value = getElements(grid, grid)
setTimeout(() => instance.value.fitView({ padding: 0.5 }))
}
</script> </script>
<template> <template>
<VueFlow <VueFlow :nodes="nodes" :edges="edges" @load="onLoad"> </VueFlow>
v-model="elements"
loading="One moment please..."
@load="onLoad"
@elementsRemove="onElementsRemove"
@connect="onConnect"
>
<MiniMap />
<Controls />
<Background />
<div :style="buttonWrapperStyles">
<button style="margin-right: 5px" @click="updatePos">change pos</button>
<button @click="updateElements">update elements</button>
</div>
</VueFlow>
</template> </template>
<style> <style>
.fade-enter-active, .fade-enter-active,
+11 -8
View File
@@ -1,24 +1,24 @@
import { Elements } from '~/index' import { Edge, Node } from '~/index'
export function getElements(xElements = 10, yElements = 10): Elements { export function getElements(xElements = 10, yElements = 10) {
const initialElements = [] const initialNodes: Node[] = []
const initialEdges: Edge[] = []
let nodeId = 1 let nodeId = 1
let recentNodeId = null let recentNodeId = null
for (let y = 0; y < yElements; y++) { for (let y = 0; y < yElements; y++) {
for (let x = 0; x < xElements; x++) { for (let x = 0; x < xElements; x++) {
const position = { x: x * 100, y: y * 50 } const position = { x: x * 100, y: y * 50 }
const data = { label: `Node ${nodeId}` }
const node = { const node = {
id: nodeId.toString(), id: nodeId.toString(),
style: { width: 50, fontSize: 11 }, style: { width: 50, fontSize: 11 },
data, label: `Node ${nodeId}`,
position, position,
} }
initialElements.push(node) initialNodes.push(node)
if (recentNodeId && nodeId <= xElements * yElements) { if (recentNodeId && nodeId <= xElements * yElements) {
initialElements.push({ id: `${x}-${y}`, source: recentNodeId.toString(), target: nodeId.toString() }) initialEdges.push({ id: `${x}-${y}`, source: recentNodeId.toString(), target: nodeId.toString() })
} }
recentNodeId = nodeId recentNodeId = nodeId
@@ -26,5 +26,8 @@ export function getElements(xElements = 10, yElements = 10): Elements {
} }
} }
return initialElements return {
nodes: initialNodes,
edges: initialEdges,
}
} }
+1 -1
View File
@@ -85,7 +85,7 @@ export default (store: FlowStore = useStore()) =>
if (!doc) return if (!doc) return
let validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true) let validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true)
if (!isValidConnection) { if (!isValidConnection) {
const node = store.getNodes.find((n) => n.id === nodeId) const node = store.getNode(nodeId)
if (node) validConnectFunc = (!isTarget ? node.isValidTargetPos : node.isValidSourcePos) ?? (() => true) if (node) validConnectFunc = (!isTarget ? node.isValidTargetPos : node.isValidSourcePos) ?? (() => true)
} }
const elementBelow = doc.elementFromPoint(event.clientX, event.clientY) const elementBelow = doc.elementFromPoint(event.clientX, event.clientY)
+20 -1
View File
@@ -2,6 +2,7 @@
import { useStore, useWindow, useZoomPanHelper } from '../../composables' import { useStore, useWindow, useZoomPanHelper } from '../../composables'
import { FlowInstance } from '../../types' import { FlowInstance } from '../../types'
import { onLoadGetEdges, onLoadGetElements, onLoadGetNodes, onLoadProject, onLoadToObject } from '../../utils' import { onLoadGetEdges, onLoadGetElements, onLoadGetNodes, onLoadProject, onLoadToObject } from '../../utils'
import ZoomPane from '../ZoomPane/ZoomPane.vue'
const store = useStore() const store = useStore()
@@ -36,6 +37,24 @@ export default {
</script> </script>
<template> <template>
<div class="vue-flow__renderer"> <div class="vue-flow__renderer">
<slot /> <ZoomPane :key="`zoom-pane-${store.id}`">
<template
v-for="nodeName of Object.keys(store.getNodeTypes)"
#[`node-${nodeName}`]="nodeProps"
:key="`node-${nodeName}-${store.id}`"
>
<slot :name="`node-${nodeName}`" v-bind="nodeProps" />
</template>
<template
v-for="edgeName of Object.keys(store.getEdgeTypes)"
#[`edge-${edgeName}`]="edgeProps"
:key="`edge-${edgeName}-${store.id}`"
>
<slot :name="`edge-${edgeName}`" v-bind="edgeProps" />
</template>
<template #custom-connection-line="customConnectionLineProps">
<slot name="custom-connection-line" v-bind="customConnectionLineProps" />
</template>
</ZoomPane>
</div> </div>
</template> </template>
+23 -1
View File
@@ -4,6 +4,8 @@ import { useStore, useKeyPress } from '../../composables'
import { getConnectedEdges } from '../../utils' import { getConnectedEdges } from '../../utils'
import NodesSelection from '../../components/NodesSelection/NodesSelection.vue' import NodesSelection from '../../components/NodesSelection/NodesSelection.vue'
import UserSelection from '../../components/UserSelection/UserSelection.vue' import UserSelection from '../../components/UserSelection/UserSelection.vue'
import NodeRenderer from '../NodeRenderer/NodeRenderer.vue'
import EdgeRenderer from '../EdgeRenderer/EdgeRenderer.vue'
const store = useStore() const store = useStore()
const userSelection = ref(false) const userSelection = ref(false)
@@ -49,7 +51,27 @@ export default {
} }
</script> </script>
<template> <template>
<slot></slot> <NodeRenderer :key="`node-renderer-${store.id}`">
<template
v-for="nodeName of Object.keys(store.getNodeTypes)"
#[`node-${nodeName}`]="nodeProps"
:key="`node-${nodeName}-${store.id}`"
>
<slot :name="`node-${nodeName}`" v-bind="nodeProps" />
</template>
</NodeRenderer>
<EdgeRenderer :key="`edge-renderer-${store.id}`">
<template
v-for="edgeName of Object.keys(store.getEdgeTypes)"
#[`edge-${edgeName}`]="edgeProps"
:key="`edge-${edgeName}-${store.id}`"
>
<slot :name="`edge-${edgeName}`" v-bind="edgeProps" />
</template>
<template #custom-connection-line="customConnectionLineProps">
<slot name="custom-connection-line" v-bind="customConnectionLineProps" />
</template>
</EdgeRenderer>
<UserSelection v-if="userSelection" :key="`user-selection-${store.id}`" /> <UserSelection v-if="userSelection" :key="`user-selection-${store.id}`" />
<NodesSelection v-if="store.nodesSelectionActive" :key="`nodes-selction-${store.id}`" /> <NodesSelection v-if="store.nodesSelectionActive" :key="`nodes-selction-${store.id}`" />
<div :key="`flow-pane-${store.id}`" class="vue-flow__pane" @click="onClick" @contextmenu="onContextMenu" @wheel="onWheel" /> <div :key="`flow-pane-${store.id}`" class="vue-flow__pane" @click="onClick" @contextmenu="onContextMenu" @wheel="onWheel" />
+21 -49
View File
@@ -1,10 +1,5 @@
<script lang="ts" setup> <script lang="ts" setup>
import Renderer from '../Renderer/Renderer.vue' import Renderer from '../Renderer/Renderer.vue'
import ZoomPane from '../ZoomPane/ZoomPane.vue'
import SelectionPane from '../SelectionPane/SelectionPane.vue'
import NodeRenderer from '../NodeRenderer/NodeRenderer.vue'
import EdgeRenderer from '../EdgeRenderer/EdgeRenderer.vue'
import LoadingIndicator from '../../components/Loading/LoadingIndicator.vue'
import { createHooks, initFlow } from '../../composables' import { createHooks, initFlow } from '../../composables'
import type { FlowProps } from '../../types/flow' import type { FlowProps } from '../../types/flow'
@@ -23,14 +18,13 @@ const props = withDefaults(defineProps<FlowProps>(), {
panOnScroll: false, panOnScroll: false,
paneMoveable: true, paneMoveable: true,
}) })
const emit = defineEmits([...Object.keys(createHooks()), 'update:nodes', 'update:edges']) const emit = defineEmits([...Object.keys(createHooks()), 'update:nodes', 'update:edges', 'update:elements', 'update:modelValue'])
const store = initFlow(emit, props.id) const store = initFlow(emit, props.id)
const { nodes, edges } = useVModels(props, emit) nextTick(() => store.setState(props))
store.setState(props)
watch( watch(
() => props, () => props,
() => store.setState(props), (v) => nextTick(() => store.setState(v)),
{ flush: 'post', deep: true }, { flush: 'sync', deep: true },
) )
</script> </script>
<script lang="ts"> <script lang="ts">
@@ -40,47 +34,25 @@ export default {
</script> </script>
<template> <template>
<div class="vue-flow"> <div class="vue-flow">
<Suspense timeout="0"> <Renderer :key="`renderer-${store.id}`">
<template #default> <template
<Renderer :key="`renderer-${store.id}`"> v-for="nodeName of Object.keys(store.getNodeTypes)"
<ZoomPane :key="`zoom-pane-${store.id}`"> #[`node-${nodeName}`]="nodeProps"
<template #default="zoomPaneProps"> :key="`node-${nodeName}-${store.id}`"
<SelectionPane :key="`selection-pane-${store.id}`"> >
<NodeRenderer :key="`node-renderer-${store.id}`"> <slot :name="`node-${nodeName}`" v-bind="nodeProps" />
<template
v-for="nodeName of Object.keys(store.getNodeTypes)"
#[`node-${nodeName}`]="nodeProps"
:key="`node-${nodeName}-${store.id}`"
>
<slot :name="`node-${nodeName}`" v-bind="nodeProps" />
</template>
</NodeRenderer>
<EdgeRenderer :key="`edge-renderer-${store.id}`">
<template
v-for="edgeName of Object.keys(store.getEdgeTypes)"
#[`edge-${edgeName}`]="edgeProps"
:key="`edge-${edgeName}-${store.id}`"
>
<slot :name="`edge-${edgeName}`" v-bind="edgeProps" />
</template>
<template #custom-connection-line="customConnectionLineProps">
<slot name="custom-connection-line" v-bind="customConnectionLineProps" />
</template>
</EdgeRenderer>
</SelectionPane>
<slot name="zoom-pane" v-bind="zoomPaneProps"></slot>
</template>
</ZoomPane>
</Renderer>
</template> </template>
<template #fallback> <template
<slot name="loading-indicator"> v-for="edgeName of Object.keys(store.getEdgeTypes)"
<LoadingIndicator v-if="store.loading && store.loading !== '' && !store.isReady" :label="store.loading"> #[`edge-${edgeName}`]="edgeProps"
<slot name="loading-label" /> :key="`edge-${edgeName}-${store.id}`"
</LoadingIndicator> >
</slot> <slot :name="`edge-${edgeName}`" v-bind="edgeProps" />
</template> </template>
</Suspense> <template #custom-connection-line="customConnectionLineProps">
<slot name="custom-connection-line" v-bind="customConnectionLineProps" />
</template>
</Renderer>
<slot v-bind="store"></slot> <slot v-bind="store"></slot>
</div> </div>
</template> </template>
+28 -15
View File
@@ -2,8 +2,9 @@
import { D3ZoomEvent, zoom, zoomIdentity, ZoomTransform } from 'd3-zoom' import { D3ZoomEvent, zoom, zoomIdentity, ZoomTransform } from 'd3-zoom'
import { pointer, select } from 'd3-selection' import { pointer, select } from 'd3-selection'
import { FlowTransform, PanOnScrollMode } from '../../types' import { FlowTransform, PanOnScrollMode } from '../../types'
import { useKeyPress, useStore, useWindow } from '../../composables' import { useKeyPress, useStore } from '../../composables'
import { clamp, clampPosition } from '../../utils' import { clamp, clampPosition } from '../../utils'
import SelectionPane from '../SelectionPane/SelectionPane.vue'
const store = useStore() const store = useStore()
const zoomPaneEl = templateRef<HTMLDivElement>('zoomPane', null) const zoomPaneEl = templateRef<HTMLDivElement>('zoomPane', null)
@@ -30,9 +31,9 @@ const d3Zoom = ref(zoom<HTMLDivElement, any>().scaleExtent([store.minZoom, store
const d3Selection = ref() const d3Selection = ref()
store.transform = [transform.value.x, transform.value.y, transform.value.zoom] store.transform = [transform.value.x, transform.value.y, transform.value.zoom]
const { width, height } = useElementBounding(zoomPaneEl)
nextTick(async () => { onMounted(() => {
await until(zoomPaneEl).toBeTruthy()
const d3z = d3Zoom.value! const d3z = d3Zoom.value!
d3Selection.value = select(zoomPaneEl.value).call(d3z) d3Selection.value = select(zoomPaneEl.value).call(d3z)
const d3s = d3Selection.value! const d3s = d3Selection.value!
@@ -154,20 +155,14 @@ nextTick(async () => {
// default filter for d3-zoom // default filter for d3-zoom
return (!event.ctrlKey || event.type === 'wheel') && !event.button return (!event.ctrlKey || event.type === 'wheel') && !event.button
}) })
})
const { width, height } = useElementBounding(zoomPaneEl)
// skip waiting for ssr
const window = useWindow()
if ('screen' in window) await until(() => store.isReady).toBe(true)
nextTick(() => {
watch( watch(
[width, height], [width, height],
([newWidth, newHeight]) => { ([newWidth, newHeight]) => {
store.dimensions.width = newWidth nextTick(() => {
store.dimensions.height = newHeight store.dimensions.width = newWidth
store.dimensions.height = newHeight
})
}, },
{ flush: 'sync', immediate: true }, { flush: 'sync', immediate: true },
) )
@@ -175,7 +170,7 @@ nextTick(() => {
transform, transform,
(val) => { (val) => {
const { x, y } = clampPosition(val, store.translateExtent) const { x, y } = clampPosition(val, store.translateExtent)
store.transform = [x, y, clamp(val.zoom, store.minZoom, store.maxZoom)] nextTick(() => (store.transform = [x, y, clamp(val.zoom, store.minZoom, store.maxZoom)]))
}, },
{ flush: 'sync', immediate: true }, { flush: 'sync', immediate: true },
) )
@@ -188,6 +183,24 @@ export default {
</script> </script>
<template> <template>
<div ref="zoomPane" class="vue-flow__zoompane"> <div ref="zoomPane" class="vue-flow__zoompane">
<slot /> <SelectionPane :key="`selection-pane-${store.id}`">
<template
v-for="nodeName of Object.keys(store.getNodeTypes)"
#[`node-${nodeName}`]="nodeProps"
:key="`node-${nodeName}-${store.id}`"
>
<slot :name="`node-${nodeName}`" v-bind="nodeProps" />
</template>
<template
v-for="edgeName of Object.keys(store.getEdgeTypes)"
#[`edge-${edgeName}`]="edgeProps"
:key="`edge-${edgeName}-${store.id}`"
>
<slot :name="`edge-${edgeName}`" v-bind="edgeProps" />
</template>
<template #custom-connection-line="customConnectionLineProps">
<slot name="custom-connection-line" v-bind="customConnectionLineProps" />
</template>
</SelectionPane>
</div> </div>
</template> </template>
+1 -1
View File
@@ -113,7 +113,7 @@ export type FlowInstance<DataNode = any, DataEdge = DataNode> = {
} }
export interface FlowProps<DataNode = any, DataEdge = DataNode> { export interface FlowProps<DataNode = any, DataEdge = DataNode> {
modelValue?: any modelValue?: any[]
nodes?: Node<DataNode>[] nodes?: Node<DataNode>[]
edges?: Edge<DataEdge>[] edges?: Edge<DataEdge>[]
elements?: Elements elements?: Elements