reagraph Documentation

repository·master·Indexed 22 days ago

https://github.com/reaviz/reagraph

A high-performance WebGL node-based network graph visualization library built specifically for React applications. It features 2D and 3D layouts (Force Directed, Tree, Radial, Hierarchical), customizable node sizing, and interactive capabilities such as lasso selection, node dragging, and path finding. Key components include GraphCanvas for rendering, GraphScene for detailed scene configuration, and CameraControls for viewport management.

Tokens
11.8K
Snippets
27
Records
45
Agent score
70%

What's inside reagraph

  1. Overview of reagraph features and layouts

    master

    Reagraph is a high-performance WebGL-based network graph visualization library for React.

    Key Features

    • Performance: WebGL-based rendering.
    • Node Customization: Sizing based on attributes, page rank, centrality, or custom logic; node badges; customizable nodes.
    • Interactivity: Dragging nodes, lasso selection, expand/collapse nodes, radial context menu, and path finding.
    • Visuals: Light/Dark mode with custom themes, advanced label placement, edge interpolation/styling, clustering, edge bundling, and highlighting/selection hooks.

    Built-in Layouts

    Reagraph supports various 2D and 3D layouts, including:

    • Force Directed: 2D and 3D
    • Tree: Top Down (2D/3D) and Left Right (2D/3D)
    • Radial: Radial Out (2D/3D)
    • Hierarchical: Top Down (2D) and Left Right (2D)
    • Other: Circular 2D, No Overlap 2D, Force Atlas2 2D, Concentric (2D/3D)
  2. Edge label and sub-label positioning

    master

    The Edge component allows fine-grained control over how text labels are positioned relative to the edge line and each other.

    Label Placement (labelPlacement)

    Controls where the main label sits relative to the edge line:

    • below: Shows the label under the edge line.
    • above: Shows the label above the edge line.
    • inline: Shows the label along the edge line.
    • natural: Uses normal text positions.

    Sub-label Placement (subLabelPlacement)

    Controls where the subLabel is positioned relative to the main label:

    • below: Shows the sub-label below the main label.
    • above: Shows the sub-label above the main label.
  3. Use the GraphScene component

    master

    The GraphScene component is the primary entry point for rendering a graph in Reagraph. It accepts nodes and edges as props and provides extensive configuration for layout, styling, interaction, and event handling.

    Key features include:

    • Layout Control: Supports various layout types (e.g., forceDirected2d, forceDirected3d).
    • Custom Rendering: Allows overriding how nodes (renderNode) and clusters (onRenderCluster) are drawn.
    • Interactivity: Provides hooks for node, edge, and cluster clicks, pointer events, and dragging.
    • Clustering: Supports grouping nodes based on a clusterAttribute (only available with force-directed layouts).
    • Edge Aggregation: Can automatically aggregate edges with the same source and target when aggregateEdges is enabled.
    import { GraphScene } from 'reagraph';
    
    // Example usage of GraphScene
    <GraphScene
      nodes={myNodes}
      edges={myEdges}
      layoutType="forceDirected2d"
      draggable={true}
      onNodeClick={(node) => console.log('Clicked:', node.id)}
    />
  4. Configure ESLint with reaviz-lint-rules

    master

    To use the recommended linting rules for this project, import the reaviz-lint-rules configuration package in your eslint.config.ts file. You can extend these rules by spreading the config into your exported array and adding custom rule overrides in the rules object.

    Note that the base configuration is provided by the reaviz-lint-rules package.

    import config from 'reaviz-lint-rules';
    
    export default [...config, { rules: { 'react/no-unknown-property': 'warn' } }];
  5. Handle selection interaction events

    master

    To make the selection logic work with your UI, you must pass the returned handlers from useSelection to your graph components:

    • onNodeClick: Pass to the component handling node clicks to enable selection via clicking.
    • onCanvasClick: Pass to the canvas click handler to allow clicking empty space to deselect.
    • onNodePointerOver / onNodePointerOut: Pass to node pointer events to enable hover-based highlighting of adjacent elements.
    • onLasso / onLassoEnd: Pass to your lasso/area selection implementation to sync lasso results with the selection state.
  6. Render a network graph with GraphCanvas

    master

    The primary way to render a graph is by using the GraphCanvas component. You must provide a nodes array and an edges array.

    Each node requires a unique id and can optionally include a label. Each edge requires a unique id, a source node ID, and a target node ID.

    import React from 'react';
    import { GraphCanvas } from 'reagraph';
    
    export default () => (
      <GraphCanvas
        nodes={[
          {
            id: 'n-1',
            label: '1'
          },
          {
            id: 'n-2',
            label: '2'
          }
        ]}
        edges={[
          {
            id: '1->2',
            source: 'n-1',
            target: 'n-2',
            label: 'Edge 1-2'
          }
        ]}
      />
    );
  7. Configure useSelection props

    master

    When calling useSelection, you can pass a SelectionProps object to customize selection behavior:

    PropTypeDefaultDescription
    refRefObject<GraphCanvasRef | null>RequiredRef to the graph canvas instance.
    selectionsstring[][]Initial array of selected node/edge IDs.
    activesstring[][]Initial array of active (highlighted) node/edge IDs.
    nodesGraphNode[][]Current node data.
    edgesGraphEdge[][]Current edge data.
    disabledbooleanfalseIf true, selection interactions are disabled.
    focusOnSelectboolean | 'singleOnly'trueIf true, the view fits to selected nodes. 'singleOnly' only fits if one item is selected.
    typeSelectionTypes'single''single', 'multi', or 'multiModifier'.
    pathSelectionTypePathSelectionTypes'direct'Determines how adjacent elements are calculated for selection.
    pathHoverTypePathSelectionTypes'out'Determines how adjacent elements are highlighted on hover.
    onSelection(selectionIds: string[]) => voidundefinedCallback triggered whenever the selection set changes.
  8. Use the useCameraControls hook to manipulate the graph camera

    master

    The useCameraControls hook provides access to the graph's camera controls via a React context. It allows you to programmatically control camera movement, zooming, panning, and state (frozen/unfrozen).

    Note: This hook must be used within a ControlsProvider component, otherwise it will throw an error: `useCameraControls` hook must be used within a `ControlsProvider` component.

    import { useCameraControls } from 'reagraph';
    
    const MyComponent = () => {
      const { zoomIn, resetControls, freeze } = useCameraControls();
    
      return (
        <div>
          <button onClick={() => zoomIn()}>Zoom In</button>
          <button onClick={() => resetControls(true)}>Reset (Animated)</button>
          <button onClick={() => freeze()}>Freeze Camera</button>
        </div>
      );
    };
  9. Use the GraphCanvas component

    master

    The GraphCanvas component is the primary entrypoint for rendering a graph in Reagraph. It is a React component that accepts configuration via GraphCanvasProps and can be controlled via a ref of type GraphCanvasRef.

    import { GraphCanvas } from 'reagraph';
    
    // Basic usage
    const MyGraph = () => (
      <GraphCanvas />
    );
  10. Use the forceDirected layout engine

    master

    The forceDirected function is a layout strategy factory that creates a simulation-based layout for graphs. It supports both 2D and 3D dimensions and includes advanced features like clustering, DAG (Directed Acyclic Graph) modes, and node repulsion.

    When called, it returns a LayoutStrategy object containing a step() method to run the simulation until stability and a getNodePosition(id) method to retrieve the calculated coordinates for a specific node.

    To use it, provide a ForceDirectedLayoutInputs object containing the graph data and configuration parameters.

    import { forceDirected } from './layout/forceDirected';
    
    const layoutStrategy = forceDirected({
      graph: myGraphData,
      dimensions: 2,
      forceLayout: 'forceDirected2d',
      clusters: myClusterMap,
      // ... other configuration options
    });
    
    // Run the simulation until it stabilizes
    layoutStrategy.step();
    
    // Get the position of a node
    const position = layoutStrategy.getNodePosition('node-id');