projectstorm / react-diagrams

a super simple, no-nonsense diagramming library written in react that just works
https://projectstorm.cloud/react-diagrams
MIT License
8.6k stars 1.17k forks source link

Typescript with useContext hook #752

Closed DzoYee closed 3 years ago

DzoYee commented 3 years ago

I want to create a contextProvider to pass around react-diagram paradigms such as engine but I'm running into some typescript errors. Any help would be greatly appreciated.

import React, { useState } from "react";
import createEngine, {
  DefaultLinkModel,
  DefaultNodeModel,
  DiagramEngine,
  DiagramModel,
} from "@projectstorm/react-diagrams";

export const DiagramContext = React.createContext({
  engine: DiagramEngine,
});

export const DiagramProvider = ({ children }: React.PropsWithChildren<{}>) => {
  const [engine, setEngine] = useState(createEngine());

  const model = new DiagramModel();
  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 1",
    color: "rgb(0,192,255)",
  });
  let port2 = node2.addInPort("In");
  node2.setPosition(200, 200);

  const link = port1.link<DefaultLinkModel>(port2);
  link.getOptions().testName = "Test";
  link.addLabel("Hello World!");

  model.addAll(node1, node2, link);

  engine.setModel(model);
  return (
    <DiagramContext.Provider value={{ engine }}>
      {children}
    </DiagramContext.Provider>
  );
};
Screen Shot 2020-10-22 at 5 22 05 PM
renato-bohler commented 3 years ago

It seems the problem is that the defaultValue of this context is set to the class DiagramEngine

What happens if you replace the createContext call with this:

export const DiagramContext = React.createContext({
  engine: createEngine(),
});