npm package: @majdibo/flow-visualizer
Description: React components for visualizing flow graphs and timelines
Author: majdibo
Latest version: 1.0.0

# Flow Visualizer

<p align="center">
  <img src="./public/logo.svg" alt="Flow Visualizer Logo" width="120" height="120">
</p>

<p align="center">
  <strong>Beautiful React components for visualizing execution flows and timelines</strong>
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/@majdibo/flow-visualizer">
    <img src="https://img.shields.io/npm/v/@majdibo/flow-visualizer.svg" alt="npm version">
  </a>
  <a href="https://github.com/majdibo/flow-visualizer/blob/main/LICENSE">
    <img src="https://img.shields.io/npm/l/@majdibo/flow-visualizer.svg" alt="license">
  </a>
  <a href="https://www.npmjs.com/package/@majdibo/flow-visualizer">
    <img src="https://img.shields.io/npm/dm/@majdibo/flow-visualizer.svg" alt="downloads">
  </a>
</p>

<p align="center">
  <a href="https://majdibo.github.io/flow-visualizer">🎮 Try the Interactive Playground</a>
</p>

## Why Flow Visualizer?

Visualizing complex execution flows shouldn't require building a custom graph renderer from scratch. Flow Visualizer gives you production-ready React components to display:

- **Workflow executions** - Show users how their automations run
- **State machines** - Visualize state transitions and flows
- **Process traces** - Debug and monitor system processes
- **AI agent reasoning** - Display agent decision trees and tool usage
- **Build pipelines** - Show CI/CD execution flows
- **Any trace-based execution** - Generic enough for any sequential process

Built on top of [`@majdibo/flow-engine`](https://github.com/majdibo/flow-engine), it handles the hard parts (graph layout, state management, timeline tracking) so you can focus on your application.

## ✨ Features

- 🎨 **Beautiful by default** - Modern UI with light/dark mode support
- ⚛️ **React native** - Drop-in components, fully typed with TypeScript
- 🖱️ **Interactive** - Zoom, pan, and explore with smooth animations
- 📊 **Auto-layout** - Powered by Dagre for perfect graph positioning
- ⏱️ **Timeline support** - Replay executions step-by-step
- 🎯 **Customizable** - Override styles and customize node displays
- 📦 **Zero config** - Works out of the box with sensible defaults

## 🚀 Installation

```bash
npm install @majdibo/flow-visualizer
```

Or with yarn:

```bash
yarn add @majdibo/flow-visualizer
```

> **Note:** `@majdibo/flow-engine` is a required peer dependency for graph construction and state management.

## 📖 Quick Start

### Basic Example

```tsx
import { FlowVisualizer, computeLayout } from '@majdibo/flow-visualizer';
import { buildGraphFromTraces, computeVisualState } from '@majdibo/flow-engine';
import { useState } from 'react';

function MyFlowApp() {
  // Your execution traces
  const traces = [
    { step: 'start', nodeType: 'action', data: { msg: 'Starting' }, timestamp: Date.now() },
    { step: 'process', nodeType: 'action', data: { msg: 'Processing' }, timestamp: Date.now() },
    { step: 'end', nodeType: 'action', data: { msg: 'Done' }, timestamp: Date.now() }
  ];

  const [currentIndex, setCurrentIndex] = useState(0);

  // Build graph from traces
  const graph = buildGraphFromTraces(traces);
  const timeline = traces.map(t => t.step);

  // Compute layout
  const { nodes, edges } = computeLayout(graph);

  // Compute visual state
  const visualState = computeVisualState(graph, timeline, currentIndex);

  return (
    <div>
      <FlowVisualizer
        nodes={nodes}
        edges={edges}
        state={visualState}
        onNodeClick={(nodeId) => console.log('Clicked:', nodeId)}
      />

      {/* Timeline controls */}
      <button onClick={() => setCurrentIndex(Math.max(0, currentIndex - 1))}>
        Previous
      </button>
      <button onClick={() => setCurrentIndex(Math.min(timeline.length - 1, currentIndex + 1))}>
        Next
      </button>
    </div>
  );
}
```

### With Custom Node Details

Show detailed information when users click on nodes:

```tsx
import { FlowVisualizer, NodeDetailModal } from '@majdibo/flow-visualizer';
import { useState } from 'react';

function MyApp() {
  const [selectedNode, setSelectedNode] = useState<string | null>(null);

  // Customize how trace details are displayed
  const renderTraceDetails = (trace: any, traceIndex: number) => (
    <div className="custom-trace-card">
      <h4>Step {traceIndex + 1}</h4>
      <p>{trace.step}</p>
      <pre>{JSON.stringify(trace.data, null, 2)}</pre>
    </div>
  );

  return (
    <>
      <FlowVisualizer
        nodes={nodes}
        edges={edges}
        state={visualState}
        onNodeClick={setSelectedNode}
      />

      {selectedNode && (
        <NodeDetailModal
          nodeId={selectedNode}
          nodes={nodes}
          graph={graph}
          traces={traces}
          visualState={visualState}
          icons={{}}
          onClose={() => setSelectedNode(null)}
          renderTraceDetails={renderTraceDetails}
        />
      )}
    </>
  );
}
```

### Custom Layout Options

Control how your graph is laid out:

```tsx
const { nodes, edges } = computeLayout(graph, {
  direction: 'LR',        // Left-to-right layout
  nodeSep: 100,           // Horizontal spacing
  rankSep: 150,           // Vertical spacing
  edgeStyle: 'orthogonal' // Right-angle edges
});
```

## 📚 API Reference

### `<FlowVisualizer />`

The main component for rendering interactive flow diagrams.

| Prop | Type | Description |
|------|------|-------------|
| `nodes` | `VisualNode[]` | Array of nodes with positions (from `computeLayout`) |
| `edges` | `VisualEdge[]` | Array of edges with paths (from `computeLayout`) |
| `state` | `VisualState` | Current state (from `computeVisualState`) |
| `onNodeClick?` | `(nodeId: string) => void` | Called when a node is clicked |

**Interactions:**
- **Mouse wheel** - Zoom in/out
- **Click + drag** - Pan around the graph
- **Double-click** - Reset zoom and position
- **Click node** - Trigger `onNodeClick` callback

### `<NodeDetailModal />`

Display detailed information about a selected node in a modal.

| Prop | Type | Description |
|------|------|-------------|
| `nodeId` | `string` | ID of the node to display |
| `nodes` | `VisualNode[]` | Array of visual nodes |
| `graph` | `FlowGraph` | The flow graph |
| `traces` | `Trace[]` | Array of execution traces |
| `visualState` | `VisualState` | Current visual state |
| `icons` | `Record<string, ReactNode>` | Icon mapping for node types |
| `onClose` | `() => void` | Called when modal is closed |
| `renderTraceDetails?` | `(trace, index) => ReactNode` | Custom trace renderer |

### `computeLayout(graph, options?)`

Compute positions for nodes and paths for edges using automatic layout.

**Parameters:**
- `graph` - FlowGraph from `buildGraphFromTraces`
- `options?` - Layout configuration:
  - `direction` - Layout direction: `'TB'` (top-bottom), `'LR'` (left-right), `'BT'` (bottom-top), `'RL'` (right-left). Default: `'TB'`
  - `nodeSep` - Horizontal spacing between nodes. Default: `80`
  - `rankSep` - Vertical spacing between ranks. Default: `120`
  - `edgeStyle` - Edge routing style: `'polyline'` or `'orthogonal'`. Default: `'polyline'`

**Returns:** `{ nodes: VisualNode[], edges: VisualEdge[] }`

## 🎨 Styling & Theming

Flow Visualizer includes beautiful default styles and automatically adapts to light/dark mode based on user preferences (`prefers-color-scheme`).

### Customizing Colors

Override CSS variables to match your brand:

```css
:root {
  /* Light mode */
  --flow-node-current-stroke: #171717;
  --flow-node-traversed-fill: #f5f5f5;
  --flow-edge-current: #171717;
  --flow-text-primary: #171717;
}

@media (prefers-color-scheme: dark) {
  :root {
    /* Dark mode */
    --flow-node-current-stroke: #f5f5f5;
    --flow-node-traversed-fill: #262626;
    --flow-edge-current: #f5f5f5;
    --flow-text-primary: #f5f5f5;
  }
}
```

### Available CSS Variables

| Variable | Description |
|----------|-------------|
| `--flow-bg` | Background color |
| `--flow-node-current-fill` | Current node background |
| `--flow-node-current-stroke` | Current node border |
| `--flow-node-traversed-fill` | Completed node background |
| `--flow-node-untraversed-fill` | Pending node background |
| `--flow-edge-current` | Current edge color |
| `--flow-edge-traversed` | Completed edge color |
| `--flow-text-primary` | Primary text color |
| `--flow-text-secondary` | Secondary text color |
| `--flow-gradient-start` | Gradient start color |
| `--flow-gradient-end` | Gradient end color |

## 🔧 TypeScript Support

Flow Visualizer is written in TypeScript and includes full type definitions:

```typescript
import type {
  VisualNode,
  VisualEdge,
  LayoutOptions,
  LayoutResult,
  FlowVisualizerProps,
  NodeDetailModalProps
} from '@majdibo/flow-visualizer';
```

All components and functions are fully typed for the best developer experience.

## 🤝 Contributing

We welcome contributions! Here's how you can help:

1. **Fork the repository**
2. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
3. **Commit your changes** (`git commit -m 'Add amazing feature'`)
4. **Push to the branch** (`git push origin feature/amazing-feature`)
5. **Open a Pull Request**

### Development Setup

```bash
# Clone the repo
git clone https://github.com/majdibo/flow-visualizer.git
cd flow-visualizer

# Install dependencies
npm install

# Start development server
npm run dev

# Build the library
npm run build
```

### Reporting Issues

Found a bug or have a feature request? [Open an issue](https://github.com/majdibo/flow-visualizer/issues) on GitHub.

## 📦 Related Projects

- [`@majdibo/flow-engine`](https://github.com/majdibo/flow-engine) - Core graph engine (required dependency)

## 🙏 Acknowledgments

Built with:
- [React](https://react.dev/) - UI library
- [Dagre](https://github.com/dagrejs/dagre) - Graph layout
- [TypeScript](https://www.typescriptlang.org/) - Type safety
- [Tailwind CSS](https://tailwindcss.com/) - Styling

## 📄 License

MIT License - see [LICENSE](LICENSE) for details.

---

<p align="center">
  Made with ❤️ by <a href="https://github.com/majdibo">majdibo</a>
</p>

<p align="center">
  <a href="https://github.com/majdibo/flow-visualizer">GitHub</a> •
  <a href="https://www.npmjs.com/package/@majdibo/flow-visualizer">npm</a> •
  <a href="https://github.com/majdibo/flow-visualizer/issues">Issues</a>
</p>