feat(docs): add animation edge to layouting example

This commit is contained in:
braks
2024-02-07 22:29:40 +01:00
committed by Braks
parent 43a1c9d2ac
commit 75355b04e7
6 changed files with 157 additions and 117 deletions
+46 -57
View File
@@ -1,6 +1,6 @@
<script setup> <script setup>
import { computed, ref, toRef, watch } from 'vue' import { computed, ref, toRef, watch } from 'vue'
import { BaseEdge, getSmoothStepPath, useNodesData, useVueFlow } from '@vue-flow/core' import { BaseEdge, EdgeLabelRenderer, Position, getSmoothStepPath, useNodesData } from '@vue-flow/core'
import { TransitionPresets, executeTransition } from '@vueuse/core' import { TransitionPresets, executeTransition } from '@vueuse/core'
const props = defineProps({ const props = defineProps({
@@ -8,6 +8,10 @@ const props = defineProps({
type: String, type: String,
required: true, required: true,
}, },
source: {
type: String,
required: true,
},
sourceX: { sourceX: {
type: Number, type: Number,
required: true, required: true,
@@ -26,65 +30,45 @@ const props = defineProps({
}, },
sourcePosition: { sourcePosition: {
type: String, type: String,
required: true, default: Position.Right,
}, },
targetPosition: { targetPosition: {
type: String, type: String,
required: true, default: Position.Left,
},
data: {
type: Object,
required: false,
},
markerEnd: {
type: String,
required: false,
},
style: {
type: Object,
required: false,
},
sourceHandleId: {
type: String,
required: false,
},
targetHandleId: {
type: String,
required: false,
}, },
}) })
const { onNodeDrag } = useVueFlow()
const edgePoint = ref(0) const edgePoint = ref(0)
const sourceNodeData = useNodesData(() => props.source) const sourceNodeData = useNodesData(() => props.source)
const isSourceNodeRunning = toRef(() => sourceNodeData.value?.isRunning) const isFinished = toRef(() => sourceNodeData.value.isFinished)
const isAnimating = ref(false)
const edgeColor = toRef(() => { const edgeColor = toRef(() => {
if (sourceNodeData.value?.hasError) { if (sourceNodeData.value.hasError) {
return '#f87171' return '#f87171'
} }
if (sourceNodeData.value?.isFinished) { if (sourceNodeData.value.isFinished) {
return '#10b981' return '#10b981'
} }
if (isSourceNodeRunning.value) { if (sourceNodeData.value.isCancelled) {
return '#6b7280' return '#fbbf24'
} }
if (sourceNodeData.value?.isSkipped) { if (sourceNodeData.value.isSkipped) {
return '#FFCC99' return '#f59e0b'
} }
return '#1a192b' return '#6b7280'
}) })
const edgeRef = ref() const edgeRef = ref()
const circlePosition = ref({ x: 0, y: 0 }) const labelPosition = ref({ x: 0, y: 0 })
const currentLength = ref(0) const currentLength = ref(0)
@@ -100,43 +84,44 @@ watch(edgePoint, (point) => {
const currLength = pathEl.getTotalLength() const currLength = pathEl.getTotalLength()
if (currentLength.value !== currLength) { if (currentLength.value !== currLength) {
runAnimation(point) return runAnimation()
return
} }
circlePosition.value = pathEl.getPointAtLength(point) labelPosition.value = pathEl.getPointAtLength(point)
}) })
watch(isSourceNodeRunning, (isRunning, _, onCleanup) => { watch(isFinished, async (isFinished) => {
if (isRunning) { if (isFinished) {
runAnimation() await runAnimation()
onCleanup(() => { edgePoint.value = 0
edgePoint.value = 0 currentLength.value = 0
currentLength.value = 0 labelPosition.value = { x: 0, y: 0 }
circlePosition.value = { x: 0, y: 0 }
})
} }
}) })
function runAnimation(from = 0) { async function runAnimation() {
const pathEl = edgeRef.value?.pathEl const pathEl = edgeRef.value?.pathEl
if (!pathEl) { if (!pathEl) {
return return
} }
edgePoint.value = 0 isAnimating.value = true
const totalLength = pathEl.getTotalLength() const totalLength = pathEl.getTotalLength()
const from = edgePoint.value || 0
if (currentLength.value !== totalLength) { if (currentLength.value !== totalLength) {
currentLength.value = totalLength currentLength.value = totalLength
} }
executeTransition(edgePoint, from, totalLength, { await executeTransition(edgePoint, from, totalLength, {
transition: TransitionPresets.easeInOutCubic, transition: TransitionPresets.easeInOutCubic,
}) })
isAnimating.value = false
} }
</script> </script>
@@ -148,14 +133,18 @@ export default {
</script> </script>
<template> <template>
<BaseEdge v-bind="$attrs" :id="id" ref="edgeRef" :path="path[0]" :marker-end="markerEnd" :style="{ stroke: edgeColor }" /> <BaseEdge v-bind="$attrs" :id="id" ref="edgeRef" :path="path[0]" :style="{ stroke: edgeColor }" />
<circle <EdgeLabelRenderer v-if="isAnimating">
v-if="isSourceNodeRunning" <div
r="4" :style="{
cy="0" position: 'absolute',
cx="0" transform: `translate(-50%, -50%) translate(${labelPosition.x}px,${labelPosition.y}px)`,
:transform="`translate(${circlePosition.x}, ${circlePosition.y})`" pointerEvents: 'all',
style="fill: #f59e0b" }"
/> class="nodrag nopan"
>
📦
</div>
</EdgeLabelRenderer>
</template> </template>
+13 -3
View File
@@ -4,6 +4,7 @@ import { nextTick, ref } from 'vue'
import { Panel, Position, VueFlow, useVueFlow } from '@vue-flow/core' import { Panel, Position, VueFlow, useVueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background' import { Background } from '@vue-flow/background'
import ProcessNode from './ProcessNode.vue' import ProcessNode from './ProcessNode.vue'
import AnimationEdge from './AnimationEdge.vue'
import { initialEdges, initialNodes } from './initial-elements.js' import { initialEdges, initialNodes } from './initial-elements.js'
import { useRunProcess } from './useRunProcess' import { useRunProcess } from './useRunProcess'
@@ -62,11 +63,20 @@ function handleLayout(direction) {
<div class="layoutflow"> <div class="layoutflow">
<VueFlow :nodes="nodes" :edges="edges" @nodes-initialized="handleLayout('LR')"> <VueFlow :nodes="nodes" :edges="edges" @nodes-initialized="handleLayout('LR')">
<template #node-process="props"> <template #node-process="props">
<ProcessNode v-bind="props" /> <ProcessNode :data="props.data" :source-position="props.sourcePosition" :target-position="props.targetPosition" />
</template> </template>
<template #edge-animation="props"> <template #edge-animation="edgeProps">
<AnimationEdge v-bind="props" /> <AnimationEdge
:id="edgeProps.id"
:source="edgeProps.source"
:source-x="edgeProps.sourceX"
:source-y="edgeProps.sourceY"
:targetX="edgeProps.targetX"
:targetY="edgeProps.targetY"
:source-position="edgeProps.sourcePosition"
:target-position="edgeProps.targetPosition"
/>
</template> </template>
<Background /> <Background />
+47 -9
View File
@@ -1,6 +1,6 @@
<script setup> <script setup>
import { toRef } from 'vue' import { toRef } from 'vue'
import { Handle } from '@vue-flow/core' import { Handle, useHandleConnections } from '@vue-flow/core'
const props = defineProps({ const props = defineProps({
data: { data: {
@@ -15,7 +15,23 @@ const props = defineProps({
}, },
}) })
const sourceConnections = useHandleConnections({
type: 'target',
})
const targetConnections = useHandleConnections({
type: 'source',
})
const isSender = toRef(() => sourceConnections.value.length <= 0)
const isReceiver = toRef(() => targetConnections.value.length <= 0)
const bgColor = toRef(() => { const bgColor = toRef(() => {
if (isSender.value) {
return '#4b5563'
}
if (props.data.hasError) { if (props.data.hasError) {
return '#f87171' return '#f87171'
} }
@@ -30,19 +46,41 @@ const bgColor = toRef(() => {
return '#4b5563' return '#4b5563'
}) })
const processLabel = toRef(() => {
if (props.data.hasError) {
return '❌'
}
if (props.data.isSkipped) {
return '🚧'
}
if (props.data.isCancelled) {
return '🚫'
}
if (isSender.value) {
return '📦'
}
if (props.data.isFinished) {
return '😎'
}
return '📥'
})
</script> </script>
<template> <template>
<div class="process-node" :style="{ backgroundColor: bgColor }"> <div class="process-node" :style="{ backgroundColor: bgColor }">
<Handle type="target" :position="targetPosition" /> <Handle v-if="!isSender" type="target" :position="targetPosition" />
<Handle type="source" :position="sourcePosition" /> <Handle v-if="!isReceiver" type="source" :position="sourcePosition" />
<div v-if="data.isRunning" class="spinner" /> <div v-if="data.isRunning" class="spinner" />
<span v-else-if="data.hasError">&#x274C;</span> <span v-else>
<span v-else-if="data.isSkipped">&#x1F6A7;</span> {{ processLabel }}
<span v-else-if="data.isFinished"> &#x1F60E;</span> </span>
<span v-else-if="data.isCancelled"> &#x1F6AB;</span>
<span v-else> &#x1F4E6;</span>
</div> </div>
</template> </template>
@@ -50,6 +88,7 @@ const bgColor = toRef(() => {
.process-node { .process-node {
padding: 10px; padding: 10px;
color: white; color: white;
border: 1px solid #4b5563;
border-radius: 99px; border-radius: 99px;
font-size: 12px; font-size: 12px;
width: 18px; width: 18px;
@@ -57,7 +96,6 @@ const bgColor = toRef(() => {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
} }
.spinner { .spinner {
+23 -23
View File
@@ -1,74 +1,74 @@
const position = { x: 0, y: 0 } const position = { x: 0, y: 0 }
const type = 'process' const nodeType = 'process'
const edgeType = 'animation'
export const initialNodes = [ export const initialNodes = [
{ {
id: '1', id: '1',
label: 'Start',
position, position,
type, type: nodeType,
}, },
{ {
id: '2', id: '2',
position, position,
type, type: nodeType,
}, },
{ {
id: '2a', id: '2a',
position, position,
type, type: nodeType,
}, },
{ {
id: '2b', id: '2b',
position, position,
type, type: nodeType,
}, },
{ {
id: '2c', id: '2c',
position, position,
type, type: nodeType,
}, },
{ {
id: '2d', id: '2d',
position, position,
type, type: nodeType,
}, },
{ {
id: '3', id: '3',
position, position,
type, type: nodeType,
}, },
{ {
id: '4', id: '4',
position, position,
type, type: nodeType,
}, },
{ {
id: '5', id: '5',
position, position,
type, type: nodeType,
}, },
{ {
id: '6', id: '6',
position, position,
type, type: nodeType,
}, },
{ {
id: '7', id: '7',
position, position,
type, type: nodeType,
}, },
] ]
export const initialEdges = [ export const initialEdges = [
{ id: 'e1-2', source: '1', target: '2', type: 'smoothstep', animated: true }, { id: 'e1-2', source: '1', target: '2', type: edgeType, animated: true },
{ id: 'e1-3', source: '1', target: '3', type: 'smoothstep', animated: true }, { id: 'e1-3', source: '1', target: '3', type: edgeType, animated: true },
{ id: 'e2-2a', source: '2', target: '2a', type: 'smoothstep', animated: true }, { id: 'e2-2a', source: '2', target: '2a', type: edgeType, animated: true },
{ id: 'e2-2b', source: '2', target: '2b', type: 'smoothstep', animated: true }, { id: 'e2-2b', source: '2', target: '2b', type: edgeType, animated: true },
{ id: 'e2-2c', source: '2', target: '2c', type: 'smoothstep', animated: true }, { id: 'e2-2c', source: '2', target: '2c', type: edgeType, animated: true },
{ id: 'e2c-2d', source: '2c', target: '2d', type: 'smoothstep', animated: true }, { id: 'e2c-2d', source: '2c', target: '2d', type: edgeType, animated: true },
{ id: 'e3-7', source: '3', target: '4', type: 'smoothstep', animated: true }, { id: 'e3-7', source: '3', target: '4', type: edgeType, animated: true },
{ id: 'e4-5', source: '4', target: '5', type: 'smoothstep', animated: true }, { id: 'e4-5', source: '4', target: '5', type: edgeType, animated: true },
{ id: 'e5-6', source: '5', target: '6', type: 'smoothstep', animated: true }, { id: 'e5-6', source: '5', target: '6', type: edgeType, animated: true },
{ id: 'e5-7', source: '5', target: '7', type: 'smoothstep', animated: true }, { id: 'e5-7', source: '5', target: '7', type: edgeType, animated: true },
] ]
+26 -23
View File
@@ -18,7 +18,7 @@ export function useRunProcess(dagreGraph) {
const executedNodes = new Set() const executedNodes = new Set()
const runningTasks = new Map() const runningTasks = new Map()
async function runNode(node) { async function runNode(node, isStart = false) {
if (executedNodes.has(node.id)) { if (executedNodes.has(node.id)) {
return return
} }
@@ -30,33 +30,36 @@ export function useRunProcess(dagreGraph) {
// Simulate an async process with a random timeout between 1 and 3 seconds // Simulate an async process with a random timeout between 1 and 3 seconds
const delay = Math.floor(Math.random() * 2000) + 1000 const delay = Math.floor(Math.random() * 2000) + 1000
return new Promise((resolve) => { return new Promise((resolve) => {
const timeout = setTimeout(async () => { const timeout = setTimeout(
const children = graph.value.successors(node.id) async () => {
const children = graph.value.successors(node.id)
// Randomly decide whether the node will throw an error // Randomly decide whether the node will throw an error
const willThrowError = Math.random() < 0.15 const willThrowError = Math.random() < 0.15
if (willThrowError) { if (willThrowError) {
updateNodeData(node.id, { isRunning: false, hasError: true }) updateNodeData(node.id, { isRunning: false, hasError: true })
await skipDescendants(node.id)
runningTasks.delete(node.id)
resolve()
return
}
updateNodeData(node.id, { isRunning: false, isFinished: true })
await skipDescendants(node.id)
runningTasks.delete(node.id) runningTasks.delete(node.id)
if (children.length > 0) {
// Run the process on the children in parallel
await Promise.all(children.map((id) => runNode({ id })))
}
resolve() resolve()
return },
} isStart ? 0 : delay,
)
updateNodeData(node.id, { isRunning: false, isFinished: true })
runningTasks.delete(node.id)
if (children.length > 0) {
// Run the process on the children in parallel
await Promise.all(children.map((id) => runNode({ id })))
}
resolve()
}, delay)
runningTasks.set(node.id, timeout) runningTasks.set(node.id, timeout)
}) })
@@ -75,7 +78,7 @@ export function useRunProcess(dagreGraph) {
const startingNodes = nodes.filter((node) => graph.value.predecessors(node.id)?.length === 0) const startingNodes = nodes.filter((node) => graph.value.predecessors(node.id)?.length === 0)
// Run the process on all starting nodes in parallel // Run the process on all starting nodes in parallel
await Promise.all(startingNodes.map(runNode)) await Promise.all(startingNodes.map((node) => runNode(node, true)))
clear() clear()
} }
+2 -2
View File
@@ -20,7 +20,7 @@ export function useRunProcess(dagreGraph: MaybeRefOrGetter<dagre.graphlib.Graph>
const executedNodes = new Set<string>() const executedNodes = new Set<string>()
const runningTasks = new Map<string, NodeJS.Timeout>() const runningTasks = new Map<string, NodeJS.Timeout>()
async function runNode(node: { id: string }, isStartingNode = false) { async function runNode(node: { id: string }, isStart = false) {
if (executedNodes.has(node.id)) { if (executedNodes.has(node.id)) {
return return
} }
@@ -59,7 +59,7 @@ export function useRunProcess(dagreGraph: MaybeRefOrGetter<dagre.graphlib.Graph>
resolve() resolve()
}, },
isStartingNode ? 0 : delay, isStart ? 0 : delay,
) )
runningTasks.set(node.id, timeout) runningTasks.set(node.id, timeout)