@gravity-ui/graph

中文文档
1.13.1发布于 2026/11/06MITTypeScriptESM + CJS近 30 天下载 2.4万

Modern graph editor component

原始使用文档
文档目录15 节
  1. Motivation
  2. How It Works
  3. Install
  4. Usage
  5. React Example
  6. Vanilla JavaScript Example
  7. Live Examples
  8. Documentation
  9. Table of Contents
  10. License
  11. For AI agents
  12. When to use
  13. When not to use
  14. Common pitfalls
  15. Documentation for AI agents

@gravity-ui/graph · npm package Release storybook

Migration Guide from 0.x to 1.x →

A graph visualization library that combines the best of both worlds:

  • Canvas for high performance when viewing the full graph
  • HTML/React for rich interactions when zoomed in

No more choosing between performance and interactivity. Perfect for large diagrams, flowcharts, and node-based editors.

preview graph.

Motivation

Modern web applications often require complex visualization and interactivity, but existing solutions typically focus on a single rendering technology:

  • Canvas offers high performance for complex graphics but is limited in text handling and interactivity.
  • HTML DOM is convenient for interfaces but less efficient for complex graphics or large numbers of elements.

@gravity-ui/graph solves this by automatically switching between Canvas and HTML based on zoom level:

  • Zoomed Out: Uses Canvas for efficient rendering of the full graph
  • Medium Zoom: Shows schematic view with basic interactivity
  • Zoomed In: Switches to HTML/React components for rich interactions

How It Works

The library uses a smart rendering system that automatically manages the transition between Canvas and React components:

  1. At low zoom levels, everything is rendered on Canvas for performance
  2. When zooming in to detailed view, the GraphCanvas component:
    • Tracks camera viewport and scale changes
    • Calculates which blocks are visible in the current viewport (with padding for smooth scrolling)
    • Renders React components only for visible blocks
    • Automatically updates the list when scrolling or zooming
    • Removes React components when zooming out
// Example of React components rendering
const MyGraph = () => {
  return (
    <GraphCanvas
      graph={graph}
      renderBlock={(graph, block) => (
        <MyCustomBlockComponent
          graph={graph}
          block={block}
        />
      )}
    />
  );
};

Storybook

Install

npm install @gravity-ui/graph

Usage

React Example

Detailed React Components Documentation

import React, { useEffect } from "react";
import type { Graph, TBlock } from "@gravity-ui/graph";
import { EAnchorType, GraphState } from "@gravity-ui/graph";
import { GraphCanvas, GraphBlock, useGraph } from "@gravity-ui/graph/react";

const config = {};

export function GraphEditor() {
  const { graph, setEntities, start } = useGraph(config);

  useEffect(() => {
    setEntities({
      blocks: [
        {
          is: "block-action",
          id: "action_1",
          x: -100,
          y: -450,
          width: 126,
          height: 126,
          selected: true,
          name: "Block #1",
          anchors: [
            {
              id: "out1",
              blockId: "action_1",
              type: EAnchorType.OUT,
              index: 0,
            },
          ],
        },
        {
          id: "action_2",
          is: "block-action",
          x: 253,
          y: 176,
          width: 126,
          height: 126,
          selected: false,
          name: "Block #2",
          anchors: [
            {
              id: "in1",
              blockId: "action_2",
              type: EAnchorType.IN,
              index: 0,
            },
          ],
        },
      ],
      connections: [
        {
          sourceBlockId: "action_1",
          sourceAnchorId: "out1",
          targetBlockId: "action_2",
          targetAnchorId: "in1",
        },
      ],
    });
  }, [setEntities]);

  const renderBlockFn = (graph: Graph, block: TBlock) => {
    return (
      <GraphBlock graph={graph} block={block}>
        {block.id}
      </GraphBlock>
    );
  };

  return (
    <GraphCanvas
      graph={graph}
      renderBlock={renderBlockFn}
      onStateChanged={({ state }) => {
        if (state === GraphState.ATTACHED) {
          start();
          graph.zoomTo("center", { padding: 300 });
        }
      }}
    />
  );
}

Vanilla JavaScript Example

import { Graph } from "@gravity-ui/graph";

// Create container element
const container = document.createElement('div');
container.style.width = '100vw';
container.style.height = '100vh';
container.style.overflow = 'hidden';
document.body.appendChild(container);

// Initialize graph with configuration
const graph = new Graph({
    configurationName: "example",
    blocks: [],
    connections: [],
    settings: {
        canDragCamera: true,
        canZoomCamera: true,
        useBezierConnections: true,
        showConnectionArrows: true
    }
}, container);

// Add blocks and connections
graph.setEntities({
    blocks: [
        {
            is: "block-action",
            id: "block1",
            x: 100,
            y: 100,
            width: 120,
            height: 120,
            name: "Block #1",
            anchors: [
                {
                    id: "out1",
                    blockId: "block1",
                    type: EAnchorType.OUT,
                    index: 0
                }
            ]
        },
        {
            is: "block-action",
            id: "block2",
            x: 300,
            y: 300,
            width: 120,
            height: 120,
            name: "Block #2",
            anchors: [
                {
                    id: "in1",
                    blockId: "block2",
                    type: EAnchorType.IN,
                    index: 0
                }
            ]
        }
    ],
    connections: [
        {
            sourceBlockId: "block1",
            sourceAnchorId: "out1",
            targetBlockId: "block2",
            targetAnchorId: "in1"
        }
    ]
});

// Start rendering
graph.start();

// Center the view
graph.zoomTo("center", { padding: 100 });

Live Examples

Documentation

Table of Contents

  1. System

  2. Components

  3. Rendering

  4. Blocks and Connections

  5. Testing

License

Distributed under the MIT License. See LICENSE for details.

For AI agents

A hybrid Canvas/React graph editor for node-based diagrams — reach for it to build flowcharts, node editors, or large interactive diagrams where Canvas gives performance at low zoom and React components give rich interactivity when zoomed in.

When to use

  • Node-based editors (flowcharts, pipelines, visual builders) with hundreds/thousands of nodes and connections.
  • Mixed rendering: Canvas for the full-graph overview, React components for the blocks visible in the viewport at high zoom.
  • Vanilla JS or React consumers — the core Graph class is framework-agnostic; @gravity-ui/graph/react provides the React bindings.

When not to use

  • To plot numeric data series (line/bar/scatter charts), use @gravity-ui/charts or @gravity-ui/yagr — graph is a node/edge diagram editor, not a data chart.
  • For a static, non-editable diagram with few nodes, an SVG or a simpler diagram lib may suffice without the Canvas/React viewport machinery.

Common pitfalls

  • Hallucinated import GraphEditor — the React components are GraphCanvas, GraphBlock, and the useGraph hook, imported from @gravity-ui/graph/react; the core class is Graph from @gravity-ui/graph.
  • Calling graph methods before ATTACHED state — call start()/zoomTo(...) inside the onStateChanged callback when state === GraphState.ATTACHED, not on mount.
  • Forgetting setEntities — useGraph returns graph, setEntities, start; data only appears after setEntities({blocks, connections}).
  • Mixing anchor types — connections must reference existing anchor ids with matching EAnchorType (IN/OUT) on the source and target blocks.

Documentation for AI agents

Agent-readable documentation for the installed version is located in node_modules/@gravity-ui/graph/build/docs/INDEX.md.

版本与发布记录

@gravity-ui/graph 共发布 71 个版本,首次发布于 2024/08/28;过去 12 个月发布了 34 个版本。

版本发布日期距今
1.13.1latest2026/11/0610 天前
1.13.02026/11/0314 天前
1.12.22026/10/021 个月前
1.12.12026/09/231 个月前
1.12.02026/09/211 个月前
1.11.32026/07/164 个月前

关于 @gravity-ui/graph 的常见问题

@gravity-ui/graph 是什么?

Modern graph editor component

如何安装 @gravity-ui/graph?

在项目目录运行 npm install @gravity-ui/graph,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^17.0.0 || ^18.0.0)、react-dom(^17.0.0 || ^18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gravity-ui/graph 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gravity-ui/graph 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gravity-ui/graph 可以商用吗?

@gravity-ui/graph 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gravity-ui/graph 的下载量有多少?

根据 npm 官方下载统计,@gravity-ui/graph 在 2026/10/17 – 2026/11/15 这 30 天内被下载 23,567 次,日均约 786 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gravity-ui/graph 还在维护吗?

最新版本 1.13.1 发布于 2026/11/06(10 天前);至今共发布 71 个版本,其中过去 12 个月发布了 34 个;首次发布于 2024/08/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。