diff --git a/workspace/src/app/views/shared/ReactFlow/ReactFlow.utils.ts b/workspace/src/app/views/shared/ReactFlow/ReactFlow.utils.ts new file mode 100644 index 0000000000..86ac5bab9f --- /dev/null +++ b/workspace/src/app/views/shared/ReactFlow/ReactFlow.utils.ts @@ -0,0 +1,51 @@ +import {Edge, Node} from "react-flow-renderer-lts" +import {ReactFlowElement} from "./typing"; + +/** The elements separated into nodes and edges as its usual starting from react-flow-renderer v10.x */ +interface ReactFlowElements { + nodes: Node[] + edges: Edge[] +} + +const isNode = (element: ReactFlowElement & { source?: string }): boolean => !element.source; + +/** Remove elements from another list of elements. All edges of removed nodes are also removed. */ +const removeElements = (elementsToRemove: ReactFlowElement[], elements: ReactFlowElements): ReactFlowElements => { + const newElements = {...elements} + const nodesToRemove = new Set() + const edgesToRemove = new Set() + elementsToRemove.forEach(elem => { + if(isNode(elem)) { + nodesToRemove.add(elem.id) + } else { + edgesToRemove.add(elem.id) + } + }) + if(nodesToRemove.size) { + newElements.nodes = elements.nodes.filter(node => !nodesToRemove.has(node.id)) + } + if(edgesToRemove.size) { + newElements.edges = elements.edges.filter(edge => + !edgesToRemove.has(edge.id) && !nodesToRemove.has(edge.source) && !nodesToRemove.has(edge.target)) + } + return newElements +} + +/** Remove a list of edges from another list of edges. */ +const removeEdges = (edgesToRemove: Edge[], edges: Edge[]): Edge[] => { + const edgesToRemoveSet = new Set() + edgesToRemove.forEach(edge => edgesToRemoveSet.add(edge.id)) + if(edgesToRemoveSet.size) { + return edges.filter(edge => !edgesToRemoveSet.has(edge.id)) + } else { + return [...edges] + } +} + +const utils = { + isNode, + removeElements, + removeEdges +} + +export default utils diff --git a/workspace/src/app/views/shared/ReactFlow/typing.ts b/workspace/src/app/views/shared/ReactFlow/typing.ts new file mode 100644 index 0000000000..79dd6333f6 --- /dev/null +++ b/workspace/src/app/views/shared/ReactFlow/typing.ts @@ -0,0 +1,4 @@ +import {Node, Edge} from "react-flow-renderer-lts" + +/** Short-cut for either Node or Edge. */ +export type ReactFlowElement = Node | Edge