# Angular Diagram Component

Diagram is a node-based flow editor for workflows, automations and pipelines: nodes drawn by your templates, connected by edges on a canvas that pans and zooms. Nodes are moved, connected and deleted with the mouse, a finger or the keyboard alone, every change is announced to screen readers, and a list of the nodes and their connections is always available. It renders on the server and has no dependency.

## Basic

A diagram has nodes , each with a unique id , the position of its top left corner in pixels and any data , and edges that connect a source node to a target node. Bind both two-way with [(nodes)] and [(edges)] : the diagram replaces the arrays when the user moves, connects or deletes something. Without a template, a node shows its data.label (change the field with nodeLabel ), with a target handle on its left and a source handle on its right. Drag a node to move it, drag from a handle to another to connect two nodes, drag the background to pan, and hold Ctrl or ⌘ with the wheel, or pinch, to zoom. Click to select, Shift and click to add to the selection, Shift and drag on the background to select with a box, and press Delete to remove the selection. Give the diagram a height: 28rem by default.

```typescript
import { Component } from '@angular/core';
import { DiagramEdge, DiagramModule, DiagramNode } from '@exhaustive-ui/core/diagram';

@Component({
    template: `
        <div class="card">
            <p-diagram [(nodes)]="nodes" [(edges)]="edges" fitViewOnInit ariaLabel="Basic flow" style="height: 22rem" />
        </div>
    `,
    standalone: true,
    imports: [DiagramModule]
})
export class DiagramBasicDemo {
    nodes: DiagramNode[] = [
        { id: 'start', position: { x: 0, y: 80 }, data: { label: 'Start' } },
        { id: 'review', position: { x: 240, y: 0 }, data: { label: 'Review' } },
        { id: 'publish', position: { x: 240, y: 160 }, data: { label: 'Publish' } },
        { id: 'done', position: { x: 480, y: 80 }, data: { label: 'Done' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'start-review', source: 'start', target: 'review' },
        { id: 'start-publish', source: 'start', target: 'publish' },
        { id: 'review-done', source: 'review', target: 'done' }
    ];
}
```

## Custom Nodes

A node is drawn by the template of its type : write &lt;ng-template pDiagramNode="trigger" let-node&gt; for the nodes of type trigger , and &lt;ng-template pDiagramNode let-node&gt; for the nodes without a type. The template receives the node as the implicit variable, its data , its label and the selected and dragging flags. Give the template a size, or set width and height on the node. Place the connection handles with the pDiagramHandle directive: a source handle starts connections, a target handle receives them, and position puts it on the top, right, bottom or left side. A node without handles can not be connected. The buttons, links and fields of a template work as usual and never start a drag; add the p-diagram-nodrag class to any other element that must not drag the node.

```typescript
import { Component } from '@angular/core';
import { DiagramEdge, DiagramModule, DiagramNode } from '@exhaustive-ui/core/diagram';

interface Step {
    label: string;
    detail: string;
}

@Component({
    template: `
        <div class="card">
            <p-diagram [(nodes)]="nodes" [(edges)]="edges" fitViewOnInit ariaLabel="Automation" style="height: 22rem">
                <ng-template pDiagramNode="trigger" let-node let-selected="selected">
                    <div class="w-56 rounded-border border border-surface bg-surface-0 dark:bg-surface-900 shadow-sm" [class.border-primary]="selected">
                        <div class="px-3 py-1 text-xs font-semibold uppercase tracking-wide bg-primary text-primary-contrast rounded-t-[inherit]">Trigger</div>
                        <div class="px-3 py-2">
                            <div class="font-semibold">{{ node.data.label }}</div>
                            <div class="text-sm text-muted-color">{{ node.data.detail }}</div>
                        </div>
                        <span pDiagramHandle type="source" position="right"></span>
                    </div>
                </ng-template>
                <ng-template pDiagramNode="action" let-node let-selected="selected">
                    <div class="w-56 rounded-border border border-surface bg-surface-0 dark:bg-surface-900 shadow-sm" [class.border-primary]="selected">
                        <span pDiagramHandle type="target" position="left"></span>
                        <div class="px-3 py-1 text-xs font-semibold uppercase tracking-wide bg-surface-100 dark:bg-surface-800 rounded-t-[inherit]">Action</div>
                        <div class="px-3 py-2">
                            <div class="font-semibold">{{ node.data.label }}</div>
                            <div class="text-sm text-muted-color">{{ node.data.detail }}</div>
                        </div>
                        <span pDiagramHandle type="source" position="right"></span>
                    </div>
                </ng-template>
            </p-diagram>
        </div>
    `,
    standalone: true,
    imports: [DiagramModule]
})
export class DiagramCustomnodesDemo {
    nodes: DiagramNode<Step>[] = [
        { id: 'form', type: 'trigger', position: { x: 0, y: 60 }, data: { label: 'Form submitted', detail: 'Contact form' } },
        { id: 'crm', type: 'action', position: { x: 300, y: 0 }, data: { label: 'Create a contact', detail: 'In the CRM' } },
        { id: 'mail', type: 'action', position: { x: 300, y: 140 }, data: { label: 'Send an email', detail: 'Welcome template' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'form-crm', source: 'form', target: 'crm' },
        { id: 'form-mail', source: 'form', target: 'mail' }
    ];
}
```

## Handles and Validation

A node can have several handles of the same type: name each one with handleId , and an edge picks them with sourceHandle and targetHandle . Without them, an edge uses the first handle of each type. A handle sits on the middle of its side; move it along the side with a style, such as top: 30% . isValidConnection receives the source , sourceHandle , target and targetHandle of a connection and tells whether it is allowed. A node is never connected to itself, and the same handles are never connected twice. While a connection is dragged, the handle under the pointer turns green or red; the refused targets are not offered in the keyboard list either. Here, a decision can only lead to an action, and its yes and no handles to one action each. Turn off autoConnect to add the edges yourself from onConnect , for example after asking for a label.

```typescript
import { Component } from '@angular/core';
import { DiagramConnection, DiagramEdge, DiagramModule, DiagramNode } from '@exhaustive-ui/core/diagram';

@Component({
    template: `
        <div class="card">
            <p-diagram [(nodes)]="nodes" [(edges)]="edges" [isValidConnection]="isValid" fitViewOnInit ariaLabel="Approval" style="height: 22rem">
                <ng-template pDiagramNode="decision" let-node>
                    <div class="relative w-44 h-24 flex items-center justify-center rounded-border border border-surface bg-surface-0 dark:bg-surface-900">
                        <span pDiagramHandle type="target" position="left"></span>
                        <span class="font-semibold">{{ node.data.label }}</span>
                        <span class="absolute right-3 text-xs text-muted-color" style="top: 18%">yes</span>
                        <span class="absolute right-3 text-xs text-muted-color" style="top: 62%">no</span>
                        <span pDiagramHandle type="source" position="right" handleId="yes" style="top: 30%" ariaLabel="Connect Amount over 500 when yes"></span>
                        <span pDiagramHandle type="source" position="right" handleId="no" style="top: 72%" ariaLabel="Connect Amount over 500 when no"></span>
                    </div>
                </ng-template>
            </p-diagram>
        </div>
    `,
    standalone: true,
    imports: [DiagramModule]
})
export class DiagramHandlesDemo {
    nodes: DiagramNode[] = [
        { id: 'request', position: { x: 0, y: 40 }, data: { label: 'Expense request' } },
        { id: 'amount', type: 'decision', position: { x: 230, y: 20 }, data: { label: 'Amount over 500?' } },
        { id: 'manager', position: { x: 480, y: -40 }, data: { label: 'Ask the manager' } },
        { id: 'pay', position: { x: 480, y: 120 }, data: { label: 'Pay' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'request-amount', source: 'request', target: 'amount' },
        { id: 'amount-manager', source: 'amount', sourceHandle: 'yes', target: 'manager', label: 'yes' }
    ];

    isValid = (connection: DiagramConnection) => {
        if (connection.source !== 'amount') {
            return true;
        }
        const action = connection.target === 'manager' || connection.target === 'pay';
        const used = this.edges.some((edge) => edge.source === 'amount' && edge.sourceHandle === connection.sourceHandle);
        return action && !used;
    };
}
```

## Edge Types and Labels

The type of an edge gives its shape: bezier , a curve, step , right angles, or straight . defaultEdgeType sets it for the edges without a type and for the line drawn while connecting. A label is shown in the middle of the edge and is part of its accessible name. markerEnd draws a filled arrow, arrowclosed by default, an open arrow , or none ; animated moves a dash along the edge to show a flow, and stands still when the user prefers reduced motion. Click an edge or its label to select it, or reach it with Tab after the nodes and press Space; Delete removes it.

```typescript
import { Component } from '@angular/core';
import { DiagramEdge, DiagramModule, DiagramNode } from '@exhaustive-ui/core/diagram';

@Component({
    template: `
        <div class="card">
            <p-diagram [(nodes)]="nodes" [(edges)]="edges" direction="vertical" fitViewOnInit ariaLabel="Edge types" style="height: 22rem" />
        </div>
    `,
    standalone: true,
    imports: [DiagramModule]
})
export class DiagramEdgesDemo {
    nodes: DiagramNode[] = [
        { id: 'source', position: { x: 220, y: 0 }, data: { label: 'Source' } },
        { id: 'bezier', position: { x: 0, y: 200 }, data: { label: 'Bezier' } },
        { id: 'step', position: { x: 220, y: 200 }, data: { label: 'Step' } },
        { id: 'straight', position: { x: 440, y: 200 }, data: { label: 'Straight' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'to-bezier', source: 'source', target: 'bezier', type: 'bezier', label: 'curve' },
        { id: 'to-step', source: 'source', target: 'step', type: 'step', label: 'animated', animated: true },
        { id: 'to-straight', source: 'source', target: 'straight', type: 'straight', label: 'open arrow', markerEnd: 'arrow' }
    ];
}
```

## Controls, Minimap and Background

The controls, shown unless showControls is false, zoom in and out, fit the view and show the list of the nodes and their connections. showMinimap adds a map of the whole diagram: click or drag in it to move the view. background draws dots , lines or none , every backgroundGap pixels. With snapToGrid , dragged nodes and arrow key moves snap to a grid of snapGrid pixels. The wheel scrolls the page, so that a diagram never traps the scroll: zoom with Ctrl or ⌘ and the wheel, a pinch, the controls or the + and - keys on the canvas, or set zoomOnScroll . minZoom and maxZoom limit the zoom. Bind the position and zoom with [(viewport)] , and use fitView , zoomIn , zoomOut , zoomTo , setCenter and setViewport from code.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DiagramEdge, DiagramModule, DiagramNode } from '@exhaustive-ui/core/diagram';
import { SelectButtonModule } from '@exhaustive-ui/core/selectbutton';
import { ToggleSwitchModule } from '@exhaustive-ui/core/toggleswitch';

@Component({
    template: `
        <div class="card">
            <div class="flex flex-wrap items-center gap-4 mb-4">
                <p-select-button [(ngModel)]="background" [options]="backgrounds" optionLabel="label" optionValue="value" [allowEmpty]="false" ariaLabelledBy="diagram-controls-background" />
                <span id="diagram-controls-background" class="sr-only">Background</span>
                <div class="flex items-center gap-2">
                    <p-toggle-switch [(ngModel)]="minimap" inputId="diagram-controls-minimap" />
                    <label for="diagram-controls-minimap">Minimap</label>
                </div>
                <div class="flex items-center gap-2">
                    <p-toggle-switch [(ngModel)]="snap" inputId="diagram-controls-snap" />
                    <label for="diagram-controls-snap">Snap to grid</label>
                </div>
            </div>
            <p-diagram [(nodes)]="nodes" [(edges)]="edges" [background]="background" [showMinimap]="minimap" [snapToGrid]="snap" [snapGrid]="20" fitViewOnInit ariaLabel="Pipeline" style="height: 24rem" />
        </div>
    `,
    standalone: true,
    imports: [DiagramModule, SelectButtonModule, ToggleSwitchModule, FormsModule]
})
export class DiagramControlsDemo {
    background: 'dots' | 'lines' | 'none' = 'dots';

    backgrounds = [
        { label: 'Dots', value: 'dots' },
        { label: 'Lines', value: 'lines' },
        { label: 'None', value: 'none' }
    ];

    minimap = true;

    snap = false;

    nodes: DiagramNode[] = [
        { id: 'commit', position: { x: 0, y: 100 }, data: { label: 'Commit' } },
        { id: 'lint', position: { x: 220, y: 0 }, data: { label: 'Lint' } },
        { id: 'test', position: { x: 220, y: 100 }, data: { label: 'Test' } },
        { id: 'build', position: { x: 220, y: 200 }, data: { label: 'Build' } },
        { id: 'deploy', position: { x: 440, y: 100 }, data: { label: 'Deploy' } },
        { id: 'notify', position: { x: 660, y: 100 }, data: { label: 'Notify' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'c-l', source: 'commit', target: 'lint' },
        { id: 'c-t', source: 'commit', target: 'test' },
        { id: 'c-b', source: 'commit', target: 'build' },
        { id: 'l-d', source: 'lint', target: 'deploy' },
        { id: 't-d', source: 'test', target: 'deploy' },
        { id: 'b-d', source: 'build', target: 'deploy' },
        { id: 'd-n', source: 'deploy', target: 'notify' }
    ];
}
```

## Save and Restore

The state of a diagram is plain data: nodes , edges and the viewport . toObject() returns the three together, ready for JSON.stringify ; set them back to restore the diagram. Save after onNodesChange , onEdgesChange and onViewportChange , which are emitted once a change is done, not during a drag. Keep only the fields you need in data , and merge with your own records when loading. This demo keeps the diagram in the local storage of the browser: move or connect nodes, save, change them again, then restore.

```typescript
import { Component, viewChild } from '@angular/core';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { Diagram, DiagramEdge, DiagramFlow, DiagramModule, DiagramNode, DiagramViewport } from '@exhaustive-ui/core/diagram';

const STORAGE_KEY = 'exhaustive-ui-diagram-demo';

const initialNodes = (): DiagramNode[] => [
    { id: 'idea', position: { x: 0, y: 40 }, data: { label: 'Idea' } },
    { id: 'draft', position: { x: 220, y: 40 }, data: { label: 'Draft' } },
    { id: 'ship', position: { x: 440, y: 40 }, data: { label: 'Ship' } }
];

const initialEdges = (): DiagramEdge[] => [{ id: 'idea-draft', source: 'idea', target: 'draft' }];

@Component({
    template: `
        <div class="card">
            <div class="flex flex-wrap items-center gap-2 mb-4">
                <p-button label="Save" severity="secondary" size="small" (onClick)="save()" />
                <p-button label="Restore" severity="secondary" size="small" (onClick)="restore()" />
                <p-button label="Reset" severity="secondary" size="small" text (onClick)="reset()" />
                <span class="text-sm text-muted-color" aria-live="polite">{{ status }}</span>
            </div>
            <p-diagram #diagram [(nodes)]="nodes" [(edges)]="edges" [(viewport)]="viewport" ariaLabel="Saved flow" style="height: 16rem" />
            @if (json) {
                <pre class="mt-4 p-3 text-xs rounded-border bg-surface-100 dark:bg-surface-800 overflow-auto max-h-48" tabindex="0" aria-label="Saved JSON">{{ json }}</pre>
            }
        </div>
    `,
    standalone: true,
    imports: [DiagramModule, ButtonModule]
})
export class DiagramPersistDemo {
    diagram = viewChild.required<Diagram>('diagram');

    nodes = initialNodes();

    edges = initialEdges();

    viewport: DiagramViewport = { x: 24, y: 72, zoom: 1 };

    status = '';

    json = '';

    save() {
        const flow = this.diagram().toObject();
        this.json = JSON.stringify(flow, null, 2);
        try {
            localStorage.setItem(STORAGE_KEY, this.json);
            this.status = `Saved ${flow.nodes.length} nodes and ${flow.edges.length} edges`;
        } catch {
            this.status = 'The browser does not allow saving';
        }
    }

    restore() {
        try {
            const flow: DiagramFlow | null = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null');
            if (!flow) {
                this.status = 'Nothing saved yet';
                return;
            }
            this.nodes = flow.nodes;
            this.edges = flow.edges;
            this.viewport = flow.viewport;
            this.status = 'Restored';
        } catch {
            this.status = 'Nothing could be restored';
        }
    }

    reset() {
        this.nodes = initialNodes();
        this.edges = initialEdges();
        this.viewport = { x: 24, y: 72, zoom: 1 };
        this.json = '';
        try {
            localStorage.removeItem(STORAGE_KEY);
        } catch {
            // nothing saved
        }
        this.status = 'Reset';
    }
}
```

## Workflow

An order workflow with two node types, a branch on the stock and a loop back after a reorder. layout() places the nodes in layers that follow the edges, from left to right or from top to bottom with direction , using their measured sizes; the edges that close a loop are ignored. The same layered layout is exported as layoutDiagram(nodes, edges, options) to place nodes before the first render, on the server too. New steps are added by updating nodes ; onSelectionChange gives the selected nodes and edges, here shown under the diagram. With readonly , the diagram can still be panned, zoomed and read, but nodes can not be moved, connected or deleted.

```typescript
import { Component, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { Diagram, DiagramEdge, DiagramModule, DiagramNode, DiagramSelectionChangeEvent, layoutDiagram } from '@exhaustive-ui/core/diagram';
import { ToggleSwitchModule } from '@exhaustive-ui/core/toggleswitch';

interface Task {
    label: string;
    owner: string;
}

function layoutNodes(nodes: DiagramNode<Task>[], edges: DiagramEdge[]) {
    return layoutDiagram(nodes, edges, { layerGap: 70, nodeGap: 40, nodeSize: (node) => (node.type === 'check' ? { width: 160, height: 48 } : { width: 192, height: 62 }) });
}

@Component({
    template: `
        <div class="card">
            <div class="flex flex-wrap items-center gap-2 mb-4">
                <p-button label="Arrange" severity="secondary" size="small" (onClick)="arrange()" />
                <p-button label="Add a step" severity="secondary" size="small" [disabled]="readonly" (onClick)="add()" />
                <div class="flex items-center gap-2 ml-2">
                    <p-toggle-switch [(ngModel)]="readonly" inputId="diagram-workflow-readonly" />
                    <label for="diagram-workflow-readonly">Read only</label>
                </div>
            </div>
            <p-diagram #diagram [(nodes)]="nodes" [(edges)]="edges" [readonly]="readonly" defaultEdgeType="step" fitViewOnInit showMinimap (onSelectionChange)="selected($event)" ariaLabel="Order workflow" style="height: 28rem">
                <ng-template pDiagramNode="task" let-node let-selected="selected">
                    <div class="w-48 rounded-border border bg-surface-0 dark:bg-surface-900 px-3 py-2" [class.border-surface]="!selected" [class.border-primary]="selected">
                        <span pDiagramHandle type="target" position="left"></span>
                        <div class="font-semibold">{{ node.data.label }}</div>
                        <div class="text-sm text-muted-color">{{ node.data.owner }}</div>
                        <span pDiagramHandle type="source" position="right"></span>
                    </div>
                </ng-template>
                <ng-template pDiagramNode="check" let-node let-selected="selected">
                    <div class="w-40 rounded-border border-2 border-dashed bg-surface-0 dark:bg-surface-900 px-3 py-2 text-center" [class.border-surface]="!selected" [class.border-primary]="selected">
                        <span pDiagramHandle type="target" position="left"></span>
                        <div class="font-semibold">{{ node.data.label }}</div>
                        <span pDiagramHandle type="source" position="right" handleId="yes" style="top: 30%"></span>
                        <span pDiagramHandle type="source" position="bottom" handleId="no"></span>
                    </div>
                </ng-template>
            </p-diagram>
            <p class="mt-4 mb-0 text-sm text-muted-color" aria-live="polite">{{ selection }}</p>
        </div>
    `,
    standalone: true,
    imports: [DiagramModule, ButtonModule, ToggleSwitchModule, FormsModule]
})
export class DiagramWorkflowDemo {
    diagram = viewChild.required<Diagram>('diagram');

    readonly = false;

    selection = 'Nothing selected';

    count = 0;

    nodes: DiagramNode<Task>[] = [
        { id: 'received', type: 'task', position: { x: 0, y: 0 }, data: { label: 'Order received', owner: 'Shop' } },
        { id: 'stock', type: 'check', position: { x: 0, y: 0 }, data: { label: 'In stock?', owner: 'Warehouse' } },
        { id: 'pack', type: 'task', position: { x: 0, y: 0 }, data: { label: 'Pick and pack', owner: 'Warehouse' } },
        { id: 'ship', type: 'task', position: { x: 0, y: 0 }, data: { label: 'Ship', owner: 'Carrier' } },
        { id: 'notify', type: 'task', position: { x: 0, y: 0 }, data: { label: 'Notify the customer', owner: 'Shop' } },
        { id: 'reorder', type: 'task', position: { x: 0, y: 0 }, data: { label: 'Reorder from supplier', owner: 'Purchasing' } }
    ];

    edges: DiagramEdge[] = [
        { id: 'received-stock', source: 'received', target: 'stock' },
        { id: 'stock-pack', source: 'stock', sourceHandle: 'yes', target: 'pack', label: 'in stock' },
        { id: 'stock-reorder', source: 'stock', sourceHandle: 'no', target: 'reorder', label: 'out of stock' },
        { id: 'reorder-stock', source: 'reorder', target: 'stock', type: 'bezier', animated: true },
        { id: 'pack-ship', source: 'pack', target: 'ship' },
        { id: 'ship-notify', source: 'ship', target: 'notify' }
    ];

    constructor() {
        // the positions come from the layered layout, measured nodes are placed again with arrange()
        this.nodes = layoutNodes(this.nodes, this.edges);
    }

    arrange() {
        this.diagram().layout({ layerGap: 70, nodeGap: 40 });
        requestAnimationFrame(() => this.diagram().fitView());
    }

    add() {
        const id = `step-${++this.count}`;
        const view = this.diagram().viewport();
        this.nodes = [...this.nodes, { id, type: 'task', position: { x: (40 - view.x) / view.zoom, y: (40 - view.y) / view.zoom }, data: { label: `New step ${this.count}`, owner: 'Unassigned' } }];
    }

    selected(event: DiagramSelectionChangeEvent<Task>) {
        const names = [...event.nodes.map((node) => node.data!.label), ...event.edges.map((edge) => edge.label ?? `${edge.source} to ${edge.target}`)];
        this.selection = names.length ? `Selected: ${names.join(', ')}` : 'Nothing selected';
    }
}
```

## Accessibility

Screen Reader A diagram is a visual medium, and no ARIA pattern describes a graph. Diagram gives every action a keyboard way and every state a text, and keeps a plain list as the reference: use it to check what a screen reader user gets, and test with your own content. The diagram is a group named by ariaLabel , ariaLabelledBy or "Diagram". Each node is a focusable group with the role description "node", named by its label, with ", selected" added while it is selected, and described by the keyboard instructions. The nodes come in the tab order of the nodes array, whatever their place on screen, so order the array the way the flow reads. Each source handle follows its node in the tab order: it is a button named "Connect Order received from its right side" that opens the list of the nodes it can connect to. Target handles are hidden from assistive technologies, since they appear in that list. The edges come after the nodes, as toggle buttons with the role description "connection", named "From Order received to Check stock" with their label. The list of the nodes and their connections is always in the page for screen readers, and the last button of the controls shows it on screen: for each node, the nodes it connects to and the labels of the edges. A polite live region announces the moves, connections, selections, deletions and zoom changes made with the keyboard and the controls. The minimap, the background and the edge labels are hidden from assistive technologies, as they repeat what the list and the edge names say. Every text can be translated with labels ; name the source handles of a custom node with ariaLabel when the side is not meaningful, such as "Connect Amount over 500 when yes". The dash of animated edges stands still and the transitions are removed when the user prefers reduced motion. The edges and the handles have a contrast of at least 3:1 with the canvas in the four presets. A node that gets the focus is panned into view.

## Known Limitations

This first version focuses on the editing of small and medium flows. It does not have yet: undo and redo, copy and paste, or grouping nodes into sub-flows; an edge path editor, edge templates, or edges that avoid the nodes: edges are drawn straight, as a curve or with right angles between their handles; a layout beyond the layered layout() helper: no force-directed or orthogonal layout, and nodes may overlap after a layout when their sizes vary a lot within a layer; rendering of only the visible nodes: every node and edge is in the page, which stays fluid up to about 500 nodes; during a drag, only the edges of the moved nodes get a new path, but larger diagrams are slower to render; node resizing by the user, and node rotation; arrow keys that follow the writing direction: they move nodes left and right on screen, also in right-to-left pages; a structure that screen readers navigate as a graph: they read the nodes, handles and edges in order, and the list of nodes and connections is the reference for the whole flow.

## Diagram

Diagram is a node-based flow editor: nodes drawn by templates and connected by edges on a canvas that pans and zooms, for workflows, automations and pipelines, usable with the keyboard and screen readers.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | DiagramPassThrough | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| nodes | DiagramNode<T>[] | [] | Nodes of the diagram. The diagram updates it with a new array when the user moves or deletes nodes, so it can be bound two-way with  `[(nodes)]` . |
| edges | DiagramEdge<any>[] | [] | Edges of the diagram. The diagram updates it with a new array when the user connects nodes or deletes edges, so it can be bound two-way with  `[(edges)]` . |
| viewport | DiagramViewport | { x: 0, y: 0, zoom: 1 } | Position and zoom of the viewport, bound two-way with  `[(viewport)]`  to save or restore it. |
| minZoom | number | 0.2 | Smallest zoom. |
| maxZoom | number | 2 | Largest zoom. |
| zoomOnScroll | boolean | false | Whether the mouse wheel zooms. By default, the wheel scrolls the page, and Ctrl or ⌘ with the wheel, or a pinch, zooms. |
| panOnDrag | boolean | true | Whether dragging the background pans the diagram. Space and drag always pans. |
| snapToGrid | boolean | false | Whether dragged nodes snap to a grid of snapGrid pixels. |
| snapGrid | number | 20 | Size of the snap grid, in pixels. |
| background | "none" \| "dots" \| "lines" | 'dots' | Pattern of the background. |
| backgroundGap | number | 20 | Space between the dots or lines of the background, in pixels at zoom 1. |
| showControls | boolean | true | Whether the zoom controls are shown. |
| showMinimap | boolean | false | Whether the minimap is shown. |
| fitViewOnInit | boolean | false | Whether the view fits the nodes once they are measured, after the first render. |
| readonly | boolean | false | Whether the diagram can only be viewed: nodes can not be moved, connected or deleted. Panning, zooming and selection still work. |
| nodesDraggable | boolean | true | Whether the nodes can be moved. |
| nodesConnectable | boolean | true | Whether the nodes can be connected. |
| elementsSelectable | boolean | true | Whether the nodes and edges can be selected. |
| deletable | boolean | true | Whether the Delete and Backspace keys delete the selection. |
| defaultEdgeType | DiagramEdgeType | 'bezier' | Shape of the edges without a type, and of the line drawn while connecting. |
| defaultMarkerEnd | DiagramMarker | 'arrowclosed' | Marker at the end of the edges without a markerEnd. |
| autoConnect | boolean | true | Whether a connection made by the user adds an edge to edges. Turn it off to add the edge yourself from onConnect. |
| isValidConnection | (connection: DiagramConnection) => boolean | - | Tells whether a connection is allowed, on top of the built-in rules: no connection of a node to itself and no duplicate edge. Refused targets are not offered in the connect menu and show as invalid while dragging. |
| nodeLabel | string \| ((node: DiagramNode<T>) => string) | 'data.label' | Name of the field, or a function, that gives the name of a node: shown by the default node, used as its accessible name, in the announcements and in the text alternative. |
| direction | DiagramDirection | 'horizontal' | Direction of the flow: the sides of the handles of the default node, and the default of the layout method. |
| keyboardStep | number | 10 | Distance a node moves with an arrow key, in pixels; Shift multiplies it by 5. With snapToGrid, a step is the snap grid. |
| labels | Partial<DiagramLabels> | - | Texts of the component, merged with the English defaults. |
| ariaLabel | string | - | Accessible name of the diagram. |
| ariaLabelledBy | string | - | Identifier of the element that labels the diagram. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| onNodesChange | event: DiagramNodesChangeEvent<T | Callback to invoke when nodes are moved, removed or laid out, after nodes is updated. |
| onEdgesChange | event: DiagramEdgesChangeEvent | Callback to invoke when edges are added or removed, after edges is updated. |
| onConnect | event: DiagramConnectEvent | Callback to invoke when the user connects two nodes, with the pointer or the keyboard. |
| onNodeClick | event: DiagramNodeClickEvent<T | Callback to invoke when a node is clicked without being dragged. |
| onEdgeClick | event: DiagramEdgeClickEvent | Callback to invoke when an edge or its label is clicked. |
| onSelectionChange | event: DiagramSelectionChangeEvent<T | Callback to invoke when the selected nodes or edges change. |
| onViewportChange | value: DiagramViewport | Callback to invoke when a pan or a zoom ends, or a method changes the viewport. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| zoomIn | announce: boolean | void | Zooms in by 20%, around the center of the view. |
| zoomOut | announce: boolean | void | Zooms out by 20%, around the center of the view. |
| zoomTo | zoom: number | void | Sets the zoom, around the center of the view. |
| setViewport | viewport: DiagramViewport | void | Sets the position and zoom of the viewport. |
| setCenter | x: number, y: number, zoom: number | void | Centers the view on a point of the diagram. |
| fitView | options: DiagramFitViewOptions | void | Zooms and pans so that the nodes fit in the view. |
| screenToFlowPosition | point: DiagramXYPosition | void | Converts a point of the screen, such as the clientX and clientY of a drop event, to a point of the diagram. |
| setSelected | nodeIds: string[], edgeIds: string[] | void | Selects the given nodes and edges, replacing the selection. |
| clearSelection |  | void | Empties the selection. |
| getSelection |  | void | The selected nodes and edges. |
| deleteSelected |  | void | Deletes the selected nodes and edges, and the edges of the deleted nodes. Nodes and edges with deletable false stay. |
| deleteElements | nodeIds: string[], edgeIds: string[] | void | Deletes nodes and edges, and the edges of the deleted nodes. Nodes and edges with deletable false stay. |
| canConnect | connection: DiagramConnection | void | Whether a connection is allowed: two different connectable nodes, no identical edge yet, and isValidConnection agrees. |
| layout | options: DiagramLayoutOptions | void | Places the nodes in layers that follow the edges, with the measured sizes of the nodes, and updates nodes. |
| toObject |  | void | The nodes, edges and viewport, to save the diagram, for example as JSON. Restore it by setting nodes, edges and viewport. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element. |
| viewport | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the viewport, the area that is panned and zoomed. |
| background | PassThroughOption<SVGSVGElement, I> | Used to pass attributes to the SVG of the background pattern. |
| transform | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the layer that is translated and scaled with the viewport. |
| nodes | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the layer of the nodes. |
| node | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to a node. |
| edges | PassThroughOption<SVGSVGElement, I> | Used to pass attributes to the SVG of the edges. |
| edge | PassThroughOption<SVGGElement, I> | Used to pass attributes to the group of an edge. |
| edgePath | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the visible path of an edge. |
| edgeLabel | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the label of an edge. |
| connectionLine | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the line drawn while a connection is dragged. |
| selectionBox | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the rectangle of a box selection. |
| controls | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the zoom controls. |
| controlButton | PassThroughOption<HTMLButtonElement, I> | Used to pass attributes to a button of the controls. |
| minimap | PassThroughOption<SVGSVGElement, I> | Used to pass attributes to the minimap. |
| connectMenu | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the list of targets opened from a handle with the keyboard. |
| connectOption | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to a target of the connect menu. |
| outline | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the text alternative, the list of the nodes and their connections. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-diagram | Class name of the root element |
| p-diagram-viewport | Class name of the viewport |
| p-diagram-background | Class name of the background pattern |
| p-diagram-transform | Class name of the layer translated and scaled with the viewport |
| p-diagram-nodes | Class name of the layer of the nodes |
| p-diagram-node | Class name of a node |
| p-diagram-node-label | Class name of the label of a default node |
| p-diagram-handle | Class name of a connection handle |
| p-diagram-edges | Class name of the SVG of the edges |
| p-diagram-edge | Class name of an edge |
| p-diagram-edge-interaction | Class name of the wide invisible path that makes an edge easy to click |
| p-diagram-edge-path | Class name of the visible path of an edge |
| p-diagram-edge-labels | Class name of the layer of the edge labels |
| p-diagram-edge-label | Class name of the label of an edge |
| p-diagram-marker | Class name of an arrow marker |
| p-diagram-connection-line | Class name of the line drawn while connecting |
| p-diagram-selection-box | Class name of the rectangle of a box selection |
| p-diagram-controls | Class name of the controls |
| p-diagram-control-button | Class name of a button of the controls |
| p-diagram-control-icon | Class name of the icon of a control button |
| p-diagram-minimap | Class name of the minimap |
| p-diagram-minimap-node | Class name of a node of the minimap |
| p-diagram-minimap-mask | Class name of the mask of the minimap outside the view |
| p-diagram-connect-menu | Class name of the connect menu |
| p-diagram-connect-option | Class name of a target of the connect menu |
| p-diagram-outline | Class name of the visible text alternative |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| diagram.background | --p-diagram-background | Background of the canvas |
| diagram.border.color | --p-diagram-border-color | Border color of the diagram |
| diagram.border.radius | --p-diagram-border-radius | Border radius of the diagram |
| diagram.color | --p-diagram-color | Text color of the diagram |
| diagram.transition.duration | --p-diagram-transition-duration | Transition duration |
| diagram.focus.ring.width | --p-diagram-focus-ring-width | Focus ring width of the canvas |
| diagram.focus.ring.color | --p-diagram-focus-ring-color | Focus ring color of the canvas |
| diagram.pattern.color | --p-diagram-pattern-color | Color of the dots or lines of the background |
| diagram.node.background | --p-diagram-node-background | Background of a default node |
| diagram.node.border.color | --p-diagram-node-border-color | Border color of a default node |
| diagram.node.hover.border.color | --p-diagram-node-hover-border-color | Border color of a default node on hover |
| diagram.node.selected.border.color | --p-diagram-node-selected-border-color | Border color of a selected node |
| diagram.node.border.radius | --p-diagram-node-border-radius | Border radius of a node |
| diagram.node.color | --p-diagram-node-color | Text color of a node |
| diagram.node.padding | --p-diagram-node-padding | Padding of a default node |
| diagram.node.min.width | --p-diagram-node-min-width | Minimum width of a default node |
| diagram.node.font.size | --p-diagram-node-font-size | Font size of a default node |
| diagram.node.shadow | --p-diagram-node-shadow | Shadow of a default node |
| diagram.node.selected.shadow | --p-diagram-node-selected-shadow | Shadow of a selected default node |
| diagram.node.focus.ring.width | --p-diagram-node-focus-ring-width | Focus ring width of a node, a handle and a control |
| diagram.node.focus.ring.style | --p-diagram-node-focus-ring-style | Focus ring style of a node, a handle and a control |
| diagram.node.focus.ring.color | --p-diagram-node-focus-ring-color | Focus ring color of a node, a handle and a control |
| diagram.node.focus.ring.offset | --p-diagram-node-focus-ring-offset | Focus ring offset of a node, a handle and a control |
| diagram.node.focus.ring.shadow | --p-diagram-node-focus-ring-shadow | Focus ring shadow of a node, a handle and a control |
| diagram.handle.size | --p-diagram-handle-size | Size of a connection handle |
| diagram.handle.background | --p-diagram-handle-background | Background of a handle |
| diagram.handle.border.color | --p-diagram-handle-border-color | Border color of a handle |
| diagram.handle.border.width | --p-diagram-handle-border-width | Border width of a handle |
| diagram.handle.hover.background | --p-diagram-handle-hover-background | Background of a connectable handle on hover |
| diagram.handle.valid.background | --p-diagram-handle-valid-background | Background of a target handle that accepts the connection being dragged |
| diagram.handle.invalid.background | --p-diagram-handle-invalid-background | Background of a target handle that refuses the connection being dragged |
| diagram.edge.color | --p-diagram-edge-color | Color of an edge |
| diagram.edge.width | --p-diagram-edge-width | Stroke width of an edge |
| diagram.edge.hover.color | --p-diagram-edge-hover-color | Color of an edge on hover |
| diagram.edge.selected.color | --p-diagram-edge-selected-color | Color of a selected edge |
| diagram.edge.focus.color | --p-diagram-edge-focus-color | Color of the focus halo of an edge |
| diagram.edge.label.background | --p-diagram-edge-label-background | Background of an edge label |
| diagram.edge.label.border.color | --p-diagram-edge-label-border-color | Border color of an edge label |
| diagram.edge.label.color | --p-diagram-edge-label-color | Text color of an edge label |
| diagram.edge.label.border.radius | --p-diagram-edge-label-border-radius | Border radius of an edge label |
| diagram.edge.label.padding | --p-diagram-edge-label-padding | Padding of an edge label |
| diagram.edge.label.font.size | --p-diagram-edge-label-font-size | Font size of an edge label |
| diagram.connection.line.color | --p-diagram-connection-line-color | Color of the line drawn while connecting |
| diagram.selection.box.background | --p-diagram-selection-box-background | Background of the box selection |
| diagram.selection.box.border.color | --p-diagram-selection-box-border-color | Border color of the box selection |
| diagram.controls.offset | --p-diagram-controls-offset | Distance of the controls, the minimap and the list of nodes from the edges of the diagram |
| diagram.controls.gap | --p-diagram-controls-gap | Gap between the buttons of the controls |
| diagram.controls.padding | --p-diagram-controls-padding | Padding of the controls |
| diagram.controls.background | --p-diagram-controls-background | Background of the controls and the list of nodes |
| diagram.controls.border.color | --p-diagram-controls-border-color | Border color of the controls and the list of nodes |
| diagram.controls.border.radius | --p-diagram-controls-border-radius | Border radius of the controls and the list of nodes |
| diagram.controls.shadow | --p-diagram-controls-shadow | Shadow of the controls, the minimap and the list of nodes |
| diagram.controls.button.size | --p-diagram-controls-button-size | Size of a control button |
| diagram.controls.button.border.radius | --p-diagram-controls-button-border-radius | Border radius of a control button |
| diagram.controls.button.color | --p-diagram-controls-button-color | Color of a control button |
| diagram.controls.button.hover.background | --p-diagram-controls-button-hover-background | Background of a control button on hover or pressed |
| diagram.controls.button.hover.color | --p-diagram-controls-button-hover-color | Color of a control button on hover or pressed |
| diagram.minimap.width | --p-diagram-minimap-width | Width of the minimap |
| diagram.minimap.height | --p-diagram-minimap-height | Height of the minimap |
| diagram.minimap.background | --p-diagram-minimap-background | Background of the minimap |
| diagram.minimap.border.color | --p-diagram-minimap-border-color | Border color of the minimap |
| diagram.minimap.border.radius | --p-diagram-minimap-border-radius | Border radius of the minimap |
| diagram.minimap.node.color | --p-diagram-minimap-node-color | Color of a node in the minimap |
| diagram.minimap.selected.node.color | --p-diagram-minimap-selected-node-color | Color of a selected node in the minimap |
| diagram.minimap.mask.color | --p-diagram-minimap-mask-color | Color of the minimap outside the view |
| diagram.connect.menu.background | --p-diagram-connect-menu-background | Background of the connect menu |
| diagram.connect.menu.border.color | --p-diagram-connect-menu-border-color | Border color of the connect menu |
| diagram.connect.menu.color | --p-diagram-connect-menu-color | Text color of the connect menu |
| diagram.connect.menu.border.radius | --p-diagram-connect-menu-border-radius | Border radius of the connect menu |
| diagram.connect.menu.shadow | --p-diagram-connect-menu-shadow | Shadow of the connect menu |
| diagram.connect.menu.padding | --p-diagram-connect-menu-padding | Padding of the connect menu |
| diagram.connect.menu.option.padding | --p-diagram-connect-menu-option-padding | Padding of a target of the connect menu |
| diagram.connect.menu.option.border.radius | --p-diagram-connect-menu-option-border-radius | Border radius of a target of the connect menu |
| diagram.connect.menu.option.hover.background | --p-diagram-connect-menu-option-hover-background | Background of a target on hover |
| diagram.connect.menu.option.focus.background | --p-diagram-connect-menu-option-focus-background | Background of the active target |
| diagram.connect.menu.option.focus.color | --p-diagram-connect-menu-option-focus-color | Text color of the active target |
| diagram.outline.padding | --p-diagram-outline-padding | Padding of the visible list of nodes |
| diagram.outline.font.size | --p-diagram-outline-font-size | Font size of the visible list of nodes |
| diagram.outline.muted.color | --p-diagram-outline-muted-color | Color of the connections in the list of nodes |

