# Build a workflow editor

Use this pattern when your users assemble a workflow rather than draw an arbitrary graph. The editor starts with Trigger → Priority check and two branches. Users add steps from a palette, insert a step on a connection, edit a selected step in a side panel, and test the route with a sample priority.

The diagram owns the live models; the engine owns behavior and history. Keep step configuration in node data, make user edits through commands, and draw execution results as an overlay rather than document edits.

Start in the project left by your [JavaScript quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start), or [Qwik quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start). Keep its entry point, stylesheet imports and configuration. The quick starts already install the packages used below; no additional installation is needed.

## 1. Define steps and branching ports

Add this shared module in each project. [`NodeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) describes each step, and [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec) names its endpoints. An If step has an input and two ordered outputs, `true` above `false`. Ordinary steps have one input and one output.

[`RenderOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#renderoptions) supplies data-driven `nodeTemplates`. Each template returns content, ports and size. Marking a row with `data-port` puts its port level with that row. Build content with DOM nodes and `textContent` so a user-entered title is text, not markup.

```ts title="src/workflow.ts"
import type { RenderOptions } from '@grafloria/element';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export type StepKind = 'step' | 'if';

export function stepSpec(id: string, kind: StepKind): NodeSpec {
  return {
    id,
    type: kind,
    position: { x: 60, y: 400 },
    data: { title: kind === 'if' ? 'Priority check' : 'New step', label: kind === 'if' ? 'Priority check' : 'New step', threshold: 4 },
    size: { width: 170, height: kind === 'if' ? 120 : 92 },
    ports: [
      { id: `${id}:in`, type: 'input', side: 'left' },
      ...(kind === 'if'
        ? [
            { id: `${id}:true`, type: 'output' as const, side: 'right' as const, index: 0 },
            { id: `${id}:false`, type: 'output' as const, side: 'right' as const, index: 1 },
          ]
        : [{ id: `${id}:out`, type: 'output' as const, side: 'right' as const }]),
    ],
  };
}

export const nodes: NodeSpec[] = [
  { ...stepSpec('trigger', 'step'), position: { x: 40, y: 140 }, data: { title: 'Trigger', label: 'Trigger' } },
  { ...stepSpec('check', 'if'), position: { x: 300, y: 110 } },
  { ...stepSpec('urgent', 'step'), position: { x: 580, y: 40 }, data: { title: 'Urgent queue', label: 'Urgent queue' } },
  { ...stepSpec('normal', 'step'), position: { x: 580, y: 240 }, data: { title: 'Normal queue', label: 'Normal queue' } },
];

export const edges: EdgeSpec[] = [
  { id: 'start', source: 'trigger', sourceHandle: 'trigger:out', target: 'check', targetHandle: 'check:in' },
  { id: 'yes', source: 'check', sourceHandle: 'check:true', target: 'urgent', targetHandle: 'urgent:in', label: 'true' },
  { id: 'no', source: 'check', sourceHandle: 'check:false', target: 'normal', targetHandle: 'normal:in', label: 'false' },
];

export const options: RenderOptions = {
  nodeDropOnLink: true,
  affordances: {
    portAdd: true,
    linkAdd: true,
    linkDelete: true,
    linkButtons: 'hover-and-selected',
  },
  connectionReasons: true,
  nodeTemplates: {
    step: (data, { node }) => card(node.id, 'step', data),
    if: (data, { node }) => card(node.id, 'if', data),
  },
};

function card(id: string, kind: StepKind, data: Record<string, unknown>) {
  const spec = stepSpec(id, kind);
  const html = document.createElement('div');
  html.style.cssText = 'box-sizing:border-box;height:100%;padding:10px;border:1px solid #94a3b8;border-radius:10px;background:white;color:#172033;font:14px system-ui';
  const title = document.createElement('strong');
  title.textContent = typeof data['title'] === 'string' ? data['title'] : 'Step';
  html.append(title);
  for (const port of spec.ports ?? []) {
    const row = document.createElement('div');
    row.style.cssText = 'height:26px;line-height:26px;text-align:right;font-size:12px';
    if (port.id) row.dataset['port'] = port.id;
    row.textContent = port.type === 'input' ? 'input' : port.id?.split(':')[1] ?? 'output';
    html.append(row);
  }
  return { html, ports: spec.ports, size: spec.size };
}
```

The template functions run in the browser. `anchorPorts` already defaults to `true` with templates, so leave it out. A template is also responsible for deriving ports and size when its data changes; a [`SetNodeDataCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-r-u#setnodedatacommand) includes that structural change in the edit's undo step.

## 2. Add palette insertion and side-panel editing

Add the controller below beside `workflow.ts`. Each framework hands it a real, mounted [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) and a sibling element for the toolbar and side panel.

The palette starts a disconnected step at the bottom of the canvas. Pressing a free output's **+** first chooses that output; the palette then adds and connects the new step. Pressing a connection's **+** changes the palette into an insertion menu. The buttons only emit requests: your application decides which step to create.

The controller uses the shipped [`AddNodeCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-a-r#addnodecommand), [`AddLinkCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-a-r#addlinkcommand) and [`RemoveLinkCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-a-r#removelinkcommand), grouped with [`MacroCommand`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-commands-classes-a-r#macrocommand). [`buildNode`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-functions#buildnode) converts a palette spec into a [`NodeModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-nodemodel); [`LinkModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-linkmodel) names the ports to connect.

```ts title="src/workflow-editor.ts"
import {
  AddLinkCommand, AddNodeCommand, LinkModel, MacroCommand,
  RemoveLinkCommand, SetNodeDataCommand,
} from '@grafloria/engine';
import { buildNode, registerConnectionValidator } from '@grafloria/renderer';
import type { DiagramInstance, InsertNodeOnLinkOptions, RunOverlay } from '@grafloria/renderer';
import { stepSpec } from './workflow';
import type { StepKind } from './workflow';

let nextStepId = 0;

export function attachEditor(api: DiagramInstance, panel: HTMLElement): () => void {
  const engine = api.getEngine();
  const model = api.getModel();
  const abort = new AbortController();
  let disposed = false;
  let busy = false;
  let selected = '';
  let choose: ((kind: StepKind) => Promise<void>) | null = null;
  let runToken = 0;

  panel.innerHTML = `
    <div style="display:flex;gap:8px;flex-wrap:wrap">
      <button data-action="step">Add step</button>
      <button data-action="if">Add If</button>
      <button data-action="undo">Undo</button>
      <button data-action="redo">Redo</button>
      <button data-action="tidy">Tidy</button>
      <button data-action="readonly">Toggle read-only</button>
      <button data-action="run">Test workflow</button>
      <button data-action="clear">Clear run</button>
    </div>
    <p data-readout>Select a step to edit it, or add a step from the palette.</p>
    <aside style="display:flex;gap:12px;flex-wrap:wrap;padding:12px;border:1px solid #cbd5e1">
      <label>Title <input data-title></label>
      <label>If threshold <input data-threshold type="number" value="4"></label>
      <button data-action="save">Apply to selected step</button>
      <label>Test priority <input data-priority type="number" value="5"></label>
    </aside>`;

  const title = panel.querySelector<HTMLInputElement>('[data-title]')!;
  const threshold = panel.querySelector<HTMLInputElement>('[data-threshold]')!;
  const priority = panel.querySelector<HTMLInputElement>('[data-priority]')!;
  const readout = panel.querySelector<HTMLElement>('[data-readout]')!;
  const button = (name: string) => panel.querySelector<HTMLButtonElement>(`[data-action="${name}"]`)!;
  const say = (text: string) => { readout.textContent = text; };

  function newId(): string {
    let id: string;
    do { id = `workflow-step-${++nextStepId}`; } while (model.getNode(id));
    return id;
  }

  function sync(): void {
    const locked = api.isReadonly();
    const node = model.getNode(selected);
    if (!node) selected = '';
    title.value = node && typeof node.data['title'] === 'string' ? node.data['title'] : '';
    threshold.value = String(node && typeof node.data['threshold'] === 'number' ? node.data['threshold'] : 4);
    title.disabled = !node || locked || busy;
    threshold.disabled = !node || node.type !== 'if' || locked || busy;
    button('save').disabled = !node || locked || busy;
    button('undo').disabled = locked || busy || !engine.commandManager.canUndo();
    button('redo').disabled = locked || busy || !engine.commandManager.canRedo();
    for (const name of ['step', 'if', 'tidy']) button(name).disabled = locked || busy;
    button('run').disabled = busy;
    button('readonly').disabled = busy;
    button('readonly').setAttribute('aria-pressed', String(locked));
  }

  async function perform(action: () => Promise<void>): Promise<void> {
    if (busy || disposed) return;
    busy = true;
    sync();
    try { await action(); }
    catch (error) { say(error instanceof Error ? error.message : 'Operation failed'); }
    finally { busy = false; if (!disposed) sync(); }
  }

  async function add(kind: StepKind, portId?: string, position?: { x: number; y: number }): Promise<void> {
    if (api.isReadonly()) return;
    const id = newId();
    const spec = stepSpec(id, kind);
    if (position) spec.position = position;
    const macro = new MacroCommand('Add workflow step');
    macro.addStep(new AddNodeCommand(buildNode(spec, 0)));
    if (portId) macro.addStep(new AddLinkCommand(new LinkModel(portId, `${id}:in`)));
    await engine.commandManager.execute(macro);
    if (portId && !position) await api.placeNodes([id]);
    say(`Added ${kind}.`);
  }

  async function insert(linkId: string, kind: StepKind): Promise<void> {
    if (api.isReadonly()) return;
    const id = newId();
    const settings: InsertNodeOnLinkOptions = {
      inPort: `${id}:in`,
      outPort: `${id}:${kind === 'if' ? 'true' : 'out'}`,
      direction: 'LR',
      gap: 90,
    };
    const result = await api.insertNodeOnLink(linkId, stepSpec(id, kind), settings);
    say(result ? `Inserted ${result.nodeId}; moved ${result.moved.length} downstream steps.` : 'No insertion: check the link and ports.');
  }

  async function spliceExisting(linkId: string, nodeId: string): Promise<void> {
    if (api.isReadonly()) return;
    const link = model.getLink(linkId);
    const node = model.getNode(nodeId);
    if (!link || !node) return;
    const input = node.getPort(`${nodeId}:in`);
    const output = node.getPortsByType('output').find(port => port.getConnectionCount() === 0);
    if (!input || !output || input.getConnectionCount() !== 0) {
      say('Use a step with a free input and output.');
      return;
    }
    const upstream = new LinkModel(link.sourcePortId, input.id, link.pathType);
    upstream.setLabels(link.labels);
    const label = link.getMetadata('label');
    if (typeof label === 'string') upstream.setMetadata('label', label);
    const macro = new MacroCommand('Insert existing workflow step');
    macro.addStep(new RemoveLinkCommand(linkId));
    macro.addStep(new AddLinkCommand(upstream));
    macro.addStep(new AddLinkCommand(new LinkModel(output.id, link.targetPortId, link.pathType)));
    await engine.commandManager.execute(macro);
    say('Existing step connected into the workflow.');
  }

  function offer(action: (kind: StepKind) => Promise<void>): void {
    if (api.isReadonly() || busy) return;
    choose = action;
    say('Choose Add step or Add If from the palette.');
  }

  const subscriptions = [
    api.on('selection:change', ({ nodes }) => { selected = nodes[0]?.id ?? ''; sync(); }),
    api.on('nodes:change', sync),
    api.on('port:add-request', ({ portId }) => offer(kind => add(kind, portId))),
    api.on('link:add-request', ({ linkId }) => offer(kind => insert(linkId, kind))),
    api.on('link:delete-request', ({ linkId }) => { void perform(() => engine.removeLink(linkId)); }),
    api.on('connect:drop-empty', ({ portId, world }) => offer(kind => add(kind, portId, world))),
    api.on('link:insert-request', ({ linkId, nodeId }) => { void perform(() => spliceExisting(linkId, nodeId)); }),
  ];
  const historyEvents = ['command:executed', 'command:undone', 'command:redone', 'command:merged', 'command:history:cleared'];
  for (const event of historyEvents) engine.on(event, sync);
  const unwatchLock = model.on('readonly:change', sync);
  const unwatchNode = model.on('node:changed', sync);

  const unregister = registerConnectionValidator(({ sourceNode, targetNode }) => {
    if (sourceNode.diagram !== model || targetNode.diagram !== model) return true;
    const seen = new Set<string>();
    const todo = [targetNode.id];
    while (todo.length) {
      const id = todo.pop()!;
      if (id === sourceNode.id) return 'That connection creates a loop';
      if (seen.has(id)) continue;
      seen.add(id);
      for (const link of model.getNode(id)?.getOutgoingLinks() ?? []) {
        const next = model.getNodeByPortId(link.targetPortId);
        if (next) todo.push(next.id);
      }
    }
    return true;
  });

  async function testWorkflow(): Promise<void> {
    const samplePriority = priority.valueAsNumber;
    if (!Number.isFinite(samplePriority)) throw new Error('Enter a numeric test priority');
    const token = ++runToken;
    const wasReadonly = api.isReadonly();
    api.setReadonly(true);
    const overlay: RunOverlay = { nodes: {}, links: {} };
    const statuses = overlay.nodes!;
    const wires = overlay.links!;
    const queue: { id: string; via?: string }[] = [{ id: 'trigger' }];
    const seen = new Set<string>();
    try {
      while (queue.length && !disposed && token === runToken) {
        const item = queue.shift()!;
        if (seen.has(item.id)) continue;
        seen.add(item.id);
        const node = model.getNode(item.id);
        if (!node) continue;
        statuses[item.id] = { status: 'running' };
        if (item.via) wires[item.via] = { label: '1 item', animate: true };
        api.setOverlay(overlay);
        await new Promise<void>(resolve => setTimeout(resolve, 450));
        if (disposed || token !== runToken) return;
        statuses[item.id] = { status: 'completed', badge: '1 item' };
        if (item.via) wires[item.via] = { label: '1 item' };
        const limit = typeof node.data['threshold'] === 'number' ? node.data['threshold'] : 4;
        const chosenPort = `${node.id}:${samplePriority >= limit ? 'true' : 'false'}`;
        for (const link of node.getOutgoingLinks()) {
          if (node.type === 'if' && link.sourcePortId !== chosenPort) continue;
          const next = model.getNodeByPortId(link.targetPortId);
          if (next) queue.push({ id: next.id, via: link.id });
        }
        api.setOverlay(overlay);
      }
      say(`Test finished: ${seen.size} steps reached.`);
    } finally { if (!disposed) api.setReadonly(wasReadonly); }
  }

  panel.addEventListener('click', event => {
    if (!(event.target instanceof Element)) return;
    const action = event.target.closest<HTMLButtonElement>('button')?.dataset['action'];
    if (action === 'step' || action === 'if') {
      const pending = choose;
      choose = null;
      void perform(() => pending ? pending(action) : add(action));
    } else if (action === 'undo') void perform(() => engine.undo());
    else if (action === 'redo') void perform(() => engine.redo());
    else if (action === 'tidy') void perform(async () => { await api.tidy(); say('Tidied in output-port order.'); });
    else if (action === 'readonly' && !busy) {
      choose = null;
      api.setReadonly(!api.isReadonly());
      sync();
    } else if (action === 'save' && selected && !api.isReadonly()) {
      const id = selected;
      const value = title.value;
      const limit = threshold.valueAsNumber;
      void perform(async () => {
        if (!Number.isFinite(limit)) throw new Error('Enter a numeric threshold');
        await engine.commandManager.execute(new SetNodeDataCommand(id, { title: value, label: value, threshold: limit }));
        say('Step configuration updated.');
      });
    } else if (action === 'run') void perform(testWorkflow);
    else if (action === 'clear') { ++runToken; api.clearOverlay(); say('Run overlay cleared.'); }
  }, { signal: abort.signal });
  sync();

  return () => {
    disposed = true;
    ++runToken;
    abort.abort();
    for (const unsubscribe of subscriptions) unsubscribe();
    for (const event of historyEvents) engine.off(event, sync);
    unwatchLock();
    unwatchNode();
    unregister();
    panel.replaceChildren();
  };
}
```

[`InsertNodeOnLinkOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#insertnodeonlinkoptions) makes insertion explicit: the upstream connection enters `inPort`, the downstream connection leaves `outPort`, and `gap: 90` reserves more space than the default. Omit `labels` to keep branch labels beside the original source. Inserting an If routes the original destination through its `true` output; its `false` output stays available for another step.

`insertNodeOnLink()` replaces A → B with A → N → B and returns the new node ID, both link IDs and the IDs shifted downstream. One Undo restores the original link and removes the inserted node and its moves. A missing link, duplicate node ID or unresolved port produces `null`.

Adding after a free output records node creation and connection as one macro; `placeNodes([id])` then records placement separately. Undo placement first, then Undo addition. `placeNodes()` leaves the other flow steps in place. Tidy intentionally rearranges the connected flow in output-port order and records its moves as one undo step.

The side panel reads the selected live node and applies title and threshold with `SetNodeDataCommand`. Selection, node-change, history and read-only events keep its fields and Undo/Redo availability synchronized, including changes made with keyboard shortcuts. See [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) for transaction boundaries.

[`registerConnectionValidator`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-ext-functions#registerconnectionvalidator) rejects a proposed connection when a path from its target already reaches its source. Returning a reason string vetoes the connection; the enabled `connectionReasons` option displays that reason. The disposer removes this editor's rule when you unmount it.

## 3. Mount the editor in your framework

Use [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render) for browser application code when you want the instance immediately. It accepts diagram data, not Mermaid text. The framework tabs use the generic diagram host to pass the same template options and obtain the mounted instance through its ready callback.

React uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriadiagram), Vue uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriadiagram), Angular uses [`GrafloriaDiagramComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-classes#grafloriadiagramcomponent), and Qwik uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriadiagram). The shared controller operates on the instance each binding owns; it does not create a second engine.

In JavaScript, replace the quick start's counter/diagram body in `src/main.ts`, retaining its stylesheet import. For React and Vue, add the component shown and render it from the existing `App` component instead of the quick start's flow. For Angular, add `WorkflowComponent` to the existing root component's `imports` and replace `<app-flow />` with `<app-workflow />`; retain the router outlet. For Qwik, add `src/WorkflowRoute.tsx` below and re-export it from the quick start route as shown after the tabs. Keep all starter entry files unchanged.

:::code-group
```ts title="JavaScript"
// src/main.ts
import './style.css';
import { render } from '@grafloria/element';
import { nodes, edges, options } from './workflow';
import { attachEditor } from './workflow-editor';

const app = document.querySelector<HTMLDivElement>('#app')!;
app.innerHTML = '<div id="editor-panel"></div><div id="workflow-canvas" style="height:520px;width:100%"></div><button id="close-editor">Close editor</button>';
const panel = document.querySelector<HTMLElement>('#editor-panel')!;
const api = render({ nodes, edges }, '#workflow-canvas', options);
const detach = attachEditor(api, panel);
document.querySelector<HTMLButtonElement>('#close-editor')!.onclick = () => {
  detach();
  api.dispose();
  app.replaceChildren();
};
```
```tsx title="React"
// src/WorkflowEditor.tsx
import { useEffect, useRef } from 'react';
import { GrafloriaDiagram } from '@grafloria/react';
import { nodes, edges, options } from './workflow';
import { attachEditor } from './workflow-editor';

const spec = { nodes, edges };

export function WorkflowEditor() {
  const panel = useRef<HTMLDivElement>(null);
  const cleanup = useRef<(() => void) | null>(null);
  useEffect(() => () => { cleanup.current?.(); }, []);
  return (
    <section>
      <div ref={panel} />
      <GrafloriaDiagram spec={spec} options={options} style={{ height: 520 }}
        onReady={api => {
          cleanup.current?.();
          if (panel.current) cleanup.current = attachEditor(api, panel.current);
        }} />
    </section>
  );
}
```
```vue title="Vue"
<!-- src/WorkflowEditor.vue -->
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue';
import { GrafloriaDiagram } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges, options } from './workflow';
import { attachEditor } from './workflow-editor';

const spec = { nodes, edges };
const panel = ref<HTMLDivElement | null>(null);
let cleanup: (() => void) | null = null;
function ready(api: DiagramInstance): void {
  cleanup?.();
  if (panel.value) cleanup = attachEditor(api, panel.value);
}
onBeforeUnmount(() => cleanup?.());
</script>

<template>
  <section>
    <div ref="panel" />
    <div style="height: 520px">
      <GrafloriaDiagram :spec="spec" :options="options" @ready="ready" />
    </div>
  </section>
</template>
```
```ts title="Angular"
// src/app/workflow.component.ts
import { Component, ElementRef, viewChild } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges, options } from '../workflow';
import { attachEditor } from '../workflow-editor';

@Component({
  selector: 'app-workflow',
  imports: [GrafloriaDiagramComponent],
  template: `
    <div #panel></div>
    <grafloria-diagram [spec]="spec" [options]="options"
      (ready)="ready($event)" style="height:520px" />
  `,
})
export class WorkflowComponent implements OnDestroy {
  readonly spec = { nodes, edges };
  readonly options = options;
  readonly panel = viewChild.required<ElementRef<HTMLDivElement>>('panel');
  private cleanup: (() => void) | null = null;
  ready(api: DiagramInstance): void {
    this.cleanup?.();
    this.cleanup = attachEditor(api, this.panel().nativeElement);
  }
  ngOnDestroy(): void { this.cleanup?.(); }
}
```
```tsx title="Qwik"
// src/WorkflowRoute.tsx
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaDiagram } from '@grafloria/qwik';
import type { RenderOptions } from '@grafloria/element';
import { nodes, edges } from './workflow';

export default component$(() => {
  const panel = useSignal<HTMLDivElement>();
  const options = useSignal<NoSerialize<RenderOptions>>();
  const detach = useSignal<NoSerialize<() => void>>();
  useVisibleTask$(async ({ cleanup }) => {
    const workflow = await import('./workflow');
    options.value = noSerialize(workflow.options);
    cleanup(() => detach.value?.());
  });
  return (
    <section>
      <div ref={panel} />
      {options.value && (
        <GrafloriaDiagram spec={{ nodes, edges }} options={options.value}
          style={{ height: 520 }} onReady$={async api => {
            const { attachEditor } = await import('./workflow-editor');
            detach.value?.();
            if (panel.value) detach.value = noSerialize(attachEditor(api, panel.value));
          }} />
      )}
    </section>
  );
});
```
:::

![Look at Priority check's true branch leading to Urgent queue above the false branch to Normal queue, with palette buttons and the property panel above the canvas.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/4ad18fd50f56dfaf181b62cface3a924.png)

The React and Vue hosts start with Trigger feeding Priority check, Urgent queue above Normal queue, palette buttons and a disabled property panel. Each queue has a plus button beside its free output.

Only in the Qwik project, replace the contents of `src/routes/index.tsx` with `export { default } from '../WorkflowRoute';` to expose the component from the Qwik tab, saved at `src/WorkflowRoute.tsx`. Do not add either Qwik file to the JavaScript, React, Vue or Angular project.

Qwik builds the function-bearing options in a visible task and keeps them with `noSerialize()`. The server emits the panel shell; the browser mounts the diagram after those options exist. Cleanup belongs to unmount. The diagram components dispose their own instances; the controller removes its subscriptions, validator and panel listeners.

### Use the flow component without template options

For an editor with standard SVG nodes, use [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriaflow) instead of the generic host. This alternative renders the same branching graph and attaches the palette, property panel, Tidy and test controls through `onInit`. It does not enable the template host's connection-plus or drop-on-link affordances. Render this component from your existing `App` instead of `WorkflowEditor`.

```tsx title="src/StandardWorkflowEditor.tsx"
import { useEffect, useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { nodes, edges } from './workflow';
import { attachEditor } from './workflow-editor';

export function StandardWorkflowEditor() {
  const panel = useRef<HTMLDivElement>(null);
  const cleanup = useRef<(() => void) | null>(null);
  useEffect(() => () => { cleanup.current?.(); }, []);
  return (
    <section>
      <div ref={panel} />
      <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
        style={{ height: 520 }} onInit={api => {
          cleanup.current?.();
          if (panel.current) cleanup.current = attachEditor(api, panel.current);
        }} />
    </section>
  );
}
```

The shared step data includes `data.label` for SVG display as well as `data.title` for the templates. Applying a title updates both keys in one command, so newly added and edited steps display their titles in either host.

These samples deliberately let the instance own edits after seeding it. Do not feed the original arrays back after every click. If you need controlled React state instead, follow [React: state and content](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-state-and-content) and wire the change callbacks back to state.

## 4. Test graph-based execution

Press **Test workflow** with priority `5`. The sample walks outgoing links from `trigger`, evaluates each If's threshold, and follows only that If's chosen output. With the initial threshold `4`, the route reaches Urgent queue. Change the test priority to `2` and test again to reach Normal queue. The executor reads the graph as it exists now, including inserted steps; it does not use a fixed list of step IDs beyond the trigger.

The runnable executor is `testWorkflow()` in `workflow-editor.ts`. It simulates processing with a delay; it does not send messages or execute remote jobs. A visited set processes each reached node once. This is a sequential test runner, not a join scheduler or a durable backend executor.

[`RunOverlay`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#runoverlay) carries per-node status and badge plus per-link label and animation. `setOverlay()` draws these without writing the document, history or collaboration state. The test temporarily locks editing to keep its route stable and restores the preceding read-only setting when it finishes. **Clear run** cancels the test token and removes only the overlay.

Try the [Workflow automation builder](https://grafloria.com/demos/interaction/workflow-builder.html) for a deployment example whose test chooses branches from commit data and simulated health metrics. The [n8n-style workflow builder](https://grafloria.com/demos/interaction/n8n-workflow.html) shows the same graph-centered editor with a larger step catalog; [Marketing automation studio](https://grafloria.com/demos/interaction/marketing-automation.html) applies the pattern to marketing steps.

## Options that matter

The insertion settings choose what happens to the old connection. The other switches control editing affordances and template port placement.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `inPort` | `string` | First input, else axis-side port | Names the new node's entry port. |
| `outPort` | `string` | First output, else axis-side port | Names the new node's exit port. |
| `gap` | `number` | `60` | Reserves world-pixel space on each side of an inserted node. |
| `direction` | `'LR' \| 'TB'` | Inferred from the link | `LR` places along the horizontal axis; `TB` places along the vertical axis. |
| `labels` | `'upstream' \| 'downstream' \| 'none'` | `'upstream'` | Keeps old labels on A → N, keeps them on N → B, or carries none, respectively. |
| `anchorPorts` | `boolean` | `true` with templates | Aligns ports to the template's `data-port` rows. |
| `nodeDropOnLink` | `boolean` | `false` | Emits `link:insert-request` when a single dragged node lands on a link; the host handles the rewire. |
| `readonly` | `boolean` | `false` | Locks editing at mount. Use `setReadonly()` for live changes and `isReadonly()` to check the effective lock. |
| `affordances.linkButtons` | `'hover' \| 'hover-and-selected' \| 'selected'` | `'hover'` | Shows link buttons on hover, hover or selection, or selection only. |

Tidy and placement also accept `direction`, `rankGap` (default `80`), `nodeGap` (default `40`), `animate` (default `true`, off for reduced motion), and `duration` (default `280` ms). `placeNodes()` accepts `after` to specify the parent instead of deriving it from incoming links. Both calls resolve with the IDs moved.

The overlay status choices are `idle` (no frame), `pending` (dashed frame), `running` (pulsing frame), `completed` (green), `error` (red), and `warning` (amber). Your executor decides whether an error stops processing; the overlay only displays the result.

## Pitfalls and related tasks

- Request events do not insert or remove anything themselves. Handle `port:add-request`, `link:add-request`, `link:delete-request`, `connect:drop-empty`, and `link:insert-request` as the controller does.
- A dropped existing node is not a new-node insertion. The sample rewires its free input and output in a macro and leaves its position where the user dropped it. Only new-node insertion uses `insertNodeOnLink()` and its downstream spacing calculation.
- The registered connection validator rejects interactive loops. Programmatic rewiring is your application policy; the sample checks free ports but does not implement a full workflow compiler. See [Validate connections](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/validate-connections) for validation beyond this editor.
- Keep the generic host's seed spec and options stable: changing their value replaces the diagram. Change the live instance for edits instead.
- For persisted workflows, use [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore), not a projection of selected fields from the seed specs.

Explore the [Workflow editor kit](https://grafloria.com/demos/interaction/workflow-editor.html) for dynamic Switch rules, AI attachment slots and compact cards. Continue with [Animate flow and execution](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/animate-flow) for richer run controls, or [Preserve layout while editing](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/incremental-layout) for localized placement.
