К основному содержанию
скилл CX Codex

dagre-react-flow — скилл для Claude Code: что делает и как установить

Скилл dagre-react-flow настраивает автоматическую раскладку направленных графов в React Flow с помощью dagre. Помогает строить иерархические деревья и выравнивать узлы по направлениям.

Apache-2.0 257 установок ★ 89 обновлён 2026-09-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add existential-birds/beagle --skill dagre-react-flow -a claude-code
Открыть на GitHub

Что делает dagre-react-flow

Скилл содержит шаблоны и правила для интеграции @dagrejs/dagre с библиотекой @xyflow/react. React Flow только рендерит интерфейс. Вычислением иерархии занимается dagre. Скилл учит агента писать функцию getLayoutedElements, которая строит граф через dagre.graphlib.Graph и возвращает узлы с новыми координатами.

Главная сложность связки кроется в разнице координатных сеток. Dagre возвращает центр элемента. React Flow требует координаты левого верхнего угла. Без вычитания половины ширины и высоты узлы встанут криво. Правила скилла контролируют пересчёт координат и задают направления через rankdir: TB для деревьев сверху вниз, LR для горизонтальных схем, а также BT и RL.

Для работы нужны пакеты @dagrejs/dagre и @xyflow/react. Алгоритм требует явные размеры узлов: фиксированные значения, параметры из объекта данных или поле node.measured. Метод fitView вызывается через requestAnimationFrame, чтобы React Flow успел зафиксировать обновлённое состояние.

Какие задачи решает

  • вычислить координаты узлов и рёбер в @xyflow/react через @dagrejs/dagre
  • перевести координаты центра из dagre в левый верхний угол React Flow
  • настроить иерархическую ориентацию графа по вертикали или горизонтали
  • синхронизировать вызов fitView после пересчёта позиций графа

Примеры запросов агенту

  • Сделай автоматическую раскладку дерева в React Flow через dagre
  • Напиши функцию getLayoutedElements с горизонтальной ориентацией rankdir LR
  • Поправь смещение координат узлов между dagre и @xyflow/react

Как установить dagre-react-flow

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill dagre-react-flow -a claude-code

2Вручную: положить файлы

~/.claude/skills/dagre-react-flow/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/dagre-react-flow/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о dagre-react-flow

Как установить dagre-react-flow в Claude Code?

Запустите команду npx skills add existential-birds/beagle --skill dagre-react-flow -a claude-code. Файл навыка будет сохранён в ~/.claude/skills/dagre-react-flow/SKILL.md.

Зачем использовать dagre вместе с React Flow?

React Flow только отображает граф, но не умеет автоматически расставлять узлы по уровням. Dagre рассчитывает иерархические координаты для деревьев и схем процессов.

Почему узлы смещаются при передаче координат из dagre в React Flow?

Dagre возвращает координаты центра узла, а React Flow ожидает левый верхний угол. Для корректной позиции нужно вычесть половину ширины и высоты узла.

Исходный текст

SKILL.md · Apache-2.0
---
name: dagre-react-flow
description: Automatic graph layout using dagre with React Flow (@xyflow/react). Use when implementing auto-layout, hierarchical layouts, tree structures, or arranging nodes programmatically. Triggers on dagre, auto-layout, automatic layout, getLayoutedElements, rankdir, hierarchical graph.
---

# Dagre with React Flow

Dagre is a JavaScript library for laying out directed graphs. It computes optimal node positions for hierarchical/tree layouts. React Flow handles rendering; dagre handles positioning.

## Quick Start

```bash
pnpm add @dagrejs/dagre
```

```typescript
import dagre from '@dagrejs/dagre';
import { Node, Edge } from '@xyflow/react';

const getLayoutedElements = (
  nodes: Node[],
  edges: Edge[],
  direction: 'TB' | 'LR' = 'TB'
) => {
  const g = new dagre.graphlib.Graph();
  g.setGraph({ rankdir: direction });
  g.setDefaultEdgeLabel(() => ({}));

  nodes.forEach((node) => {
    g.setNode(node.id, { width: 172, height: 36 });
  });

  edges.forEach((edge) => {
    g.setEdge(edge.source, edge.target);
  });

  dagre.layout(g);

  const layoutedNodes = nodes.map((node) => {
    const pos = g.node(node.id);
    return {
      ...node,
      position: { x: pos.x - 86, y: pos.y - 18 }, // Center to top-left
    };
  });

  return { nodes: layoutedNodes, edges };
};
```

## Core Concepts

### Coordinate System Difference

**Critical:** Dagre returns center coordinates; React Flow uses top-left.

```typescript
// Dagre output: center of node
const dagrePos = g.node(nodeId); // { x: 100, y: 50 } = center

// React Flow expects: top-left corner
const rfPosition = {
  x: dagrePos.x - nodeWidth / 2,
  y: dagrePos.y - nodeHeight / 2,
};
```

### Node Dimensions

Dagre requires explicit dimensions. Three approaches:

**1. Fixed dimensions (simplest):**
```typescript
g.setNode(node.id, { width: 172, height: 36 });
```

**2. Per-node dimensions from data:**
```typescript
g.setNode(node.id, {
  width: node.data.width ?? 172,
  height: node.data.height ?? 36,
});
```

**3. Measured dimensions (most accurate):**
```typescript
// After React Flow measures nodes
g.setNode(node.id, {
  width: node.measured?.width ?? 172,
  height: node.measured?.height ?? 36,
});
```

### Layout Directions

| Value | Direction | Use Case |
|-------|-----------|----------|
| `TB` | Top to Bottom | Org charts, decision trees |
| `BT` | Bottom to Top | Dependency graphs (deps at bottom) |
| `LR` | Left to Right | Timelines, horizontal flows |
| `RL` | Right to Left | RTL layouts |

```typescript
g.setGraph({ rankdir: 'LR' }); // Horizontal layout
```

## Hard gates

Run these in order before treating layout as correct (each step has an objective pass condition):

1. **Dimensions match conversion** — For every node id, the `width` and `height` given to `g.setNode` for that id are the same numbers used to compute `position.x` / `position.y` from `g.node(id)` (half-width / half-height must match the dagre node box).
2. **Center → top-left** — `position` is `{ x: centerX - width/2, y: centerY - height/2 }`, not raw `g.node(id).x` / `.y` alone.
3. **React Flow state update** — After programmatic layout, `setNodes` / `setEdges` receive a **new** array instance (e.g. `[...layouted]` or `layouted.map(...)`), not the previous reference unchanged.
4. **Optional sanity** — If you use `fitView` after layout, it runs after nodes are committed (e.g. next `requestAnimationFrame` or `setTimeout(0)`), not in the same synchronous tick as `setNodes` with stale measurements.

## Complete Implementation

### Basic Layout Function

```typescript
import dagre from '@dagrejs/dagre';
import type { Node, Edge } from '@xyflow/react';

interface LayoutOptions {
  direction?: 'TB' | 'BT' | 'LR' | 'RL';
  nodeWidth?: number;
  nodeHeight?: number;
  nodesep?: number;  // Horizontal spacing
  ranksep?: number;  // Vertical spacing (between ranks)
}

export function getLayoutedElements(
  nodes: Node[],
  edges: Edge[],
  options: LayoutOptions = {}
): { nodes: Node[]; edges: Edge[] } {
  const {
    direction = 'TB',
    nodeWidth = 172,
    nodeHeight = 36,
    nodesep = 50,
    ranksep = 50,
  } = options;

  const g = new dagre.graphlib.Graph();
  g.setGraph({ rankdir: direction, nodesep, ranksep });
  g.setDefaultEdgeLabel(() => ({}));

  nodes.forEach((node) => {
    const width = node.measured?.width ?? nodeWidth;
    const height = node.measured?.height ?? nodeHeight;
    g.setNode(node.id, { width, height });
  });

  edges.forEach((edge) => {
    g.setEdge(edge.source, edge.target);
  });

  dagre.layout(g);

  const layoutedNodes = nodes.map((node) => {
    const pos = g.node(node.id);
    const width = node.measured?.width ?? nodeWidth;
    const height = node.measured?.height ?? nodeHeight;

    return {
      ...node,
      position: {
        x: pos.x - width / 2,
        y: pos.y - height / 2,
      },
    };
  });

  return { nodes: layoutedNodes, edges };
}
```

### React Flow Integration

```tsx
import { useCallback } from 'react';
import {
  ReactFlow,
  useNodesState,
  useEdgesState,
  useReactFlow,
  ReactFlowProvider,
} from '@xyflow/react';
import { getLayoutedElements } from './layout';

const initialNodes = [
  { id: '1', data: { label: 'Start' }, position: { x: 0, y: 0 } },
  { id: '2', data: { label: 'Process' }, position: { x: 0, y: 0 } },
  { id: '3', data: { label: 'End' }, position: { x: 0, y: 0 } },
];

const initialEdges = [
  { id: 'e1-2', source: '1', target: '2' },
  { id: 'e2-3', source: '2', target: '3' },
];

// Apply initial layout
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
  initialNodes,
  initialEdges,
  { direction: 'TB' }
);

function Flow() {
  const [nodes, setNodes, onNodesChange] = useNodesState(layoutedNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(layoutedEdges);
  const { fitView } = useReactFlow();

  const onLayout = useCallback((direction: 'TB' | 'LR') => {
    const { nodes: newNodes, edges: newEdges } = getLayoutedElements(
      nodes,
      edges,
      { direction }
    );

    setNodes([...newNodes]);
    setEdges([...newEdges]);

    // Fit view after layout with animation
    window.requestAnimationFrame(() => {
      fitView({ duration: 300 });
    });
  }, [nodes, edges, setNodes, setEdges, fitView]);

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <div style={{ position: 'absolute', zIndex: 10, padding: 10 }}>
        <button onClick={() => onLayout('TB')}>Vertical</button>
        <button onClick={() => onLayout('LR')}>Horizontal</button>
      </div>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        fitView
      />
    </div>
  );
}

export default function App() {
  return (
    <ReactFlowProvider>
      <Flow />
    </ReactFlowProvider>
  );
}
```

## useAutoLayout Hook

Reusable hook for automatic layout:

```typescript
import { useCallback, useEffect, useRef } from 'react';
import {
  useReactFlow,
  useNodesInitialized,
  type Node,
  type Edge,
} from '@xyflow/react';
import dagre from '@dagrejs/dagre';

interface UseAutoLayoutOptions {
  direction?: 'TB' | 'BT' | 'LR' | 'RL';
  nodesep?: number;
  ranksep?: number;
}

export function useAutoLayout(options: UseAutoLayoutOptions = {}) {
  const { direction = 'TB', nodesep = 50, ranksep = 50 } = options;
  const { getNodes, getEdges, setNodes, fitView } = useReactFlow();
  const nodesInitialized = useNodesInitialized();
  const layoutApplied = useRef(false);

  const runLayout = useCallback(() => {
    const nodes = getNodes();
    const edges = getEdges();

    const g = new dagre.graphlib.Graph();
    g.setGraph({ rankdir: direction, nodesep, ranksep });
    g.setDefaultEdgeLabel(() => ({}));

    nodes.forEach((node) => {
      g.setNode(node.id, {
        width: node.measured?.width ?? 172,
        height: node.measured?.height ?? 36,
      });
    });

    edges.forEach((edge) => {
      g.setEdge(edge.source, edge.target);
    });

    dagre.layout(g);

    const layouted = nodes.map((node) => {
      const pos = g.node(node.id);
      const width = node.measured?.width ?? 172;
      const height = node.measured?.height ?? 36;

      return {
        ...node,
        position: { x: pos.x - width / 2, y: pos.y - height / 2 },
      };
    });

    setNodes(layouted);
    window.requestAnimationFrame(() => fitView({ duration: 200 }));
  }, [direction, nodesep, ranksep, getNodes, getEdges, setNodes, fitView]);

  // Auto-layout on initialization
  useEffect(() => {
    if (nodesInitialized && !layoutApplied.current) {
      runLayout();
      layoutApplied.current = true;
    }
  }, [nodesInitialized, runLayout]);

  return { runLayout };
}
```

Usage:

```tsx
function Flow() {
  const { runLayout } = useAutoLayout({ direction: 'LR', ranksep: 100 });

  return (
    <>
      <button onClick={runLayout}>Re-layout</button>
      <ReactFlow ... />
    </>
  );
}
```

## Edge Options

Control edge routing with weight and minlen:

```typescript
edges.forEach((edge) => {
  g.setEdge(edge.source, edge.target, {
    weight: edge.data?.priority ?? 1,  // Higher = more direct path
    minlen: edge.data?.minRanks ?? 1,  // Minimum ranks between nodes
  });
});
```

**weight**: Higher weight edges are prioritized for shorter, more direct paths.

**minlen**: Forces minimum rank separation between connected nodes.

```typescript
// Force 2 ranks between nodes
g.setEdge('a', 'b', { minlen: 2 });
```

## Common Patterns

### Handle Position Based on Direction

Adjust handles for horizontal vs vertical layouts:

```tsx
function CustomNode({ data }: NodeProps) {
  const isHorizontal = data.direction === 'LR' || data.direction === 'RL';

  return (
    <div>
      <Handle
        type="target"
        position={isHorizontal ? Position.Left : Position.Top}
      />
      <div>{data.label}</div>
      <Handle
        type="source"
        position={isHorizontal ? Position.Right : Position.Bottom}
      />
    </div>
  );
}
```

### Animated Layout Transitions

Smooth position changes using CSS transitions:

```css
.react-flow__node {
  transition: transform 300ms ease-out;
}
```

For programmatic animation, see [reference.md](reference.md#animated-layout-transitions).

### Layout with Node Groups

Exclude group nodes from dagre layout:

```typescript
const layoutWithGroups = (nodes: Node[], edges: Edge[]) => {
  // Separate regular nodes from groups
  const regularNodes = nodes.filter((n) => n.type !== 'group');
  const groupNodes = nodes.filter((n) => n.type === 'group');

  // Layout only regular nodes
  const { nodes: layouted } = getLayoutedElements(regularNodes, edges);

  // Combine back
  return { nodes: [...groupNodes, ...layouted], edges };
};
```

## Troubleshooting

### Nodes Overlapping

Increase spacing:

```typescript
g.setGraph({
  rankdir: 'TB',
  nodesep: 100,  // Increase horizontal spacing
  ranksep: 100,  // Increase vertical spacing
});
```

### Layout Not Updating

Ensure new array references:

```typescript
// Wrong - same reference
setNodes(layoutedNodes);

// Correct - new reference
setNodes([...layoutedNodes]);
```

### Nodes at Wrong Position

Check coordinate conversion:

```typescript
// Dagre returns center, React Flow needs top-left
position: {
  x: pos.x - width / 2,   // Not just pos.x
  y: pos.y - height / 2,  // Not just pos.y
}
```

### Performance with Large Graphs

- Layout in a Web Worker
- Debounce layout calls
- Use `useMemo` for layout function
- Only re-layout changed portions

## Configuration Reference

See [reference.md](reference.md) for complete dagre configuration options.

© existential-birds · Apache-2.0 · existential-birds/beagle

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
react-flow framara Подсказывает агентам, как строить интерактивные нодовые графы на React Flow v12: кастомные узлы, рёбра, ручки, состояние, раскладка, производительность. CX Codex +1 868установок react-flow-node-ts Microsoft Скилл react-flow-node-ts генерирует типизированные узлы для холста React Flow со связками Handle и стором Zustand. Пригодится при сборке визуальных редакторов и пайплайнов. CX Codex +1 2установок xyflow-wasp-drone Legion Code Inc. xyflow-wasp-drone — субагент для Claude Code, который настраивает React Flow и Svelte Flow, управляет состоянием канваса и добавляет узлы, рёбра и раскладки. CX Codex ★ 96звёзд репо reactflow-fundamentals TheBushidoCollective Скилл reactflow-fundamentals помогает создавать блок-схемы, редакторы пайплайнов и графы на React Flow. Подсказывает агенту готовые структуры узлов, рёбер и элементов управления. CX Codex +1 138установок reactflow-custom-nodes TheBushidoCollective Скилл reactflow-custom-nodes учит агента создавать кастомные узлы, рёбра и хендлы для React Flow: настраиваемые компоненты, изменяемые размеры, тулбары. CX Codex +1 112установок Frontend Developer microsoft Субагент Frontend Developer в Claude Code собирает узлы холста CoreAI DIY на React 19, React Flow, Zustand и Tailwind CSS и ведёт клиентское состояние. CX Codex +1 ★ 3 232звёзд репо

Из того же набора68

Весь набор →
swiftui-code-review Скилл swiftui-code-review для Claude Code проверяет SwiftUI-код: композицию представлений, состояние, производительность и доступность. Разбирает файлы с @State, @Binding, @Observable и UI-кодом. CX Codex +1 277установок tutorial-docs Скилл tutorial-docs для Claude Code задаёт структуру обучающих руководств по методологии Diataxis. Агент подключает его при написании вводных уроков и пошаговых руководств для новичков. CX Codex +1 273установок bubbletea-code-review Скилл bubbletea-code-review для Claude Code проверяет Go-код BubbleTea-проектов: архитектуру Elm, цикл Update и стили Lipgloss. CX Codex +1 270установок zustand-state Скилл zustand-state для Claude Code помогает создавать хранилища Zustand, выбирать данные селекторами, сохранять их в localStorage и подключать devtools. CX Codex +1 261установок adr-writing Скилл adr-writing для Claude Code, который оформляет архитектурные решения в документы ADR по шаблону MADR и проверяет их полноту по чек-листу E.C.A.D.R. Работает также в Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode. CX Codex +1 254установок swift-code-review Скилл swift-code-review для Claude Code проверяет Swift-код на ошибки конкурентности, обработки ошибок и управления памятью. Подключается при ревью файлов .swift, в том числе с async/await, actors и Sendable. CX Codex +1 253установок review-verification-protocol Скилл review-verification-protocol обязывает проверить каждую находку перед тем, как внести её в отчёт — читать исходный код, искать контекст, отличать баги от стиля. Снижает ложные срабатывания в ревью. CX Codex +1 252установок pytest-code-review Скилл pytest-code-review проверяет тесты pytest на корректность асинхронных вызовов, скоуп фикстур, параметризацию и пути для моков. Помогает находить утечки и ошибки патчинга до запуска CI. CX Codex +1 239установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой