reaflow

repository·master·Indexed 22 days ago

https://github.com/reaviz/reaflow

A modular diagram engine for building static or interactive node-based visualizations and editors in React. Version 5.4.1 features automatic layout via ELKJS, customizable nodes, edges, and ports, and advanced graph logic including nesting and undo/redo support. It provides a Canvas component with a CanvasRef API for imperative control over zooming, panning, and viewport positioning.

Tokens
18.2K
Snippets
42
Records
98
Agent score
82%

What's inside reaflow

  1. Overview of Reaflow features

    master

    Reaflow is a modular diagram engine for building static or interactive editors in React. Key features include:

    • Automatic Layout: Complex layouts leveraging ELKJS.
    • Customization: Easy customization of Nodes, Edges, and Ports.
    • Interactivity: Zooming, panning, centering, and drag-and-drop for nodes, ports, and connections.
    • Advanced Graph Logic: Nesting of nodes/edges, proximity-based node linking, selection helpers, and undo/redo support.
  2. Overview of Reaflow core components

    master

    Reaflow is built using a set of modular components that you can customize to control the appearance and behavior of your flow diagrams. The core components include:

    • Canvas: The root component that hosts the entire flow.
    • Node: The individual element component representing a node in the graph.
    • Edge: The connector component that links nodes together.
    • Port: The exit/entry points located on a node.
    • MarkerArrow: The shape used on edges to indicate direction.
    • Add: A shape used on edges to indicate where a new connection can be dropped.
    • Remove: A shape used on nodes and edges to facilitate deletion.
    • Label: A component used by both nodes and edges to display text.
    • Icon: A component used by nodes to display an icon.
  3. What is REAFLOW?

    master
    REAFLOW is a modular diagram engine designed for building both static visualizations and interactive editors. It is built for React and is highly feature-rich, allowing developers to display complex node-based visualizations with total customizability through its modular architecture.
  4. Understand the categories of Reaflow utility helpers

    master

    Reaflow provides built-in helper functions to manage common interactions with the canvas and the graph. These helpers are categorized into three main types:

    1. CRUD: Helpers for manipulating nodes and edges (Create, Read, Update, Delete).
    2. Graph: Helpers for traversing the graph structure.
    3. Extended Utils: More specialized, use-case focused helpers.

    Note on usage: These helpers are designed as generic starting points. They are not intended to cover every possible specific use case. If a built-in helper does not meet your requirements, you should copy the implementation and adapt it to your specific needs.

  5. Define nodes and edges for a diagram

    master

    To build a diagram in Reaflow, you must define two data structures: nodes and edges.

    • Nodes: Represent the blocks in your diagram. Each node requires a unique id (string). You can optionally include a text or icon property to display content within the node.
    • Edges: Represent the relationships between nodes. Each edge requires a unique id, a from property (the ID of the source node), and a to property (the ID of the target node).
    const nodes = [
      {
        id: '1',
        text: '1'
      },
      {
        id: '2',
        text: '2'
      }
    ];
    
    const edges = [
      {
        id: '1-2',
        from: '1',
        to: '2'
      }
    ];
  6. Understand SVG Z-index limitations in Reaflow

    master

    In Reaflow, custom nodes are rendered using foreignObject, which is an SVG element. Standard CSS z-index has no effect on SVG elements.

    To control the visual stacking order, you must rely on the SVG rendering rule: the last element defined in the DOM is displayed on top of the previous elements. In a Reaflow node, the foreignObject will naturally appear on top of the rect component because it is defined after it in the SVG structure.

  7. Understand Reaflow data shapes

    master

    Reaflow graphs are constructed using three fundamental data shape objects. Understanding these shapes is essential for defining the structure and connectivity of your graph:

    1. NodeData: Represents the element blocks (nodes) rendered in the graph.
    2. EdgeData: Represents the links (edges) connecting nodes.
    3. PortData: Represents specific enter/exit points on a node used to facilitate precise connections between nodes.
  8. Choosing a state manager for Reaflow

    master
    Reaflow is store-agnostic, meaning it does not mandate a specific state management library. You can use any React state manager that fits your application's complexity, such as React.useState for simple applications, or shared state managers like Redux, Recoil, xState, or MobX as your application grows and requires shared state across different components.
  9. How useProximity calculates proximity

    master

    The useProximity hook works by correlating the mouse pointer position to the canvas coordinates, accounting for both canvas offset and zoom levels. It uses the kld-affine library for geometric matrix calculations.

    As a user drags, the hook measures the distance of all nodes relative to the pointer. If the closest node's distance is within the minDistance threshold (which defaults to 40), a match is triggered.

  10. Enable SSR support for Reaflow in Next.js

    master

    When using Reaflow in a Next.js environment, the Canvas component should not be rendered on the server. While rendering it on the server won't crash your application, it will trigger numerous noisy warnings related to useEffect and other client-side hooks.

    To prevent this, wrap the Canvas component in a conditional check to ensure it only renders when the window object is defined (i.e., on the client side).

    import React from 'react';
    import { Canvas } from 'reaflow';
    
    const Page = () => (
      <div style={{position: 'relative', width: '100vw', height: '100vh'}}>
        <div style={{position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, 'backgroundColor': '#F5F5F5'}}>
          {
            // Don't render the Canvas on the server
            typeof window !== 'undefined' && (
              <Canvas
                maxWidth={800}
                maxHeight={600}
                nodes={[
                  {
                    id: '1',
                    text: '1'
                  },
                  {
                    id: '2',
                    text: '2'
                  }
                ]}
                edges={[
                  {
                    id: '1-2',
                    from: '1',
                    to: '2'
                  }
                ]}
              />
            )
          }
        </div>
      </div>
    );
    
    export default Page;
  11. Manage selections manually

    master

    If you do not want the automatic hotkeys or logic provided by useSelection, you can manage selection state manually. You must maintain a state of selected IDs (strings) and pass them to the Canvas component, while manually updating that state via onClick handlers on Node, Edge, or Canvas components.

    import { NodeData, EdgeData } from 'reaflow';
    
    const [selections, setSelections] = useState<string[]>([]);
    
    const [nodes] = useState<NodeData[]>([
      { id: '1', text: 'Node 1' }
    ]);
    
    const [edges] = useState<EdgeData[]>([
      { id: '1-2', from: '1', to: '2' }
    ]);
    
    <Canvas
      nodes={nodes}
      edges={edges}
      selections={selections}
      node={
        <Node
          onClick={(event, node) => {
            setSelections([node.id]);
          }}
        />
      }
      edge={
        <Edge
          onClick={(event, edge) => {
            setSelections([edge.id]);
          }}
        />
      }
      onCanvasClick={(event) => {
        setSelections([]);
      }}
    />
  12. Access the Canvas instance via Refs

    master
    You can obtain a reference to the Canvas instance using a React ref. This allows you to perform imperative actions externally, such as centering the canvas, fitting nodes to the viewport, or controlling zoom levels. To use it, create a ref with the type CanvasRef and pass it to the ref prop of the <Canvas /> component.