chore(docs): center dnd nodes after drop
This commit is contained in:
@@ -1,11 +1,12 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { VueFlow, useVueFlow } from '@vue-flow/core'
|
import { VueFlow, useVueFlow } from '@vue-flow/core'
|
||||||
|
import { nextTick, watch } from 'vue'
|
||||||
import Sidebar from './Sidebar.vue'
|
import Sidebar from './Sidebar.vue'
|
||||||
|
|
||||||
let id = 0
|
let id = 0
|
||||||
const getId = () => `dndnode_${id++}`
|
const getId = () => `dndnode_${id++}`
|
||||||
|
|
||||||
const { onConnect, nodes, edges, addEdges, addNodes, viewport, project } = useVueFlow({
|
const { findNode, onConnect, nodes, edges, addEdges, addNodes, viewport, project, vueFlowRef } = useVueFlow({
|
||||||
nodes: [
|
nodes: [
|
||||||
{
|
{
|
||||||
id: '1',
|
id: '1',
|
||||||
@@ -29,7 +30,12 @@ onConnect((params) => addEdges([params]))
|
|||||||
const onDrop = (event) => {
|
const onDrop = (event) => {
|
||||||
const type = event.dataTransfer?.getData('application/vueflow')
|
const type = event.dataTransfer?.getData('application/vueflow')
|
||||||
|
|
||||||
const position = project({ x: event.clientX - 40, y: event.clientY - 18 })
|
const { left, top } = vueFlowRef.value.getBoundingClientRect()
|
||||||
|
|
||||||
|
const position = project({
|
||||||
|
x: event.clientX - left,
|
||||||
|
y: event.clientY - top,
|
||||||
|
})
|
||||||
|
|
||||||
const newNode = {
|
const newNode = {
|
||||||
id: getId(),
|
id: getId(),
|
||||||
@@ -39,6 +45,21 @@ const onDrop = (event) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addNodes([newNode])
|
addNodes([newNode])
|
||||||
|
|
||||||
|
// align node position after drop, so it's centered to the mouse
|
||||||
|
nextTick(() => {
|
||||||
|
const node = findNode(newNode.id)
|
||||||
|
const stop = watch(
|
||||||
|
() => node.dimensions,
|
||||||
|
(dimensions) => {
|
||||||
|
if (dimensions.width > 0 && dimensions.height > 0) {
|
||||||
|
node.position = { x: node.position.x - node.dimensions.width / 2, y: node.position.y - node.dimensions.height / 2 }
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ deep: true, flush: 'post' },
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user