To use the library in a TypeScript project, import the core engine creation function, default models, and the canvas widget. The library provides advanced types out of the box.
Follow these steps to bootstrap a diagram:
- Initialize the Engine: Use
createEngine() to create a DiagramEngine instance with default configurations. - Create Nodes: Instantiate
DefaultNodeModel objects, set their positions, and add ports using addOutPort or addInPort. - Create Links: Link ports together using the
.link<T>() method on a port. You can add labels to the resulting link. - Assemble the Model: Create a
DiagramModel, add your nodes and links to it using .addAll(), and then pass the model to the engine via engine.setModel(model). - Render: Use the
CanvasWidget component from @projectstorm/react-canvas-core and pass the engine as a prop.
import createEngine, {
DefaultLinkModel,
DefaultNodeModel,
DiagramModel
} from '@projectstorm/react-diagrams';
import {
CanvasWidget
} from '@projectstorm/react-canvas-core';
// 1. Create the engine
const engine = createEngine();
// 2. Create nodes
const node1 = new DefaultNodeModel({
name: 'Node 1',
color: 'rgb(0,192,255)',
});
node1.setPosition(100, 100);
let port1 = node1.addOutPort('Out');
const node2 = new DefaultNodeModel({
name: 'Node 2',
color: 'rgb(0,192,255)',
});
node2.setPosition(100, 100);
let port2 = node2.addInPort('In');
// 3. Link ports
const link = port1.link<DefaultLinkModel>(port2);
link.addLabel('Hello World!');
// 4. Setup the model
const model = new DiagramModel();
model.addAll(node1, node2, link);
engine.setModel(model);
// 5. Render in React
// <CanvasWidget engine={engine} />