refactor: moved addNode function outside the handleNode definition

Made sure to minimize responsibilities per function, by taking the addNode logic and moving it into its own function.

ref: N25B-114
This commit is contained in:
JGerla
2025-10-25 18:29:53 +02:00
parent e1d131e642
commit b7cd925c2c

View File

@@ -68,6 +68,59 @@ function DraggableNode({className, children, nodeType, onDrop}: DraggableNodePro
);
}
function addNode(nodeType: string, position: XYPosition) {
const {setNodes} = useFlowStore.getState();
const nds = useFlowStore.getState().nodes;
const newNode = () => {
switch (nodeType) {
case "phase":
{
const phaseNumber = nds.filter((node) => node.type === 'phase').length;
return {
id: `phase-${phaseNumber}`,
type: nodeType,
position,
data: {label: `"new"`, number: phaseNumber},
};
}
case "start":
return {
id: getId(),
type: nodeType,
position,
data: {label: `new start node`},
};
case "end":
return {
id: getId(),
type: nodeType,
position,
data: {label: `new end node`},
};
case "norm":
{
const normNumber = nds.filter((node) => node.type === 'norm').length;
return {
id: `norm-${normNumber}`,
type: nodeType,
position,
data: {label: `new norm node`},
};
}
default: {
return {
id: getId(),
type: nodeType,
position,
data: {label: `new default node`},
};
}
}
}
setNodes(nds.concat(newNode()));
}
/**
* the DndToolbar defines how the drag and drop toolbar component works
* and includes the default onDrop behavior through handleNodeDrop
@@ -75,8 +128,6 @@ function DraggableNode({className, children, nodeType, onDrop}: DraggableNodePro
*/
export function DndToolbar() {
const {screenToFlowPosition} = useReactFlow();
const {setNodes} = useReactFlow();
/**
* handleNodeDrop implements the default onDrop behavior
*/
@@ -94,61 +145,10 @@ export function DndToolbar() {
// Create a new node and add it to the flow
if (isInFlow) {
const position = screenToFlowPosition(screenPosition);
const newNode = () => {
switch (nodeType) {
case "phase":
{
const nds = useFlowStore.getState().nodes;
const phaseNumber = nds.filter((node) => node.type === 'phase').length;
return {
id: `phase-${phaseNumber}`,
type: nodeType,
position,
data: {label: `"new"`, number: phaseNumber},
};
}
case "start":
return {
id: getId(),
type: nodeType,
position,
data: {label: `new start node`},
};
case "end":
return {
id: getId(),
type: nodeType,
position,
data: {label: `new end node`},
};
case "norm":
{
const nds = useFlowStore.getState().nodes;
const normNumber = nds.filter((node) => node.type === 'norm').length;
return {
id: `norm-${normNumber}`,
type: nodeType,
position,
data: {label: `new norm node`},
};
}
default: {
return {
id: getId(),
type: nodeType,
position,
data: {label: `new default node`},
};
}
}
}
setNodes((nds) => nds.concat(newNode()));
addNode(nodeType, position);
}
},
[setNodes, screenToFlowPosition],
[screenToFlowPosition],
);
return (