From 180990b0258a34640c589c1708296da1241bcb8a Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 17 Apr 2023 20:33:32 +0100 Subject: [PATCH] clear connected input if node/edge is removed --- .../ui/src/store/context/ReactFlowContext.js | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/packages/ui/src/store/context/ReactFlowContext.js b/packages/ui/src/store/context/ReactFlowContext.js index b8b32606..1a6b979f 100644 --- a/packages/ui/src/store/context/ReactFlowContext.js +++ b/packages/ui/src/store/context/ReactFlowContext.js @@ -13,13 +13,51 @@ export const flowContext = createContext(initialValue) export const ReactFlowContext = ({ children }) => { const [reactFlowInstance, setReactFlowInstance] = useState(null) - const deleteNode = (id) => { - reactFlowInstance.setNodes(reactFlowInstance.getNodes().filter((n) => n.id !== id)) - reactFlowInstance.setEdges(reactFlowInstance.getEdges().filter((ns) => ns.source !== id && ns.target !== id)) + const deleteNode = (nodeid) => { + deleteConnectedInput(nodeid, 'node') + reactFlowInstance.setNodes(reactFlowInstance.getNodes().filter((n) => n.id !== nodeid)) + reactFlowInstance.setEdges(reactFlowInstance.getEdges().filter((ns) => ns.source !== nodeid && ns.target !== nodeid)) } - const deleteEdge = (id) => { - reactFlowInstance.setEdges(reactFlowInstance.getEdges().filter((edge) => edge.id !== id)) + const deleteEdge = (edgeid) => { + deleteConnectedInput(edgeid, 'edge') + reactFlowInstance.setEdges(reactFlowInstance.getEdges().filter((edge) => edge.id !== edgeid)) + } + + const deleteConnectedInput = (id, type) => { + const connectedEdges = + type === 'node' + ? reactFlowInstance.getEdges().filter((edge) => edge.source === id) + : reactFlowInstance.getEdges().filter((edge) => edge.id === id) + + for (const edge of connectedEdges) { + const targetNodeId = edge.target + const sourceNodeId = edge.source + const targetInput = edge.targetHandle.split('-')[2] + + reactFlowInstance.setNodes((nds) => + nds.map((node) => { + if (node.id === targetNodeId) { + let value + const inputAnchor = node.data.inputAnchors.find((ancr) => ancr.name === targetInput) + if (inputAnchor && inputAnchor.list) { + const values = node.data.inputs[targetInput] || [] + value = values.filter((item) => !item.includes(sourceNodeId)) + } else { + value = '' + } + node.data = { + ...node.data, + inputs: { + ...node.data.inputs, + [targetInput]: value + } + } + } + return node + }) + ) + } } return (