Skip to content

Instantly share code, notes, and snippets.

@mgaebler
Last active September 1, 2020 11:58
Show Gist options
  • Save mgaebler/32d904e1a93678c2816f9cc0ad00bfaf to your computer and use it in GitHub Desktop.
Save mgaebler/32d904e1a93678c2816f9cc0ad00bfaf to your computer and use it in GitHub Desktop.
cytoscape

Cytoscape

Layout definition

A layout is simply a mapping function: It maps a node to a position. A layout takes as input a set of nodes and edges along with a set of options.

React Example with hooks:

import cytoscape from "cytoscape";
import cola from "cytoscape-cola";
import * as React from "react";

import style from "./style";

const Graph: React.FunctionComponent<{
  elements: cytoscape.ElementDefinition[];
}> = ({ elements }) => {
  const container = React.useRef<HTMLDivElement>(null);
  const graph = React.useRef<cytoscape.Core>();
  const layout = React.useRef<cytoscape.Layouts>();

  React.useEffect(() => {
    if (graph.current) {
      if (layout.current) {
        layout.current.stop();
      }
      graph.current.add(elements);
      layout.current = graph.current.elements().makeLayout({
        name: "cola",
        // name: "drage",
      });
      layout.current.run();
    }
  }, [elements]);

  React.useEffect(() => {
    if (!container.current) {
      return;
    }
    try {
      if (!graph.current) {
        cytoscape.use(cola);
        graph.current = cytoscape({
          elements,
          style,
          maxZoom: 1,
          wheelSensitivity: 0.2,
          container: container.current,
        });
      }
    } catch (error) {
      console.error(error);
    }
    // cleanup
    return () => {
      graph.current && graph.current.destroy();
    };
  }, []);

  return <div style={{ width: "100%", height: "90vh" }} ref={container} />;
};

export default Graph;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment