chore(core): replace getNode with findNode

Signed-off-by: braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
braks
2023-01-18 20:47:32 +01:00
committed by Braks
parent 73de601f79
commit 203b4815f8
8 changed files with 114 additions and 151 deletions
+72 -95
View File
@@ -1,109 +1,86 @@
<script lang="ts" setup> <script setup lang="ts">
import { ConnectionMode, VueFlow, useVueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls' import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap' import { Background } from '@vue-flow/background'
import { PanelPosition, VueFlow, useVueFlow } from '@vue-flow/core'
import DiagramCustomNode from './DiagramCustomNode.vue'
import DiagramCustomParentNode from './DiagramCustomParentNode.vue'
import data from './data.json'
const { onConnect, addEdges, addNodes, findNode } = useVueFlow({ const elements = ref<any[]>([])
fitViewOnInit: true,
connectionMode: ConnectionMode.Loose, setTimeout(() => {
nodes: [ elements.value = data
{ id: '1', type: 'input', label: 'Node 1', position: { x: 250, y: 5 }, class: 'light' }, }, 1000)
{
id: '2', const {
label: 'Node 2', fitView,
position: { x: 100, y: 100 }, setInteractive,
class: 'light', nodesConnectable,
style: { backgroundColor: 'rgba(255, 0, 0, 0.8)' }, nodesDraggable,
}, onNodesChange,
{ onEdgesChange,
id: '2a', applyNodeChanges,
label: 'Node 2a', applyEdgeChanges,
position: { x: 10, y: 50 }, getNodesInitialized,
parentNode: '2', onNodesInitialized,
}, } = useVueFlow()
{ id: '3', label: 'Node 3', position: { x: 320, y: 100 }, class: 'light' },
{ function onPaneReady() {
id: '4', fitView({
label: 'Node 4', minZoom: 1,
position: { x: 320, y: 200 }, maxZoom: 1,
class: 'light', })
style: { backgroundColor: 'rgba(255, 0, 0, 0.7)', width: '300px', height: '300px' }, setInteractive(false)
},
{ nodesConnectable.value = false
id: '4a', nodesDraggable.value = true
label: 'Node 4a', }
position: { x: 15, y: 65 },
class: 'light', onNodesChange((changes) => {
extent: 'parent', const validChanges = changes.filter((change) => change.type !== 'remove')
parentNode: '4', applyNodeChanges(validChanges)
},
{
id: '4b',
label: 'Node 4b',
position: { x: 15, y: 120 },
class: 'light',
style: { backgroundColor: 'rgba(255, 0, 255, 0.7)', height: '150px', width: '270px' },
parentNode: '4',
},
{
id: '4b1',
label: 'Node 4b1',
position: { x: 20, y: 40 },
class: 'light',
parentNode: '4b',
},
{
id: '4b2',
label: 'Node 4b2',
position: { x: 100, y: 100 },
class: 'light',
parentNode: '4b',
},
],
edges: [
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' },
{ id: 'e2a-4a', source: '2a', target: '4a' },
{ id: 'e3-4', source: '3', target: '4' },
{ id: 'e3-4b', source: '3', target: '4b' },
{ id: 'e4a-4b1', source: '4a', target: '4b1' },
{ id: 'e4a-4b2', source: '4a', target: '4b2' },
{ id: 'e4b1-4b2', source: '4b1', target: '4b2' },
],
}) })
onConnect((params) => addEdges([params])) onEdgesChange((changes) => {
const validChanges = changes.filter((change) => change.type !== 'remove')
applyEdgeChanges(validChanges)
})
onMounted(() => { onNodesInitialized((nodesInitialized) => {
// add nodes to parent console.log(nodesInitialized)
addNodes([ nodesInitialized.forEach((node) => {
{ if (node.expandParent) {
id: '999', node.expandParent = false
type: 'input', node.extent = {
label: 'Added after mount', range: 'parent',
position: { x: 20, y: 100 }, padding: [48, 24, 24, 24],
class: 'light', }
expandParent: true,
parentNode: '2',
},
])
setTimeout(() => {
const node = findNode('999')!
node.expandParent = false
node.extent = {
range: 'parent',
padding: [10],
} }
}) })
}) })
</script> </script>
<template> <template>
<VueFlow> <VueFlow
<MiniMap /> v-model="elements"
<Controls /> class="panel"
:nodes-connectable="false"
:apply-default="false"
elevate-edges-on-select
@pane-ready="onPaneReady"
>
<template #node-custom="props">
<DiagramCustomNode :data="props.data" />
</template>
<template #node-custom-parent="props">
<DiagramCustomParentNode :data="props.data" />
</template>
<Controls :show-interactive="false" :position="PanelPosition.BottomRight" />
<Background /> <Background />
</VueFlow> </VueFlow>
</template> </template>
<style src="./CustomDiagram.css"></style>
@@ -25,7 +25,7 @@ const {
nodesSelectionActive, nodesSelectionActive,
multiSelectionActive, multiSelectionActive,
emits, emits,
getNode, findNode,
removeSelectedElements, removeSelectedElements,
addSelectedNodes, addSelectedNodes,
updateNodeDimensions, updateNodeDimensions,
@@ -42,7 +42,7 @@ const updateNodePositions = useUpdateNodePositions()
const node = $(useVModel(props, 'node')) const node = $(useVModel(props, 'node'))
const parentNode = $computed(() => (node.parentNode ? getNode(node.parentNode) : undefined)) const parentNode = $computed(() => (node.parentNode ? findNode(node.parentNode) : undefined))
const connectedEdges = $computed(() => getConnectedEdges([node], edges)) const connectedEdges = $computed(() => getConnectedEdges([node], edges))
+7 -7
View File
@@ -26,7 +26,7 @@ function useDrag(params: UseDragParams) {
noDragClassName, noDragClassName,
nodes, nodes,
nodeExtent, nodeExtent,
getNode, findNode,
multiSelectionActive, multiSelectionActive,
nodesSelectionActive, nodesSelectionActive,
selectNodesOnDrag, selectNodesOnDrag,
@@ -47,7 +47,7 @@ function useDrag(params: UseDragParams) {
watch([() => disabled, () => el], () => { watch([() => disabled, () => el], () => {
if (el) { if (el) {
const selection = select(el) const selection = select(el)
const node = id ? getNode(id) : undefined const node = id ? findNode(id) : undefined
if (disabled) { if (disabled) {
selection.on('.drag', null) selection.on('.drag', null)
@@ -65,13 +65,13 @@ function useDrag(params: UseDragParams) {
} }
const mousePos = getPointerPosition(event, snapToGrid ? snapGrid : undefined) const mousePos = getPointerPosition(event, snapToGrid ? snapGrid : undefined)
dragItems = getDragItems(nodes, mousePos, getNode, id) dragItems = getDragItems(nodes, mousePos, findNode, id)
if (onStart && dragItems) { if (onStart && dragItems) {
const [currentNode, nodes] = getEventHandlerParams({ const [currentNode, nodes] = getEventHandlerParams({
id, id,
dragItems, dragItems,
getNode: $$(getNode), findNode,
}) })
onStart(event.sourceEvent, currentNode, nodes) onStart(event.sourceEvent, currentNode, nodes)
} }
@@ -98,7 +98,7 @@ function useDrag(params: UseDragParams) {
n, n,
nextPosition, nextPosition,
nodeExtent, nodeExtent,
n.parentNode ? getNode(n.parentNode) : undefined, n.parentNode ? findNode(n.parentNode) : undefined,
) )
// we want to make sure that we only fire a change event when there is a changes // we want to make sure that we only fire a change event when there is a changes
@@ -117,7 +117,7 @@ function useDrag(params: UseDragParams) {
const [currentNode, nodes] = getEventHandlerParams({ const [currentNode, nodes] = getEventHandlerParams({
id, id,
dragItems, dragItems,
getNode: $$(getNode), findNode,
}) })
dragging.value = true dragging.value = true
@@ -135,7 +135,7 @@ function useDrag(params: UseDragParams) {
const [currentNode, nodes] = getEventHandlerParams({ const [currentNode, nodes] = getEventHandlerParams({
id, id,
dragItems, dragItems,
getNode: $$(getNode), findNode,
}) })
dragging.value = false dragging.value = false
+12 -12
View File
@@ -1,6 +1,6 @@
import type { MaybeRef } from '@vueuse/core' import type { MaybeRef } from '@vueuse/core'
import { isFunction } from '@vueuse/core' import { isFunction } from '@vueuse/core'
import type { Connection, Getters, GraphEdge, HandleType, ValidConnectionFunc, XYPosition } from '~/types' import type { Actions, Connection, GraphEdge, HandleType, ValidConnectionFunc, XYPosition } from '~/types'
import { ConnectionMode } from '~/types' import { ConnectionMode } from '~/types'
interface Result { interface Result {
@@ -30,7 +30,7 @@ export const checkElementBelowIsValid = (
isValidConnection: ValidConnectionFunc | undefined, isValidConnection: ValidConnectionFunc | undefined,
doc: Document, doc: Document,
edges: GraphEdge[], edges: GraphEdge[],
getNode: Getters['getNode'], findNode: Actions['findNode'],
) => { ) => {
const clientX = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientX : (event as MouseEvent).clientX const clientX = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientX : (event as MouseEvent).clientX
const clientY = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientY : (event as MouseEvent).clientY const clientY = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientY : (event as MouseEvent).clientY
@@ -73,7 +73,7 @@ export const checkElementBelowIsValid = (
result.isValid = result.isValid =
(isFunction(isValidConnection) (isFunction(isValidConnection)
? isValidConnection(connection, { edges, sourceNode: getNode(sourceId)!, targetNode: getNode(targetId)! }) ? isValidConnection(connection, { edges, sourceNode: findNode(sourceId)!, targetNode: findNode(targetId)! })
: elementBelowNodeId !== nodeId || elementBelowHandleId !== handleId) || : elementBelowNodeId !== nodeId || elementBelowHandleId !== handleId) ||
!result.connection.target || !result.connection.target ||
!result.connection.source !result.connection.source
@@ -113,7 +113,7 @@ export default function useHandle({
startConnection, startConnection,
updateConnection, updateConnection,
endConnection, endConnection,
getNode, findNode,
vueFlowRef, vueFlowRef,
} = $(useVueFlow()) } = $(useVueFlow())
@@ -129,7 +129,7 @@ export default function useHandle({
let validConnectFunc = isValidConnection let validConnectFunc = isValidConnection
const node = getNode(unref(nodeId)) const node = findNode(unref(nodeId))
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
@@ -175,7 +175,7 @@ export default function useHandle({
validConnectFunc, validConnectFunc,
doc, doc,
edges, edges,
getNode, findNode,
) )
if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle) if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle)
@@ -199,7 +199,7 @@ export default function useHandle({
validConnectFunc, validConnectFunc,
doc, doc,
edges, edges,
getNode, findNode,
) )
const isOwnHandle = connection.source === connection.target const isOwnHandle = connection.source === connection.target
@@ -234,7 +234,7 @@ export default function useHandle({
let validConnectFunc = isValidConnection let validConnectFunc = isValidConnection
const node = getNode(unref(nodeId)) const node = findNode(unref(nodeId))
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
@@ -285,7 +285,7 @@ export default function useHandle({
validConnectFunc, validConnectFunc,
doc, doc,
edges, edges,
getNode, findNode,
) )
if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle) if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle)
@@ -309,7 +309,7 @@ export default function useHandle({
validConnectFunc, validConnectFunc,
doc, doc,
edges, edges,
getNode, findNode,
) )
const isOwnHandle = connection.source === connection.target const isOwnHandle = connection.source === connection.target
@@ -343,7 +343,7 @@ export default function useHandle({
} else { } else {
let validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true) let validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true)
const node = getNode(unref(nodeId)) const node = findNode(unref(nodeId))
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
@@ -362,7 +362,7 @@ export default function useHandle({
validConnectFunc, validConnectFunc,
doc, doc,
edges, edges,
getNode, findNode,
) )
const isOwnHandle = connection.source === connection.target const isOwnHandle = connection.source === connection.target
+7 -7
View File
@@ -124,7 +124,7 @@ export function useActions(state: State, getters: ComputedGetters): Actions {
} }
const changes: NodeDimensionChange[] = updates.reduce<NodeDimensionChange[]>((res, update) => { const changes: NodeDimensionChange[] = updates.reduce<NodeDimensionChange[]>((res, update) => {
const node = getters.getNode.value(update.id) const node = findNode(update.id)
if (node) { if (node) {
const dimensions = getDimensions(update.nodeElement) const dimensions = getDimensions(update.nodeElement)
@@ -285,7 +285,7 @@ export function useActions(state: State, getters: ComputedGetters): Actions {
if (!state.initialized && !nodes.length) return if (!state.initialized && !nodes.length) return
if (!state.nodes) state.nodes = [] if (!state.nodes) state.nodes = []
const curr = nodes instanceof Function ? nodes(state.nodes) : nodes const curr = nodes instanceof Function ? nodes(state.nodes) : nodes
state.nodes = createGraphNodes(curr, getters.getNode.value, state.nodes, extent ?? state.nodeExtent) state.nodes = createGraphNodes(curr, findNode, state.nodes, extent ?? state.nodeExtent)
} }
const setEdges: Actions['setEdges'] = (edges) => { const setEdges: Actions['setEdges'] = (edges) => {
@@ -293,8 +293,8 @@ export function useActions(state: State, getters: ComputedGetters): Actions {
const curr = edges instanceof Function ? edges(state.edges) : edges const curr = edges instanceof Function ? edges(state.edges) : edges
state.edges = curr.reduce<GraphEdge[]>((res, edge) => { state.edges = curr.reduce<GraphEdge[]>((res, edge) => {
const sourceNode = getters.getNode.value(edge.source)! const sourceNode = findNode(edge.source)!
const targetNode = getters.getNode.value(edge.target)! const targetNode = findNode(edge.target)!
const missingSource = !sourceNode || typeof sourceNode === 'undefined' const missingSource = !sourceNode || typeof sourceNode === 'undefined'
const missingTarget = !targetNode || typeof targetNode === 'undefined' const missingTarget = !targetNode || typeof targetNode === 'undefined'
@@ -325,7 +325,7 @@ export function useActions(state: State, getters: ComputedGetters): Actions {
const addNodes: Actions['addNodes'] = (nodes, extent) => { const addNodes: Actions['addNodes'] = (nodes, extent) => {
const curr = nodes instanceof Function ? nodes(state.nodes) : nodes const curr = nodes instanceof Function ? nodes(state.nodes) : nodes
const graphNodes = createGraphNodes(curr, getters.getNode.value, state.nodes, extent ?? state.nodeExtent) const graphNodes = createGraphNodes(curr, findNode, state.nodes, extent ?? state.nodeExtent)
const changes = graphNodes.map(createAdditionChange) const changes = graphNodes.map(createAdditionChange)
if (changes.length) state.hooks.nodesChange.trigger(changes) if (changes.length) state.hooks.nodesChange.trigger(changes)
@@ -343,8 +343,8 @@ export function useActions(state: State, getters: ComputedGetters): Actions {
state.edges, state.edges,
) )
if (edge) { if (edge) {
const sourceNode = getters.getNode.value(edge.source)! const sourceNode = findNode(edge.source)!
const targetNode = getters.getNode.value(edge.target)! const targetNode = findNode(edge.target)!
const missingSource = !sourceNode || typeof sourceNode === 'undefined' const missingSource = !sourceNode || typeof sourceNode === 'undefined'
const missingTarget = !targetNode || typeof targetNode === 'undefined' const missingTarget = !targetNode || typeof targetNode === 'undefined'
+6 -20
View File
@@ -1,14 +1,6 @@
import type { Ref } from 'vue' import type { Ref } from 'vue'
import { isNumber } from '@vueuse/shared' import { isNumber } from '@vueuse/shared'
import type { import type { Actions, CoordinateExtent, ExtendedParentExtent, GraphNode, NodeDragItem, XYPosition } from '~/types'
ComputedGetters,
CoordinateExtent,
ExtendedParentExtent,
Getters,
GraphNode,
NodeDragItem,
XYPosition,
} from '~/types'
export function hasSelector(target: Element, selector: string, node: Ref<Element>): boolean { export function hasSelector(target: Element, selector: string, node: Ref<Element>): boolean {
let current = target let current = target
@@ -26,11 +18,11 @@ export function hasSelector(target: Element, selector: string, node: Ref<Element
export function getDragItems( export function getDragItems(
nodes: GraphNode[], nodes: GraphNode[],
mousePos: XYPosition, mousePos: XYPosition,
getNode: Getters['getNode'], findNode: Actions['findNode'],
nodeId?: string, nodeId?: string,
): NodeDragItem[] { ): NodeDragItem[] {
return nodes return nodes
.filter((n) => (n.selected || n.id === nodeId) && (!n.parentNode || !isParentSelected(n, getNode))) .filter((n) => (n.selected || n.id === nodeId) && (!n.parentNode || !isParentSelected(n, findNode)))
.map((n) => .map((n) =>
markRaw({ markRaw({
id: n.id, id: n.id,
@@ -50,19 +42,13 @@ export function getDragItems(
export function getEventHandlerParams({ export function getEventHandlerParams({
id, id,
dragItems, dragItems,
getNode, findNode,
}: { }: {
id?: string id?: string
dragItems: NodeDragItem[] dragItems: NodeDragItem[]
getNode: ComputedGetters['getNode'] findNode: Actions['findNode']
}): [GraphNode, GraphNode[]] { }): [GraphNode, GraphNode[]] {
const extendedDragItems: GraphNode[] = dragItems.map((n) => { const extendedDragItems: GraphNode[] = dragItems.map((n) => findNode(n.id)!)
const node = getNode.value(n.id)!
return {
...node,
}
})
return [id ? extendedDragItems.find((n) => n.id === id)! : extendedDragItems[0], extendedDragItems] return [id ? extendedDragItems.find((n) => n.id === id)! : extendedDragItems[0], extendedDragItems]
} }
+4 -4
View File
@@ -1,5 +1,6 @@
import { isString } from '@vueuse/core' import { isString } from '@vueuse/core'
import type { import type {
Actions,
Box, Box,
Connection, Connection,
CoordinateExtent, CoordinateExtent,
@@ -10,7 +11,6 @@ import type {
ElementData, ElementData,
Elements, Elements,
FlowElement, FlowElement,
Getters,
GraphEdge, GraphEdge,
GraphNode, GraphNode,
Node, Node,
@@ -354,12 +354,12 @@ export const getXYZPos = (parentPos: XYZPosition, computedPosition: XYZPosition)
} }
} }
export const isParentSelected = (node: GraphNode, getNode: Getters['getNode']): boolean => { export const isParentSelected = (node: GraphNode, findNode: Actions['findNode']): boolean => {
if (!node.parentNode) return false if (!node.parentNode) return false
const parent = getNode(node.parentNode) const parent = findNode(node.parentNode)
if (!parent) return false if (!parent) return false
if (parent.selected) return true if (parent.selected) return true
return isParentSelected(parent, getNode) return isParentSelected(parent, findNode)
} }
export const getMarkerId = (marker: EdgeMarkerType | undefined, vueFlowId?: string): string => { export const getMarkerId = (marker: EdgeMarkerType | undefined, vueFlowId?: string): string => {
+4 -4
View File
@@ -1,4 +1,4 @@
import type { Connection, CoordinateExtent, Edge, Getters, GraphEdge, GraphNode, Node } from '~/types' import type { Actions, Connection, CoordinateExtent, Edge, GraphEdge, GraphNode, Node } from '~/types'
export const isDef = <T>(val: T): val is NonNullable<T> => typeof unref(val) !== 'undefined' export const isDef = <T>(val: T): val is NonNullable<T> => typeof unref(val) !== 'undefined'
@@ -51,7 +51,7 @@ export const updateEdgeAction = (edge: GraphEdge, newConnection: Connection, edg
export const createGraphNodes = ( export const createGraphNodes = (
nodes: Node[], nodes: Node[],
getNode: Getters['getNode'], findNode: Actions['findNode'],
currGraphNodes: GraphNode[], currGraphNodes: GraphNode[],
extent: CoordinateExtent, extent: CoordinateExtent,
) => { ) => {
@@ -59,7 +59,7 @@ export const createGraphNodes = (
const graphNodes = nodes.map((node) => { const graphNodes = nodes.map((node) => {
const parsed = parseNode(node, extent, { const parsed = parseNode(node, extent, {
...getNode(node.id), ...findNode(node.id),
parentNode: node.parentNode, parentNode: node.parentNode,
}) })
@@ -80,7 +80,7 @@ export const createGraphNodes = (
if (parentNodes[node.id]) { if (parentNodes[node.id]) {
node.isParent = true node.isParent = true
} }
const parent = node.parentNode ? getNode(node.parentNode) : undefined const parent = node.parentNode ? findNode(node.parentNode) : undefined
if (parent) parent.isParent = true if (parent) parent.isParent = true
} }
}) })