examples: animation edge

This commit is contained in:
braks
2024-02-06 18:24:30 +01:00
committed by Braks
parent f9e4d84297
commit 43a1c9d2ac
9 changed files with 379 additions and 47 deletions

View File

@@ -18,7 +18,7 @@ import { IntersectionApp, IntersectionCSS } from './intersection'
import { SnapToHandleApp, SnappableConnectionLine } from './connection-radius'
import { NodeResizerApp, ResizableNode } from './node-resizer'
import { ToolbarApp, ToolbarNode } from './node-toolbar'
import { LayoutApp, LayoutElements, LayoutNode, LayoutScript } from './layout'
import { LayoutApp, LayoutEdge, LayoutElements, LayoutNode, LayoutScript } from './layout'
export const exampleImports = {
basic: {
@@ -103,8 +103,8 @@ export const exampleImports = {
'TransitionEdge.vue': TransitionEdge,
'style.css': TransitionCSS,
'additionalImports': {
'@vueuse/core': 'https://cdn.jsdelivr.net/npm/@vueuse/core@9.3.0/index.mjs',
'@vueuse/shared': 'https://cdn.jsdelivr.net/npm/@vueuse/shared@9.3.0/index.mjs',
'@vueuse/core': 'https://cdn.jsdelivr.net/npm/@vueuse/core@10.7.0/index.mjs',
'@vueuse/shared': 'https://cdn.jsdelivr.net/npm/@vueuse/shared@10.7.0/index.mjs',
'vue-demi': 'https://cdn.jsdelivr.net/npm/vue-demi@0.13.11/lib/index.mjs',
},
},
@@ -128,9 +128,13 @@ export const exampleImports = {
'App.vue': LayoutApp,
'initial-elements.js': LayoutElements,
'ProcessNode.vue': LayoutNode,
'AnimationEdge.vue': LayoutEdge,
'useRunProcess.js': LayoutScript,
'additionalImports': {
dagre: 'https://cdn.skypack.dev/pin/dagre@v0.8.5-NOlknF82nBdUHQKLJWRC/mode=imports,min/optimized/dagre.js',
'@vueuse/core': 'https://cdn.jsdelivr.net/npm/@vueuse/core@10.7.0/index.mjs',
'@vueuse/shared': 'https://cdn.jsdelivr.net/npm/@vueuse/shared@10.7.0/index.mjs',
'vue-demi': 'https://cdn.jsdelivr.net/npm/vue-demi@0.13.11/lib/index.mjs',
'dagre': 'https://cdn.skypack.dev/pin/dagre@v0.8.5-NOlknF82nBdUHQKLJWRC/mode=imports,min/optimized/dagre.js',
},
},
}

View File

@@ -0,0 +1,161 @@
<script setup>
import { computed, ref, toRef, watch } from 'vue'
import { BaseEdge, getSmoothStepPath, useNodesData, useVueFlow } from '@vue-flow/core'
import { TransitionPresets, executeTransition } from '@vueuse/core'
const props = defineProps({
id: {
type: String,
required: true,
},
sourceX: {
type: Number,
required: true,
},
sourceY: {
type: Number,
required: true,
},
targetX: {
type: Number,
required: true,
},
targetY: {
type: Number,
required: true,
},
sourcePosition: {
type: String,
required: true,
},
targetPosition: {
type: String,
required: true,
},
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 sourceNodeData = useNodesData(() => props.source)
const isSourceNodeRunning = toRef(() => sourceNodeData.value?.isRunning)
const edgeColor = toRef(() => {
if (sourceNodeData.value?.hasError) {
return '#f87171'
}
if (sourceNodeData.value?.isFinished) {
return '#10b981'
}
if (isSourceNodeRunning.value) {
return '#6b7280'
}
if (sourceNodeData.value?.isSkipped) {
return '#FFCC99'
}
return '#1a192b'
})
const edgeRef = ref()
const circlePosition = ref({ x: 0, y: 0 })
const currentLength = ref(0)
const path = computed(() => getSmoothStepPath(props))
watch(edgePoint, (point) => {
const pathEl = edgeRef.value?.pathEl
if (!pathEl || point === 0) {
return
}
const currLength = pathEl.getTotalLength()
if (currentLength.value !== currLength) {
runAnimation(point)
return
}
circlePosition.value = pathEl.getPointAtLength(point)
})
watch(isSourceNodeRunning, (isRunning, _, onCleanup) => {
if (isRunning) {
runAnimation()
onCleanup(() => {
edgePoint.value = 0
currentLength.value = 0
circlePosition.value = { x: 0, y: 0 }
})
}
})
function runAnimation(from = 0) {
const pathEl = edgeRef.value?.pathEl
if (!pathEl) {
return
}
edgePoint.value = 0
const totalLength = pathEl.getTotalLength()
if (currentLength.value !== totalLength) {
currentLength.value = totalLength
}
executeTransition(edgePoint, from, totalLength, {
transition: TransitionPresets.easeInOutCubic,
})
}
</script>
<script>
export default {
name: 'AnimationEdge',
inheritAttrs: false,
}
</script>
<template>
<BaseEdge v-bind="$attrs" :id="id" ref="edgeRef" :path="path[0]" :marker-end="markerEnd" :style="{ stroke: edgeColor }" />
<circle
v-if="isSourceNodeRunning"
r="4"
cy="0"
cx="0"
:transform="`translate(${circlePosition.x}, ${circlePosition.y})`"
style="fill: #f59e0b"
/>
</template>

View File

@@ -65,6 +65,10 @@ function handleLayout(direction) {
<ProcessNode v-bind="props" />
</template>
<template #edge-animation="props">
<AnimationEdge v-bind="props" />
</template>
<Background />
<Panel class="layout-panel" position="top-left">

View File

@@ -1,4 +1,5 @@
export { default as LayoutApp } from './App.vue?raw'
export { default as LayoutElements } from './initial-elements.js?raw'
export { default as LayoutNode } from './ProcessNode.vue?raw'
export { default as LayoutEdge } from './AnimationEdge.vue?raw'
export { default as LayoutScript } from './useRunProcess.js?raw'

View File

@@ -0,0 +1,117 @@
<script setup lang="ts">
import type { EdgeProps } from '@vue-flow/core'
import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, useNodesData } from '@vue-flow/core'
import { TransitionPresets, executeTransition } from '@vueuse/core'
const props = defineProps<EdgeProps>()
const edgePoint = ref(0)
const sourceNodeData = useNodesData(() => props.source)
const isFinished = toRef(() => sourceNodeData.value.isFinished)
const isAnimating = ref(false)
const edgeColor = toRef(() => {
if (sourceNodeData.value.hasError) {
return '#f87171'
}
if (sourceNodeData.value.isFinished) {
return '#10b981'
}
if (sourceNodeData.value.isCancelled) {
return '#fbbf24'
}
if (sourceNodeData.value.isSkipped) {
return '#f59e0b'
}
return '#6b7280'
})
const edgeRef = ref<InstanceType<typeof BaseEdge>>()
const circlePosition = ref({ x: 0, y: 0 })
const currentLength = ref(0)
const path = computed(() => getSmoothStepPath(props))
watch(edgePoint, (point) => {
const pathEl = edgeRef.value?.pathEl
if (!pathEl || point === 0) {
return
}
const currLength = pathEl.getTotalLength()
if (currentLength.value !== currLength) {
return runAnimation()
}
circlePosition.value = pathEl.getPointAtLength(point)
})
watch(isFinished, async (isFinished, _, onCleanup) => {
if (isFinished) {
await runAnimation()
edgePoint.value = 0
currentLength.value = 0
circlePosition.value = { x: 0, y: 0 }
}
})
async function runAnimation() {
const pathEl = edgeRef.value?.pathEl
if (!pathEl) {
return
}
isAnimating.value = true
const totalLength = pathEl.getTotalLength()
const from = edgePoint.value || 0
if (currentLength.value !== totalLength) {
currentLength.value = totalLength
}
await executeTransition(edgePoint, from, totalLength, {
transition: TransitionPresets.easeInOutCubic,
})
isAnimating.value = false
}
</script>
<script lang="ts">
export default {
name: 'AnimationEdge',
inheritAttrs: false,
}
</script>
<template>
<BaseEdge v-bind="$attrs" :id="id" ref="edgeRef" :path="path[0]" :marker-end="markerEnd" :style="{ stroke: edgeColor }" />
<EdgeLabelRenderer v-if="isAnimating">
<div
:style="{
position: 'absolute',
transform: `translate(-50%, -50%) translate(${circlePosition.x}px,${circlePosition.y}px)`,
pointerEvents: 'all',
}"
class="nodrag nopan"
>
📦
</div>
</EdgeLabelRenderer>
</template>

View File

@@ -4,6 +4,7 @@ import { ConnectionMode, Panel, Position, VueFlow, useVueFlow } from '@vue-flow/
import { initialEdges, initialNodes } from './initial-elements'
import { useRunProcess } from './useRunProcess'
import AnimationEdge from './AnimationEdge.vue'
import ProcessNode from './ProcessNode.vue'
const nodes = ref(initialNodes)
@@ -64,12 +65,16 @@ function handleLayout(direction: 'TB' | 'LR') {
<ProcessNode v-bind="props" />
</template>
<Panel class="layout-panel" position="top-right">
<template #edge-animation="props">
<AnimationEdge v-bind="props" />
</template>
<Panel class="layout-panel" position="top-left">
<button @click="handleLayout('TB')">vertical</button>
<button @click="handleLayout('LR')">horizontal</button>
</Panel>
<Panel class="process-panel" position="bottom-right">
<Panel class="process-panel" position="top-right">
<button v-if="isRunning" @click="stop">🛑</button>
<button v-else @click="run(nodes)"></button>
</Panel>

View File

@@ -1,10 +1,26 @@
<script setup lang="ts">
import type { NodeProps } from '@vue-flow/core'
import { Handle } from '@vue-flow/core'
import { Handle, useHandleConnections } from '@vue-flow/core'
const props = defineProps<NodeProps>()
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(() => {
if (isSender.value) {
return '#4b5563'
}
if (props.data.hasError) {
return '#f87171'
}
@@ -19,19 +35,41 @@ const bgColor = toRef(() => {
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>
<template>
<div class="process-node" :style="{ backgroundColor: bgColor }">
<Handle type="target" :position="targetPosition" />
<Handle type="source" :position="sourcePosition" />
<Handle v-if="!isSender" type="target" :position="targetPosition" />
<Handle v-if="!isReceiver" type="source" :position="sourcePosition" />
<div v-if="data.isRunning" class="spinner" />
<span v-else-if="data.hasError">&#x274C;</span>
<span v-else-if="data.isSkipped">&#x1F6A7;</span>
<span v-else-if="data.isFinished"> &#x1F60E;</span>
<span v-else-if="data.isCancelled"> &#x1F6AB;</span>
<span v-else> &#x1F4E6;</span>
<span v-else>
{{ processLabel }}
</span>
</div>
</template>

View File

@@ -62,14 +62,14 @@ export const initialNodes: Node[] = [
]
export const initialEdges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', type: 'smoothstep', animated: true },
{ id: 'e1-3', source: '1', target: '3', type: 'smoothstep', animated: true },
{ id: 'e2-2a', source: '2', target: '2a', type: 'smoothstep', animated: true },
{ id: 'e2-2b', source: '2', target: '2b', type: 'smoothstep', animated: true },
{ id: 'e2-2c', source: '2', target: '2c', type: 'smoothstep', animated: true },
{ id: 'e2c-2d', source: '2c', target: '2d', type: 'smoothstep', animated: true },
{ id: 'e3-7', source: '3', target: '4', type: 'smoothstep', animated: true },
{ id: 'e4-5', source: '4', target: '5', type: 'smoothstep', animated: true },
{ id: 'e5-6', source: '5', target: '6', type: 'smoothstep', animated: true },
{ id: 'e5-7', source: '5', target: '7', type: 'smoothstep', animated: true },
{ id: 'e1-2', source: '1', target: '2', type: 'animation', animated: true },
{ id: 'e1-3', source: '1', target: '3', type: 'animation', animated: true },
{ id: 'e2-2a', source: '2', target: '2a', type: 'animation', animated: true },
{ id: 'e2-2b', source: '2', target: '2b', type: 'animation', animated: true },
{ id: 'e2-2c', source: '2', target: '2c', type: 'animation', animated: true },
{ id: 'e2c-2d', source: '2c', target: '2d', type: 'animation', animated: true },
{ id: 'e3-7', source: '3', target: '4', type: 'animation', animated: true },
{ id: 'e4-5', source: '4', target: '5', type: 'animation', animated: true },
{ id: 'e5-6', source: '5', target: '6', type: 'animation', animated: true },
{ id: 'e5-7', source: '5', target: '7', type: 'animation', animated: true },
]

View File

@@ -20,7 +20,7 @@ export function useRunProcess(dagreGraph: MaybeRefOrGetter<dagre.graphlib.Graph>
const executedNodes = new Set<string>()
const runningTasks = new Map<string, NodeJS.Timeout>()
async function runNode(node: { id: string }) {
async function runNode(node: { id: string }, isStartingNode = false) {
if (executedNodes.has(node.id)) {
return
}
@@ -32,33 +32,35 @@ export function useRunProcess(dagreGraph: MaybeRefOrGetter<dagre.graphlib.Graph>
// Simulate an async process with a random timeout between 1 and 3 seconds
const delay = Math.floor(Math.random() * 2000) + 1000
return new Promise<void>((resolve) => {
const timeout = setTimeout(async () => {
const children = graph.value.successors(node.id) as unknown as string[]
const timeout = setTimeout(
async () => {
const children = graph.value.successors(node.id) as unknown as string[]
// Randomly decide whether the node will throw an error
const willThrowError = Math.random() < 0.15
// Randomly decide whether the node will throw an error
const willThrowError = Math.random() < 0.15
if (willThrowError) {
updateNodeData(node.id, { isRunning: false, hasError: true })
if (willThrowError) {
updateNodeData(node.id, { isRunning: false, hasError: true })
await skipDescendants(node.id)
await skipDescendants(node.id)
runningTasks.delete(node.id)
resolve()
return
}
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()
return
}
updateNodeData(node.id, { isRunning: false, isFinished: true })
console.log(`Node ${node.id} finished`)
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)
},
isStartingNode ? 0 : delay,
)
runningTasks.set(node.id, timeout)
})
@@ -77,7 +79,7 @@ export function useRunProcess(dagreGraph: MaybeRefOrGetter<dagre.graphlib.Graph>
const startingNodes = nodes.filter((node) => graph.value.predecessors(node.id)?.length === 0)
// 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()
}