Flow

A canvas of nodes joined by edges, that you pan, zoom and rearrange.

'use client';

import { useCallback, useState } from 'react';
import { Button } from '@/components/panelui/button';
import { Flow } from '@/components/panelui/flow';

/** An article on its way to being published. */
const STAGES = [
  { id: 'draft', name: 'Draft', detail: '1,840 words' },
  { id: 'edit', name: 'Edit', detail: 'Two rounds' },
  { id: 'check', name: 'Fact check', detail: '14 claims' },
  { id: 'legal', name: 'Legal read', detail: 'One quote to clear' },
  { id: 'schedule', name: 'Schedule', detail: 'Thursday, 09:00' },
  { id: 'publish', name: 'Publish', detail: 'Site and newsletter' },
];

const TAG = { done: 'success', live: 'info', waiting: 'muted' } as const;

/**
 * Whether the canvas has room to lay the graph out across. It is the canvas
 * that is measured and not the window: in a page with a sidebar the two are
 * far apart.
 */
function useRoom(least: number) {
  const [wide, setWide] = useState(true);
  const watch = useCallback(
    (node: HTMLElement | null) => {
      if (!node) return;
      const observer = new ResizeObserver(([entry]) => setWide(entry.contentRect.width >= least));
      observer.observe(node);
      return () => observer.disconnect();
    },
    [least]
  );
  return [wide, watch] as const;
}

export default function FlowPipeline() {
  // The stage being worked on. Everything before it is done.
  const [at, setAt] = useState(1);
  const [wide, watch] = useRoom(720);
  const columns = wide ? 3 : 2;

  // The stages run along a row and back along the next, like a snake.
  const place = (index: number) => {
    const row = Math.floor(index / columns);
    const along = index % columns;
    const column = row % 2 ? columns - 1 - along : along;
    return { x: column * (wide ? 340 : 216), y: row * (wide ? 230 : 160) };
  };

  return (
    <div ref={watch} className="relative h-[34rem] w-full">
      <Flow
        // Laid out afresh, and fitted afresh, when the room for it changes.
        key={columns}
        fitViewOnMount
        fitViewPadding={wide ? 48 : 20}
        label="Article pipeline"
        className="h-full rounded-none border-0"
      >
        <Flow.Background variant="lines" gap={28} />
        {STAGES.map((stage, index) => {
          const state = index < at ? 'done' : index === at ? 'live' : 'waiting';
          return (
            <Flow.Node
              key={stage.id}
              id={stage.id}
              position={place(index)}
              className={wide ? 'w-52' : 'w-44'}
            >
              <Flow.NodeHeader>
                <Flow.NodeDescription>Stage {index + 1}</Flow.NodeDescription>
                <Flow.NodeBadge color={TAG[state]}>
                  {state === 'done' ? 'Done' : state === 'live' ? 'Now' : 'Waiting'}
                </Flow.NodeBadge>
              </Flow.NodeHeader>
              <Flow.NodeContent>
                <Flow.NodeTitle>{stage.name}</Flow.NodeTitle>
                <Flow.NodeDescription className="truncate">{stage.detail}</Flow.NodeDescription>
              </Flow.NodeContent>
            </Flow.Node>
          );
        })}
        {STAGES.slice(1).map((stage, index) => (
          <Flow.Edge
            key={stage.id}
            from={STAGES[index].id}
            to={stage.id}
            variant="smoothstep"
            gap={10}
            arrow
            // Only the edge into the stage being worked on is marching.
            animated={index + 1 === at}
            color={index + 1 === at ? 'info' : undefined}
          />
        ))}
        {/* Fewer buttons where the graph needs the room. */}
        <Flow.Controls fit={wide} lock={wide} />
      </Flow>

      <div className="absolute bottom-3 left-3 flex gap-2">
        <Button variant="outline" size="sm" disabled={at === 0} onClick={() => setAt(at - 1)}>
          Back a stage
        </Button>
        <Button size="sm" disabled={at === STAGES.length - 1} onClick={() => setAt(at + 1)}>
          Advance
        </Button>
      </div>
    </div>
  );
}

Use it to show how things are connected and let somebody move them about: the stages of a pipeline, an automation, the parts of a system. Nodes are boxes with your own contents, edges join them, and the canvas is panned and zoomed.

It has the same parts and props as the app library's Flow, so a graph written for one reads the same in the other.

It lays nothing out for you. Every node is given a position, so for a graph whose shape comes from data you need to work the positions out first. For steps in a fixed order with nothing to rearrange, a list of steps is the simpler thing.

Installation

npx shadcn@latest add https://panelui.dev/r/web/flow.json

The source is copied into components/panelui/, where you can edit it.

Usage

import { Flow } from "@/components/panelui/flow"
<Flow fitViewOnMount>
  <Flow.Background />
  <Flow.Node id="draft" position={{ x: 40, y: 20 }}>
    <Flow.NodeContent>
      <Flow.NodeTitle>Draft</Flow.NodeTitle>
    </Flow.NodeContent>
  </Flow.Node>
  <Flow.Node id="edit" position={{ x: 40, y: 150 }}>
    <Flow.NodeContent>
      <Flow.NodeTitle>Edit</Flow.NodeTitle>
      <Flow.NodeDescription>Two rounds</Flow.NodeDescription>
    </Flow.NodeContent>
  </Flow.Node>
  <Flow.Edge from="draft" to="edit" arrow />
  <Flow.Controls />
</Flow>

Composition

<Flow>
  <Flow.Background />
  <Flow.Node id="…" position={…}>
    <Flow.NodeHeader>
      <Flow.NodeDescription />
      <Flow.NodeBadge />
    </Flow.NodeHeader>
    <Flow.NodeContent>
      <Flow.NodeTitle />
      <Flow.NodeDescription />
    </Flow.NodeContent>
    <Flow.Handle />
  </Flow.Node>
  <Flow.Group id="…" position={…}>
    <Flow.GroupItem>
      <Flow.NodeContent />
    </Flow.GroupItem>
  </Flow.Group>
  <Flow.Edge from="…" to="…" />
  <Flow.Controls />
  <Flow.MiniMap />
</Flow>
  • Flow.Background — The pattern behind the graph: dots, lines or crosses. It moves and scales with the graph.
  • Flow.Node — A box on the graph. id is what edges call it and position is where it starts. Fill it with the node parts below, or with anything of your own.
  • Flow.NodeHeader — A strip across the top of a node, ruled off from the rest, with something at each end: a step number and a Flow.NodeBadge.
  • Flow.NodeContent — The body of a node, carrying the node's padding. Inside a Flow.GroupItem it has none, because the item has its own.
  • Flow.NodeTitle — What the node is.
  • Flow.NodeDescription — A quieter line about the node. It is smaller inside a Flow.GroupItem.
  • Flow.NodeBadge — A word in a pill for the node's state, tinted with the theme colour named by color. muted is grey, and the default.
  • Flow.Handle — A dot on a node's edge that a connection can be drawn from or dropped on. Give it an id to join an edge to it by name.
  • Flow.Edge — A line from one node to another: a curve, a routed line or a straight one, optionally dashed, marching and with an arrowhead.
  • Flow.Group — A dashed box with a label, round things that belong together. It is dragged as one and an edge can be joined to it.
  • Flow.GroupItem — One thing inside a group that is not a node of its own: an icon beside a Flow.NodeContent. It moves with the group, and edges cannot join it.
  • Flow.Controls — Buttons to zoom, fit everything in view and lock the canvas.
  • Flow.MiniMap — The whole graph, small, with the part in view marked on it.

Examples

Edges that pick their own side

An edge with no fromSide, toSide or handle leaves from whichever face of its node is turned towards the other one. Drag one node past another and the edges turn to follow. Name the sides when the direction should not change.

'use client';

import { DatabaseIcon, GlobeIcon, MailIcon, ServerIcon, ZapIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import { Flow } from '@/components/panelui/flow';

function Service({ icon, name, detail, up = true }: { icon: ReactNode; name: string; detail: string; up?: boolean }) {
  return (
    <>
      <Flow.NodeHeader>
        <span className="flex items-center gap-2 text-muted-foreground [&_svg]:size-4">
          {icon}
          <Flow.NodeDescription>Service</Flow.NodeDescription>
        </span>
        <Flow.NodeBadge color={up ? 'success' : 'warning'}>{up ? 'Healthy' : 'Degraded'}</Flow.NodeBadge>
      </Flow.NodeHeader>
      <Flow.NodeContent>
        <Flow.NodeTitle>{name}</Flow.NodeTitle>
        <Flow.NodeDescription>{detail}</Flow.NodeDescription>
      </Flow.NodeContent>
    </>
  );
}

export default function FlowMap() {
  return (
    <div className="h-[28rem] w-full">
      <Flow fitViewOnMount fitViewPadding={40} label="Newsletter service" className="h-full rounded-none border-0">
        <Flow.Background variant="dots" />
        <Flow.Node id="site" position={{ x: 0, y: 120 }} className="w-52">
          <Service icon={<GlobeIcon />} name="site" detail="Sign-up pages" />
        </Flow.Node>
        <Flow.Node id="api" position={{ x: 300, y: 120 }} className="w-52">
          <Service icon={<ServerIcon />} name="api" detail="Three instances" />
        </Flow.Node>
        <Flow.Node id="db" position={{ x: 600, y: 0 }} className="w-52">
          <Service icon={<DatabaseIcon />} name="subscribers-db" detail="48,210 rows" />
        </Flow.Node>
        <Flow.Node id="cache" position={{ x: 600, y: 250 }} className="w-52">
          <Service icon={<ZapIcon />} name="cache" detail="92% hit rate" />
        </Flow.Node>
        <Flow.Node id="mailer" position={{ x: 300, y: 340 }} className="w-52">
          <Service icon={<MailIcon />} name="mailer" detail="Sending issue 112" up={false} />
        </Flow.Node>

        {/* No sides are named, so each edge leaves from whichever face faces the
            other node now. Drag one across another and watch them turn. */}
        <Flow.Edge from="site" to="api" variant="smoothstep" arrow />
        <Flow.Edge from="api" to="db" variant="smoothstep" arrow />
        <Flow.Edge from="api" to="cache" variant="smoothstep" dashed arrow />
        <Flow.Edge from="api" to="mailer" variant="smoothstep" animated arrow color="warning" />
        <Flow.Controls position="top-left" lock={false} />
      </Flow>
    </div>
  );
}

A mind map

bezier edges from one centre, each in a theme colour of its own. With no sides named, a branch can be dragged anywhere round the centre.

'use client';

import { Flow, type FlowColor } from '@/components/panelui/flow';

/** A trip being planned, and the five things it needs. */
const BRANCHES: { id: string; title: string; detail: string; x: number; y: number; color: FlowColor }[] = [
  { id: 'travel', title: 'Getting there', detail: 'Train, 2 h 50 min', x: -300, y: -150, color: 'primary' },
  { id: 'stay', title: 'Where to stay', detail: 'Three shortlisted', x: 280, y: -170, color: 'info' },
  { id: 'food', title: 'Food', detail: 'Market on Saturday', x: 340, y: 40, color: 'success' },
  { id: 'walks', title: 'Walks', detail: 'Coast path, 11 km', x: -320, y: 120, color: 'warning' },
  { id: 'budget', title: 'Budget', detail: '£640 for two', x: -20, y: 200, color: 'destructive' },
];

export default function FlowMindMap() {
  return (
    <div className="h-[28rem] w-full">
      <Flow fitViewOnMount fitViewPadding={36} label="Trip plan" className="h-full rounded-none border-0">
        <Flow.Background variant="cross" gap={32} />
        <Flow.Node id="trip" position={{ x: -100, y: -36 }} className="w-56 rounded-3xl">
          <Flow.NodeContent className="px-6 py-4 text-center">
            <Flow.NodeTitle className="text-base">A weekend in Porto</Flow.NodeTitle>
            <Flow.NodeDescription>14–16 November</Flow.NodeDescription>
          </Flow.NodeContent>
        </Flow.Node>

        {BRANCHES.map((branch) => (
          <Flow.Node key={branch.id} id={branch.id} position={{ x: branch.x, y: branch.y }} className="w-44">
            <Flow.NodeContent>
              <Flow.NodeTitle>{branch.title}</Flow.NodeTitle>
              <Flow.NodeDescription>{branch.detail}</Flow.NodeDescription>
            </Flow.NodeContent>
          </Flow.Node>
        ))}

        {/* Curves with no fixed sides: drag a branch round the centre and its
            edge leaves from the face that now points at it. */}
        {BRANCHES.map((branch) => (
          <Flow.Edge key={branch.id} from="trip" to={branch.id} variant="bezier" color={branch.color} width={2.5} />
        ))}
        <Flow.Controls position="top-left" zoom={false} lock={false} />
      </Flow>
    </div>
  );
}

Wiring it up

A Flow.Handle is somewhere to start a connection. Drag from one to another node and onConnect is told which two; the edges are yours to keep. isValidConnection refuses the ones you do not want, here a second wire between the same two steps.

'use client';

import { useCallback, useState } from 'react';
import { Button } from '@/components/panelui/button';
import { Flow, type FlowConnection } from '@/components/panelui/flow';

/** Each step, and where it sits: across a wide screen, down a narrow one. */
const NODES = [
  {
    id: 'form',
    name: 'Sign-up form',
    across: { x: 0, y: 90 },
    down: { x: 0, y: 0 },
  },
  {
    id: 'verify',
    name: 'Verify email',
    across: { x: 320, y: 0 },
    down: { x: 150, y: 80 },
  },
  {
    id: 'welcome',
    name: 'Welcome message',
    across: { x: 320, y: 180 },
    down: { x: 0, y: 160 },
  },
  {
    id: 'crm',
    name: 'Add to CRM',
    across: { x: 680, y: 90 },
    down: { x: 150, y: 240 },
  },
];

/**
 * Whether the canvas has room to lay the graph out across. It is the canvas
 * that is measured and not the window: in a page with a sidebar the two are
 * far apart.
 */
function useRoom(least: number) {
  const [wide, setWide] = useState(true);
  const watch = useCallback(
    (node: HTMLElement | null) => {
      if (!node) return;
      const observer = new ResizeObserver(([entry]) => setWide(entry.contentRect.width >= least));
      observer.observe(node);
      return () => observer.disconnect();
    },
    [least]
  );
  return [wide, watch] as const;
}

const START: FlowConnection[] = [{ source: 'form', target: 'verify' }];

export default function FlowWiring() {
  const [wires, setWires] = useState(START);
  const [wide, watch] = useRoom(720);
  // A wire leaves one face of a step and arrives at the opposite one.
  const out = wide ? 'right' : 'bottom';
  const into = wide ? 'left' : 'top';

  const joined = (a: FlowConnection, b: FlowConnection) =>
    a.source === b.source && a.target === b.target;

  return (
    <div ref={watch} className="relative h-[26rem] w-full">
      <Flow
        // Fitted afresh when the layout changes.
        key={wide ? 'across' : 'down'}
        fitViewOnMount
        fitViewPadding={wide ? 48 : 24}
        label="Sign-up automation"
        className="h-full rounded-none border-0"
        // Two nodes are joined once. A second wire between them is refused.
        isValidConnection={(connection) => !wires.some((wire) => joined(wire, connection))}
        onConnect={(connection) => setWires((current) => [...current, connection])}
      >
        <Flow.Background />
        {NODES.map((node) => (
          <Flow.Node
            key={node.id}
            id={node.id}
            position={wide ? node.across : node.down}
          >
            <Flow.NodeContent>
              <Flow.NodeTitle className="whitespace-nowrap">{node.name}</Flow.NodeTitle>
            </Flow.NodeContent>
            <Flow.Handle position={into} />
            <Flow.Handle position={out} />
          </Flow.Node>
        ))}
        {wires.map((wire) => (
          <Flow.Edge
            key={`${wire.source}-${wire.target}`}
            from={wire.source}
            to={wire.target}
            arrow
            fromSide={out}
            toSide={into}
          />
        ))}
        <Flow.Controls lock={false} />
      </Flow>

      <div className="absolute bottom-3 left-3 flex max-w-[calc(100%-4.5rem)] items-center gap-3 rounded-xl border bg-card py-1.5 pe-1.5 ps-3 shadow-sm">
        <p className="text-sm text-muted-foreground">
          {wide ? 'Drag from a dot on one step to another step to join them. ' : null}
          {wires.length} joined.
        </p>
        <Button variant="outline" size="sm" onClick={() => setWires(START)}>
          Reset
        </Button>
      </div>
    </div>
  );
}

Named ports

Flow.Handle takes an id, a face and an offset along it, so one face can hold two. Join an edge to it as "node.handle", and that end stays on the port however the node is dragged. Use ports where the side means something: here accepted leaves from one and rejected from the other.

'use client';

import { Flow } from '@/components/panelui/flow';

export default function FlowPorts() {
  return (
    <div className="h-[28rem] w-full">
      <Flow fitViewOnMount fitViewPadding={40} label="Photo uploads" className="h-full rounded-none border-0">
        <Flow.Background variant="cross" gap={26} />

        <Flow.Node id="upload" position={{ x: 0, y: 90 }} className="w-48">
          <Flow.NodeContent>
            <Flow.NodeTitle>upload</Flow.NodeTitle>
            <Flow.NodeDescription>Checks type and size</Flow.NodeDescription>
          </Flow.NodeContent>
          {/* Two ports on one face, kept apart by their offsets. */}
          <Flow.Handle id="ok" position="right" offset={0.3} />
          <Flow.Handle id="rejected" position="right" offset={0.75} />
        </Flow.Node>

        <Flow.Node id="resize" position={{ x: 290, y: 0 }} className="w-44">
          <Flow.NodeHeader>
            <Flow.NodeDescription>Accepted</Flow.NodeDescription>
            <Flow.NodeBadge color="success">ok</Flow.NodeBadge>
          </Flow.NodeHeader>
          <Flow.NodeContent>
            <Flow.NodeTitle>resize</Flow.NodeTitle>
          </Flow.NodeContent>
          <Flow.Handle id="in" position="left" />
          <Flow.Handle id="out" position="right" />
        </Flow.Node>

        <Flow.Node id="review" position={{ x: 290, y: 200 }} className="w-44">
          <Flow.NodeHeader>
            <Flow.NodeDescription>Rejected</Flow.NodeDescription>
            <Flow.NodeBadge color="destructive">held</Flow.NodeBadge>
          </Flow.NodeHeader>
          <Flow.NodeContent>
            <Flow.NodeTitle>review</Flow.NodeTitle>
          </Flow.NodeContent>
          <Flow.Handle id="in" position="left" />
          <Flow.Handle id="out" position="right" />
        </Flow.Node>

        {/* A port on every face. The top and bottom ones have nothing wired to
            them yet, and still read as somewhere to wire. */}
        <Flow.Node id="gallery" position={{ x: 570, y: 70 }} className="w-52">
          <Flow.NodeHeader>
            <Flow.NodeDescription>Four ports</Flow.NodeDescription>
          </Flow.NodeHeader>
          <Flow.NodeContent>
            <Flow.NodeTitle>gallery</Flow.NodeTitle>
            <Flow.NodeDescription>new · approved on the left</Flow.NodeDescription>
          </Flow.NodeContent>
          <Flow.Handle id="new" position="left" offset={0.35} />
          <Flow.Handle id="approved" position="left" offset={0.75} />
          <Flow.Handle id="feed" position="top" />
          <Flow.Handle id="archive" position="bottom" />
        </Flow.Node>

        {/* `node.handle` pins each end to a port, so the faces stay put however
            the nodes are dragged. */}
        <Flow.Edge from="upload.ok" to="resize.in" variant="smoothstep" arrow />
        <Flow.Edge from="upload.rejected" to="review.in" variant="smoothstep" dashed arrow color="destructive" />
        <Flow.Edge from="resize.out" to="gallery.new" variant="smoothstep" arrow />
        <Flow.Edge from="review.out" to="gallery.approved" variant="smoothstep" dashed arrow />
        <Flow.Controls position="top-left" lock={false} />
      </Flow>
    </div>
  );
}

Building a graph

The canvas holds no list of nodes or edges. Each is something you render, so adding one is adding to an array in your own state.

'use client';

import { useState } from 'react';
import { Button } from '@/components/panelui/button';
import { Flow } from '@/components/panelui/flow';

interface Step {
  id: string;
  x: number;
  y: number;
}

const FIRST: Step[] = [{ id: 'step-1', x: 0, y: 0 }];

export default function FlowBuilder() {
  // The canvas keeps no list of its own. The steps and the links are state
  // here, and adding either is adding to an array.
  const [steps, setSteps] = useState(FIRST);
  const [links, setLinks] = useState<{ from: string; to: string }[]>([]);

  const add = (linked: boolean) => {
    const index = steps.length;
    // Short columns rather than one long march, so the first steps stay in view.
    const step = { id: `step-${index + 1}`, x: Math.floor(index / 3) * 240, y: (index % 3) * 130 };
    const previous = steps[steps.length - 1];
    setSteps([...steps, step]);
    if (linked && previous) setLinks([...links, { from: previous.id, to: step.id }]);
  };

  return (
    <div className="relative h-[28rem] w-full">
      <Flow defaultViewport={{ x: 72, y: 24, zoom: 1 }} label="Steps" className="h-full rounded-none border-0">
        <Flow.Background variant="dots" />
        {steps.map((step, index) => (
          <Flow.Node key={step.id} id={step.id} position={{ x: step.x, y: step.y }} className="w-44">
            <Flow.NodeContent>
              <Flow.NodeTitle>Step {index + 1}</Flow.NodeTitle>
              <Flow.NodeDescription>Drag it anywhere</Flow.NodeDescription>
            </Flow.NodeContent>
          </Flow.Node>
        ))}
        {links.map((link) => (
          <Flow.Edge key={link.to} from={link.from} to={link.to} variant="smoothstep" arrow />
        ))}
        <Flow.Controls position="top-left" lock={false} />
      </Flow>

      <div className="absolute bottom-3 left-3 flex flex-wrap items-center gap-2">
        <Button variant="outline" size="sm" onClick={() => add(false)}>
          Add a step
        </Button>
        <Button size="sm" onClick={() => add(true)}>
          Add and link
        </Button>
        <Button variant="ghost" size="sm" onClick={() => (setSteps(FIRST), setLinks([]))}>
          Clear
        </Button>
        <span className="text-xs text-muted-foreground tabular-nums">
          {steps.length} {steps.length === 1 ? 'step' : 'steps'}, {links.length} {links.length === 1 ? 'link' : 'links'}
        </span>
      </div>
    </div>
  );
}

Moving nodes from outside

position is where a node starts. Keep the positions in state, update them from onNodeDragEnd, and pass new ones to move the nodes yourself.

'use client';

import { useState } from 'react';
import { Button } from '@/components/panelui/button';
import { Flow, type FlowNodePosition } from '@/components/panelui/flow';

const IDS = ['brief', 'sketch', 'review', 'final'] as const;
type Id = (typeof IDS)[number];

const ROW: Record<Id, FlowNodePosition> = {
  brief: { x: 0, y: 80 },
  sketch: { x: 220, y: 80 },
  review: { x: 440, y: 80 },
  final: { x: 660, y: 80 },
};

const STAIRS: Record<Id, FlowNodePosition> = {
  brief: { x: 0, y: 0 },
  sketch: { x: 200, y: 70 },
  review: { x: 400, y: 140 },
  final: { x: 600, y: 210 },
};

const TITLES: Record<Id, string> = { brief: 'Brief', sketch: 'Sketches', review: 'Review', final: 'Final art' };

export default function FlowPositions() {
  // The positions are state here. A drag reports where a node was dropped,
  // and the buttons move every node by passing new positions back.
  const [positions, setPositions] = useState(ROW);

  return (
    <div className="relative h-[28rem] w-full">
      <Flow
        fitViewOnMount
        fitViewPadding={56}
        label="Poster project"
        className="h-full rounded-none border-0"
        onNodeDragEnd={(id, position) => setPositions((current) => ({ ...current, [id]: position }))}
      >
        <Flow.Background variant="lines" gap={28} />
        {IDS.map((id) => (
          <Flow.Node key={id} id={id} position={positions[id]} className="w-40">
            <Flow.NodeContent>
              <Flow.NodeTitle>{TITLES[id]}</Flow.NodeTitle>
              <Flow.NodeDescription className="font-mono text-xs tabular-nums">
                {Math.round(positions[id].x)}, {Math.round(positions[id].y)}
              </Flow.NodeDescription>
            </Flow.NodeContent>
          </Flow.Node>
        ))}
        {IDS.slice(1).map((id, index) => (
          <Flow.Edge key={id} from={IDS[index]} to={id} variant="smoothstep" arrow />
        ))}
      </Flow>

      <div className="absolute bottom-3 left-3 flex gap-2">
        <Button variant="outline" size="sm" onClick={() => setPositions(ROW)}>
          In a row
        </Button>
        <Button variant="outline" size="sm" onClick={() => setPositions(STAIRS)}>
          As stairs
        </Button>
      </div>
    </div>
  );
}

Nodes inside a group

A Flow.Node inside a Flow.Group is placed relative to the group and moves with it. Give the group a size, because the nodes do not lay it out. confine stops a node's drag at the group's edge. pinned gives the drag to the group, so the node moves only when the group does.

'use client';

import { LampDeskIcon, RouterIcon, SpeakerIcon, ThermometerIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import { Flow } from '@/components/panelui/flow';

function Device({ icon, name, detail }: { icon: ReactNode; name: string; detail: string }) {
  return (
    <Flow.NodeContent className="flex items-center gap-2.5 px-3 py-2.5 [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground">
      {icon}
      <span className="min-w-0">
        <Flow.NodeTitle>{name}</Flow.NodeTitle>
        <Flow.NodeDescription className="text-xs">{detail}</Flow.NodeDescription>
      </span>
    </Flow.NodeContent>
  );
}

export default function FlowConfine() {
  return (
    <div className="h-[28rem] w-full">
      <Flow fitViewOnMount fitViewPadding={36} label="Smart home" className="h-full rounded-none border-0">
        <Flow.Background variant="dots" />

        <Flow.Node id="hub" position={{ x: 0, y: 120 }} className="w-40">
          <Device icon={<RouterIcon />} name="Hub" detail="Hallway" />
        </Flow.Node>

        {/* Nodes inside a group are placed relative to it, and the group needs a
            size because they do not lay it out. */}
        <Flow.Group id="living" label="Living room" position={{ x: 250, y: 0 }} size={{ width: 300, height: 180 }}>
          {/* Can be moved round the room, but not out of it. */}
          <Flow.Node id="lamp" confine position={{ x: 16, y: 44 }} className="w-36">
            <Device icon={<LampDeskIcon />} name="Lamp" detail="Drag me" />
          </Flow.Node>
          {/* Fixed to the wall: dragging it moves the room. */}
          <Flow.Node id="thermostat" pinned position={{ x: 140, y: 112 }} className="w-36">
            <Device icon={<ThermometerIcon />} name="Thermostat" detail="Pinned" />
          </Flow.Node>
        </Flow.Group>

        <Flow.Group id="kitchen" label="Kitchen" position={{ x: 250, y: 230 }} size={{ width: 300, height: 130 }}>
          <Flow.Node id="speaker" confine position={{ x: 120, y: 50 }} className="w-36">
            <Device icon={<SpeakerIcon />} name="Speaker" detail="Drag me" />
          </Flow.Node>
        </Flow.Group>

        <Flow.Edge from="hub" to="lamp" variant="smoothstep" arrow color="info" />
        <Flow.Edge from="hub" to="thermostat" variant="smoothstep" arrow color="info" />
        <Flow.Edge from="hub" to="speaker" variant="smoothstep" arrow color="info" />
        <Flow.Controls position="bottom-left" lock={false} />
      </Flow>
    </div>
  );
}

Groups and a minimap

Flow.Group holds ordinary elements and moves as one. The edges are joined to the groups by their id. Flow.MiniMap shows where the view is on the whole graph.

'use client';

import {
  ArchiveIcon,
  DatabaseIcon,
  GlobeIcon,
  HardDriveIcon,
  ServerIcon,
  ShieldCheckIcon,
} from 'lucide-react';
import { useCallback, useState, type ReactNode } from 'react';
import { Flow } from '@/components/panelui/flow';

function Service({ icon, name, detail }: { icon: ReactNode; name: string; detail: string }) {
  return (
    <Flow.GroupItem className="w-48">
      {icon}
      <Flow.NodeContent>
        <Flow.NodeTitle>{name}</Flow.NodeTitle>
        <Flow.NodeDescription>{detail}</Flow.NodeDescription>
      </Flow.NodeContent>
    </Flow.GroupItem>
  );
}

/**
 * Whether the canvas has room to lay the graph out across. It is the canvas
 * that is measured and not the window: in a page with a sidebar the two are
 * far apart.
 */
function useRoom(least: number) {
  const [wide, setWide] = useState(true);
  const watch = useCallback(
    (node: HTMLElement | null) => {
      if (!node) return;
      const observer = new ResizeObserver(([entry]) => setWide(entry.contentRect.width >= least));
      observer.observe(node);
      return () => observer.disconnect();
    },
    [least]
  );
  return [wide, watch] as const;
}

export default function FlowGroups() {
  const [wide, watch] = useRoom(720);
  // Side by side where there is room, and one under the other where there is not.
  const from = wide ? 'right' : 'bottom';
  const to = wide ? 'left' : 'top';

  return (
    // Taller where the groups are stacked, so they are not shrunk to fit.
    <div ref={watch} className={wide ? 'h-[28rem] w-full' : 'h-[36rem] w-full'}>
      <Flow
        // Fitted afresh when the layout changes.
        key={wide ? 'across' : 'down'}
        fitViewOnMount
        fitViewPadding={wide ? 48 : 24}
        label="Where a request goes"
        className="h-full rounded-none border-0"
      >
        <Flow.Background variant="dots" />
        <Flow.Group
          id="edge"
          label="Edge"
          position={{ x: 0, y: 0 }}
          className="flex flex-col gap-2"
        >
          <Service icon={<GlobeIcon />} name="Cache" detail="96 locations" />
          <Service icon={<ShieldCheckIcon />} name="Firewall" detail="Blocking 0.3%" />
        </Flow.Group>
        <Flow.Group
          id="core"
          label="Core"
          position={wide ? { x: 330, y: 130 } : { x: 70, y: 200 }}
          className="flex flex-col gap-2"
        >
          <Service icon={<ServerIcon />} name="Application" detail="Six instances" />
          <Service icon={<DatabaseIcon />} name="Database" detail="One primary, two copies" />
        </Flow.Group>
        <Flow.Group
          id="store"
          label="Storage"
          position={wide ? { x: 660, y: 0 } : { x: 0, y: 400 }}
          className="flex flex-col gap-2"
        >
          <Service icon={<HardDriveIcon />} name="Uploads" detail="2.1 TB" />
          <Service icon={<ArchiveIcon />} name="Backups" detail="Every six hours" />
        </Flow.Group>
        <Flow.Edge
          from="edge"
          to="core"
          variant="smoothstep"
          dashed
          arrow
          fromSide={from}
          toSide={to}
        />
        <Flow.Edge
          from="core"
          to="store"
          variant="smoothstep"
          dashed
          arrow
          fromSide={from}
          toSide={to}
        />
        <Flow.Controls position="top-left" lock={false} />
        {/* The map is for a graph too big to see at once, which on a narrow screen this is not. */}
        {wide ? <Flow.MiniMap position="bottom-right" /> : null}
      </Flow>
    </div>
  );
}

API Reference

Flow

PropTypeDefaultDescription
defaultViewportFlowViewport—Where the canvas looks to begin with.
minZoomnumber0.3The furthest out it can be zoomed.
maxZoomnumber2.5The furthest in it can be zoomed.
panOnDragbooleantrueWhether dragging the pane pans it.
zoomOnPinchbooleantrueWhether a pinch, or Control with the wheel, zooms it.
fitViewOnMountbooleanfalseFits every node into view once they have been measured.
fitViewPaddingnumber48The room left round the nodes when fitting them, in pixels.
onViewportChange(viewport: FlowViewport) => void—Called as the canvas is panned or zoomed.
onNodeDragEnd(id: string, position: FlowNodePosition) => void—Called with a node's new position when a drag or a key press has moved it.
onConnect(connection: FlowConnection) => void—Called when a connection drawn from a handle lands on another node.
isValidConnection(connection: FlowConnection) => boolean—Decides whether a connection may land. Without it, any two different nodes may be joined.
labelstring'Diagram'What a screen reader calls the canvas.

Flow.Background

PropTypeDefaultDescription
variant'dots' | 'lines' | 'cross' | 'none''bezier'Dots, a grid of lines, small crosses, or nothing.
gapnumber20The distance from one mark to the next, in pixels at a zoom of 1.
sizenumber—How big a mark is: a dot's radius, a line's thickness, half a cross's arm.
classNamestring—

Flow.Node

PropTypeDefaultDescription
idstring—What edges and onNodeDragEnd call this node.
positionFlowNodePosition—Where its top left corner is, on the graph.
draggablebooleantrueWhether it can be dragged and moved with the arrow keys.
confinebooleanfalseInside a Flow.Group, stop a drag at the group's edge instead of letting the node leave it. Does nothing outside a group.
pinnedbooleanfalseInside a Flow.Group, take no drag of its own: a drag that starts on it moves the group, and the node goes with it.
selectedbooleanfalseDraws it as the one that has been picked.
onPress() => void—Called when it is pressed without being dragged, or with Enter.
onDelete() => void—Called when Delete or Backspace is pressed on it.
moveStepnumber—How far one arrow key press moves it, in pixels. Shift moves four times as far.

Flow.Group

PropTypeDefaultDescription
labelReactNode—Written in the corner of the group.
size{ width: number; height: number }—A fixed size for the group. Give one when it holds Flow.Nodes, which are placed inside it rather than laid out by it, so they do not size it.

Flow.NodeHeader

PropTypeDefaultDescription
defaultTagName'div',—
propsmergeProps({ 'data-slot': 'flow-node-header', className: flowVariants().nodeHeader({ className }) }, props),—

Flow.NodeContent

PropTypeDefaultDescription
defaultTagName'div',—
propsmergeProps(—

Flow.NodeTitle

PropTypeDefaultDescription
defaultTagName'p',—
propsmergeProps({ 'data-slot': 'flow-node-title', className: flowVariants().nodeTitle({ className }) }, props),—

Flow.NodeDescription

PropTypeDefaultDescription
defaultTagName'p',—
propsmergeProps(—

Flow.NodeBadge

PropTypeDefaultDescription
colorFlowColor | 'muted'—Which of the theme's roles it is tinted with. muted is grey. Default muted.

Flow.GroupItem

PropTypeDefaultDescription
defaultTagName'div',—
propsmergeProps({ 'data-slot': 'flow-group-item', className: flowVariants().groupItem({ className }) }, props),—

Flow.Handle

PropTypeDefaultDescription
idstring—A name for this handle, so an edge can be joined to it and not only to the node.
positionFlowSide'right'Which face of the node it sits on.
offsetnumber0.5How far along that face, from 0 to 1.

Flow.Edge

PropTypeDefaultDescription
fromFlowEndpointReference—Where it leaves from: a node's id, "node.handle" for one of its handles, or { node, handle }.
toFlowEndpointReference—Where it arrives.
variantFlowEdgeVariant'bezier'A curve, a rounded right-angled route, a square one, or a straight line.
animatedbooleanfalseSets the dashes marching towards the target.
dashedbooleanfalseDraws it dashed.
colorFlowColor—One of the theme's roles. Without it the edge is a quiet grey.
widthnumber2How thick the line is, in pixels at a zoom of 1.
arrowbooleanfalseDraws an arrowhead where it arrives.
fromSideFlowSide—The face it leaves from. Worked out from where the two nodes are when left out.
toSideFlowSide—The face it arrives at.
radiusnumber8How round the corners of a smoothstep route are.
gapnumber20How far a routed edge runs straight out of a node before it turns.
curvaturenumber0.25How far a bezier bulges when its target is behind its source.

Flow.Controls

PropTypeDefaultDescription
zoombooleantrueShows the two zoom buttons.
fitbooleantrueShows the button that fits every node into view.
lockbooleantrueShows the button that locks the canvas against panning, zooming and dragging.
stepnumber1.3How much one press of a zoom button zooms.
positionFlowCorner'bottom-right'Which corner of the canvas they sit in.

Flow.MiniMap

PropTypeDefaultDescription
widthnumber120How wide the map is, in pixels.
heightnumber80How tall the map is, in pixels.
positionFlowCorner'bottom-left'Which corner of the canvas it sits in.

Every part also takes the props of the element it renders, and a className.

Notes

Size

The canvas is 24rem tall and as wide as its container. Set a height with className.

It is drawn as a bordered, rounded box. Inside a frame that already has an edge, such as a card or a panel, give it the frame's height and take its own edge off: className="h-full rounded-none border-0". The examples on this page do that.

fitViewOnMount fits the graph once. Where the room for the graph changes a great deal, as between a phone and a desktop, lay the nodes out for each and give the canvas a key that changes with the layout, so it is fitted again.

Positions

position is the node's top left corner on the graph, in pixels at a zoom of 1. The canvas holds a node's position after that: a drag moves it, and onNodeDragEnd reports where it stopped. To move a node yourself, keep its position in state and pass the new one.

fitViewOnMount zooms and pans so every node is in view once they have been measured. It never zooms in past 1.

Edges

from and to are node ids, or { node, handle } to join a handle by its id. The faces an edge uses are worked out from where the two nodes are, and change as one is dragged past the other; fromSide and toSide fix them.

variant is bezier, smoothstep, step or straight. animated sets dashes marching towards the target, and stops for anyone who has asked for reduced motion. color names one of the theme's roles; without it an edge is a quiet grey.

Panning and zooming

Drag the empty canvas to pan. Zoom with a pinch, or with Control or Command and the wheel. The plain wheel is left to the page, so a diagram in a long page does not trap its scroll. Flow.Controls has buttons for the same things, and a lock that stops all of it.

Keyboard

The canvas and every node are Tab stops. On the canvas the arrow keys pan, plus and minus zoom and 0 fits everything. On a node the arrow keys move it by moveStep, four times as far with Shift, Enter presses it and Delete calls onDelete.

A connection can only be drawn with a pointer. Where joining nodes matters to everyone, give them another way to do it, such as a menu on the node.

Inside a node

A node is a card by default; pass className to change it. Buttons, links and fields inside a node work as usual and do not start a drag. Put data-no-drag on anything else that should not.

Groups

A group's children are ordinary elements, laid out however you like inside it. They are not nodes: an edge is joined to the group, not to something in it.

Server Components

Flow is a client component. In a file that starts with "use client", write its parts with a dot, as on this page. A Server Component cannot read Flow.Background off the import, so each part is also exported by name: FlowBackground is Flow.Background, and so on for the others.

import { Flow, FlowBackground, FlowNode, FlowHandle, FlowEdge, FlowGroup, FlowGroupItem, FlowNodeHeader, FlowNodeContent, FlowNodeTitle, FlowNodeDescription, FlowNodeBadge, FlowControls, FlowMiniMap } from "@/components/panelui/flow"