Certainly! Let's create a Node Generator for React Flow using React and TypeScript that generates five types of nodes: Input Node, Pre-processing Node, Models Node, Post-process Node, and Output Node. Each node will have a title and properties that determine their handles.
Overview
- Define Node Types: Enumerate the different node types.
- Create Node Components: Define React components for each node type with appropriate handles.
- Implement Node Generator: Create a function to generate nodes based on type and properties.
- Integrate with React Flow: Set up React Flow to use the custom nodes.
1. Define Node Types
First, let's define the different node types using an enumeration for better type safety.
// src/types.ts
export enum NodeType {
Input = 'inputNode',
PreProcessing = 'preProcessingNode',
Models = 'modelsNode',
PostProcess = 'postProcessNode',
Output = 'outputNode',
}
2. Create Node Components
Each node type will have a React component. We'll use React Flow's Handle component to define source and target handles.
// src/nodes/InputNode.tsx
import React from 'react';
import { Handle, Position } from 'reactflow';
interface InputNodeProps {
data: {
label: string;
sources: number; // Number of source handles
};
}
const InputNode: React.FC<InputNodeProps> = ({ data }) => {
return (
<div className="node input-node">
<div>{data.label}</div>
{Array.from({ length: data.sources }).map((_, index) => (
<Handle
key={`source-${index}`}
type="source"
position={Position.Right}
id={`source-${index}`}
/>
))}
</div>
);
};
export default InputNode;
Repeat similar structures for other node types:
// src/nodes/OutputNode.tsx
import React from 'react';
import { Handle, Position } from 'reactflow';
interface OutputNodeProps {
data: {
label: string;
targets: number; // Number of target handles
};
}
const OutputNode: React.FC<OutputNodeProps> = ({ data }) => {
return (
<div className="node output-node">
<div>{data.label}</div>
{Array.from({ length: data.targets }).map((_, index) => (
<Handle
key={`target-${index}`}
type="target"
position={Position.Left}
id={`target-${index}`}
/>
))}
</div>
);
};
export default OutputNode;
// src/nodes/CustomNode.tsx (for Pre-processing, Models, Post-process)
import React from 'react';
import { Handle, Position } from 'reactflow';
interface CustomNodeProps {
data: {
label: string;
sources?: number; // Number of source handles
targets?: number; // Number of target handles
};
}
const CustomNode: React.FC<CustomNodeProps> = ({ data }) => {
return (
<div className="node custom-node">
<div>{data.label}</div>
{data.sources &&
Array.from({ length: data.sources }).map((_, index) => (
<Handle
key={`source-${index}`}
type="source"
position={Position.Left}
id={`source-${index}`}
/>
))}
{data.targets &&
Array.from({ length: data.targets }).map((_, index) => (
<Handle
key={`target-${index}`}
type="target"
position={Position.Right}
id={`target-${index}`}
/>
))}
</div>
);
};
export default CustomNode;
3. Implement Node Generator
Create a generator function or component that returns the appropriate node based on the type and properties.
// src/NodeGenerator.tsx
import React from 'react';
import { Handle, Position } from 'reactflow';
import InputNode from './nodes/InputNode';
import OutputNode from './nodes/OutputNode';
import CustomNode from './nodes/CustomNode';
import { NodeType } from './types';
interface NodeData {
label: string;
// Properties determining number of handles
handles?: {
sources?: number;
targets?: number;
};
}
interface NodeGeneratorProps {
type: NodeType;
id: string;
data: NodeData;
}
const NodeGenerator: React.FC<NodeGeneratorProps> = ({ type, id, data }) => {
switch (type) {
case NodeType.Input:
return <InputNode id={id} data={{ label: data.label, sources: data.handles?.sources ?? 1 }} />;
case NodeType.Output:
return <OutputNode id={id} data={{ label: data.label, targets: data.handles?.targets ?? 1 }} />;
case NodeType.PreProcessing:
case NodeType.Models:
case NodeType.PostProcess:
return (
<CustomNode
id={id}
data={{
label: data.label,
sources: data.handles?.sources,
targets: data.handles?.targets,
}}
/>
);
default:
return <div>Unknown Node</div>;
}
};
export default NodeGenerator;
4. Integrate with React Flow
Finally, set up React Flow to use the custom nodes.
// src/App.tsx
import React, { useCallback, useState } from 'react';
import ReactFlow, {
addEdge,
Controls,
ReactFlowProvider,
OnConnect,
Elements,
Connection,
} from 'reactflow';
import 'reactflow/dist/style.css';
import NodeGenerator from './NodeGenerator';
import { NodeType } from './types';
const nodeTypes = {
inputNode: NodeGenerator,
outputNode: NodeGenerator,
preProcessingNode: NodeGenerator,
modelsNode: NodeGenerator,
postProcessNode: NodeGenerator,
};
const initialElements: Elements = [
{
id: '1',
type: NodeType.Input,
position: { x: 250, y: 5 },
data: { label: 'Input Node', handles: { sources: 2 } },
},
{
id: '2',
type: NodeType.PreProcessing,
position: { x: 100, y: 100 },
data: { label: 'Pre-processing Node', handles: { sources: 1, targets: 2 } },
},
{
id: '3',
type: NodeType.Models,
position: { x: 400, y: 100 },
data: { label: 'Models Node', handles: { sources: 2, targets: 2 } },
},
{
id: '4',
type: NodeType.PostProcess,
position: { x: 250, y: 200 },
data: { label: 'Post-process Node', handles: { sources: 1, targets: 1 } },
},
{
id: '5',
type: NodeType.Output,
position: { x: 250, y: 300 },
data: { label: 'Output Node', handles: { targets: 1 } },
},
];
const App: React.FC = () => {
const [elements, setElements] = useState<Elements>(initialElements);
const onConnect: OnConnect = useCallback(
(params: Connection | any) => setElements((els) => addEdge(params, els)),
[]
);
return (
<ReactFlowProvider>
<div style={{ height: 600 }}>
<ReactFlow
elements={elements}
onConnect={onConnect}
nodeTypes={nodeTypes}
fitView
>
<Controls />
</ReactFlow>
</div>
</ReactFlowProvider>
);
};
export default App;
Styling the Nodes
You can style the nodes using CSS to differentiate them visually.
/* src/App.css */
.node {
padding: 10px;
border-radius: 5px;
color: #fff;
font-weight: bold;
}
.input-node {
background-color: #1e90ff;
}
.output-node {
background-color: #ff6347;
}
.custom-node {
background-color: #32cd32;
}
Make sure to import the CSS in your App.tsx or main entry file:
// src/App.tsx
import './App.css';
// ... rest of the code
Explanation
-
Node Components: We created separate components for InputNode, OutputNode, and a generic CustomNode for the other types. Each node receives data as props, which includes the label and handle information.
-
Handles:
- Input Node: Only source handles on the right side.
- Output Node: Only target handles on the left side.
- Custom Nodes: Both source and target handles, with positions based on whether they are sources or targets.
-
Node Generator: The NodeGenerator component takes the node type and data, then renders the appropriate node component with the specified number of handles.
-
React Flow Integration: In the App component, we define the nodeTypes mapping to use our NodeGenerator for all custom node types. We also set up some initial elements to demonstrate the nodes and their connections.
-
Styling: Basic CSS is added to differentiate node types visually. You can enhance the styles as needed.
Additional Enhancements
-
Dynamic Handle Positions: Depending on your design, you might want to position handles dynamically (e.g., top, bottom). Adjust the Position prop in the Handle component accordingly.
-
Draggable Handles: React Flow handles are draggable by default, allowing users to create connections interactively.
-
Custom Properties: Extend NodeData to include more properties for each node type as needed.
-
Validation: Implement validation logic to control which nodes can connect to each other.
Final Thoughts
This setup provides a flexible and scalable way to generate different node types in React Flow with customizable handles. You can further extend this by adding more functionality, such as context menus, custom styles, and interactive properties.
Feel free to adjust the code snippets to fit your specific project structure and requirements. Let me know if you need further assistance!