Skip to content
D
Documentation

Route and edit edges

how-to
9 min readUpdated

Use edge routing when a connection needs to communicate more than “A connects to B”: avoid a wall, keep a right-angle run, preserve a hand-placed bend, or move an endpoint to another node.

Add routing choices and interior bends to your EdgeSpec to avoid obstacles or preserve a manual route; see the JavaScript quick start for the basic endpoint specification.

These examples start in the project from your framework's quick start: JavaScript, React, Vue, Angular, or Qwik. They use the packages those projects already install. Add the files below, then render the new component from your existing root component; keep the starter's entry point, configuration and stylesheet imports. In Qwik, add the route shown below.

Routing

  1. Create the shared scene module below. Put it in src/edge-scenes.ts in JavaScript, React and Vue, src/app/edge-scenes.ts in Angular, or src/routes/edges/edge-scenes.ts in Qwik.
  2. Mount it with your framework's example in Mount the edge editor. The first scene draws A → B around the obstacle, with C available as another destination.
  3. Drag the obstacle across the corridor. The route follows its new position; you do not request a repaint or a layout.

The mounted DiagramInstance supplies getEngine(). Its DiagramEngine supplies getRoutingEngine(), which returns the instance's RoutingEngine, not a separate routing registry.

The Routing scene enables the engine's live rerouting service for its orthogonal path type. enableLiveRerouting() requires a loaded diagram and updates connected paths on movement and resize. getLiveReroutingEngine() returns that service, or null before it exists. disableLiveRerouting() stops its pending reroutes. The other scenes use the renderer's per-link routing and bend preservation instead.

This complete module supplies all six scenes and the actions used by every framework below. Its node arrays use the library's NodeSpec type. Scene buttons load demonstration data; they do not save your edits.

ts
import type { RoutingEngine } from '@grafloria/engine';
import type { DiagramInstance, EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const sceneNames = [
  'Routing',
  'Routing algorithms',
  'Animating edges',
  'Highlight connected lines',
  'Edit bends',
  'Reconnect endpoints',
] as const;

export type SceneName = (typeof sceneNames)[number];

export function createScene(name: SceneName) {
  const nodes: NodeSpec[] = [];
  const edges: EdgeSpec[] = [];

  if (name === 'Routing algorithms') {
    const routers = ['orthogonal', 'manhattan', 'elk'] as const;
    routers.forEach((router, i) => {
      const y = 70 + i * 150;
      nodes.push(
        { id: `a${i}`, position: { x: 40, y }, size: { width: 100, height: 50 }, label: 'A' },
        { id: `b${i}`, position: { x: 660, y }, size: { width: 100, height: 50 }, label: 'B' },
        { id: `o${i}`, position: { x: 340, y: y - 20 }, size: { width: 120, height: 90 }, label: router },
      );
      edges.push({
        id: `e${i}`, source: `a${i}`, target: `b${i}`, router,
        style: { stroke: ['#2563eb', '#059669', '#7c3aed'][i], strokeWidth: 2.5 },
      });
    });
    return { nodes, edges };
  }

  if (name === 'Animating edges') {
    const types = ['marching-ants', 'flow', 'pulse', 'dash-flow'] as const;
    types.forEach((type, i) => {
      const y = 40 + i * 110;
      nodes.push(
        { id: `a${i}`, position: { x: 40, y }, size: { width: 160, height: 50 }, label: type },
        { id: `b${i}`, position: { x: 660, y }, size: { width: 100, height: 50 }, label: 'B' },
      );
      edges.push({ id: `e${i}`, source: `a${i}`, target: `b${i}`, type: 'direct' });
    });
    return { nodes, edges };
  }

  nodes.push(
    { id: 'a', position: { x: 40, y: 220 }, size: { width: 120, height: 60 }, label: 'A' },
    { id: 'b', position: { x: 660, y: 220 }, size: { width: 120, height: 60 }, label: 'B' },
    { id: 'c', position: { x: 660, y: 400 }, size: { width: 120, height: 60 }, label: 'C' },
  );

  if (name === 'Routing') {
    nodes.push({ id: 'wall', position: { x: 340, y: 170 }, size: { width: 140, height: 160 }, label: 'Obstacle' });
    edges.push({ id: 'ab', source: 'a', target: 'b', type: 'orthogonal' });
  } else if (name === 'Highlight connected lines') {
    nodes[0]!.selected = true;
    edges.push(
      { id: 'ab', source: 'a', target: 'b', type: 'direct' },
      { id: 'ac', source: 'a', target: 'c', type: 'direct' },
      { id: 'bc', source: 'b', target: 'c', type: 'direct' },
    );
  } else if (name === 'Edit bends') {
    edges.push({
      id: 'ab', source: 'a', target: 'b', type: 'orthogonal',
      sourceHandle: 'right@30', targetHandle: 'left@30',
      waypoints: [{ x: 240, y: 120 }, { x: 580, y: 120 }],
      label: 'Manual route', labelPlacement: 'above',
      labelStyle: { color: '#5f6b7a', fontSize: 11 },
    });
  } else {
    edges.push({
      id: 'ab', source: 'a', target: 'b', type: 'direct',
      sourceHandle: 'right', targetHandle: 'left',
    });
  }
  return { nodes, edges };
}

export function showScene(
  instance: Pick<DiagramInstance, 'getEngine' | 'getModel' | 'setNodes' | 'setEdges'>,
  name: SceneName,
): string {
  const engine = instance.getEngine();
  engine.disableLiveRerouting();
  engine.setInteractionConfig({ enableWaypointEditing: name === 'Edit bends' });
  const scene = createScene(name);
  instance.setEdges([]);
  instance.setNodes(scene.nodes);
  instance.setEdges(scene.edges);

  if (name === 'Routing') engine.enableLiveRerouting();

  if (name === 'Animating edges') {
    const types = ['marching-ants', 'flow', 'pulse', 'dash-flow'] as const;
    types.forEach((type, i) => {
      instance.getModel().getLink(`e${i}`)?.updateStyle({ animation: { type } });
    });
  }

  const routing: RoutingEngine = engine.getRoutingEngine();
  return `${name} · registered algorithms: ${routing.getAvailableAlgorithms().join(', ')}`;
}

export async function addConnection(
  instance: Pick<DiagramInstance, 'getEngine'>,
): Promise<void> {
  await instance.getEngine().addLink({
    sourcePortId: 'a__bottom', targetPortId: 'c__left', type: 'orthogonal',
  });
}

export async function removeConnection(
  instance: Pick<DiagramInstance, 'getEngine' | 'getModel'>,
): Promise<void> {
  if (instance.getModel().getLink('ab')) {
    await instance.getEngine().removeLink('ab');
  }
}

addLink() returns the live LinkModel installed in the diagram. It validates the port ids and records an add command; missing ports or a failed validation reject the promise. removeLink() records a remove command and resolves without a value; an absent link rejects. The example's error readout displays these rejections. Both operations participate in history.

The Add A → C and Remove A → B controls appear only in the Routing scene. Default port ids are deterministic, such as a__bottom; a spec's sourceHandle: 'bottom' resolves to that port.

Compare the result with the live obstacle-avoidance demo.

Routing algorithms

  1. Select Routing algorithms in the mounted editor.
  2. Compare the three A → B lanes. Each wall names the edge's router: orthogonal, manhattan, or elk.
  3. Drag a wall and inspect the route in its lane. Each edge selects its algorithm independently.

The createScene() branch above follows the authors' three-lane example. router answers where the line goes; connector answers how the resulting polyline is drawn. You do not register your own router for these choices.

router valueWhat it does
straightJoins the endpoints directly; ignores obstacles.
orthogonalUses horizontal/vertical elbows and port exit directions, with obstacle avoidance.
manhattanSearches a grid for a right-angle route, including a cost for direction changes.
avoidSelects A* obstacle-avoiding routing.
elkSelects the ELK edge-routing integration.
A registered nameSelects a router registered with registerRouter().

The live routing algorithms demo shows the same corridor comparison. For layouts that position the nodes as well as their connections, see Lay out a diagram.

Choose the rendered shape

The bend-editing scene uses type: 'orthogonal', while the three-lane comparison selects each router independently; see How Grafloria works for how type, router and connector combine.

typeRouter when omittedConnector when omitted and no explicit router intervenes
directstraightstraight
smoothstraightsmooth
orthogonalorthogonalrounded
bezierstraightbezier
connector valueWhat you see
straightStraight segments with hard corners.
roundedStraight segments joined by corner arcs.
smoothSmoothing through the routed points.
bezierA cubic Bézier between endpoints.
A registered nameThe registered connector's drawing.

An explicit orthogonal, manhattan, avoid, or elk router implies rounded unless you also set connector. To compare straight, step, smoothstep and Bézier visuals, open the edge types demo.

Animating edges

  1. Select Animating edges.
  2. Watch the four wires: marching ants, flow, pulse and dash flow. Their left-hand nodes name the animation.

The shared action calls updateStyle() on each mounted link, using style.animation. updateStyle() merges the supplied style fields; it does not replace routing or endpoints. This scene loads and styles demonstration data, rather than implementing an undoable property inspector.

Animation typeEffect
marching-antsMoves a short repeating dash pattern.
flowMoves a longer dash pattern.
pulseVaries opacity and stroke width.
dash-flowMoves dashes with longer gaps.
noneAdds no animation class.

speed accepts slow, normal, or fast; omitted, it uses normal. direction accepts forward or reverse; omitted, it runs forward. The renderer's AnimationService, available through instance.animations, controls global motion policy, including reduced-motion preferences and battery saving. Motion can stop while the static dash pattern remains.

The live animating edges demo also carries shapes along the painted paths. For moving tokens and execution-state visuals, continue with Animate flow and execution.

Highlight connected lines

  1. Select Highlight connected lines.
  2. A starts selected: its A → B and A → C lines come forward, while B → C fades.
  3. Select B instead. The emphasis follows the selection rather than a button-maintained list of ids.

Every mount below enables rendererConfig.highlightConnected. The renderer derives the highlighted lines on each frame: this is view state, not a model edit or an undo step, and exports omit the selection-derived effect. A selected line retains its own selected appearance. A connected line that crosses a card can appear lifted and dashed, distinguishing a crossing from an attachment.

For the full renderer instance, setHighlightConnected(true) enables the effect live; setHighlightConnected(false) disables it, and getHighlightConnected() reads the current setting. Pass options instead of true to trace farther with depth, distinguish outgoing lines with outgoing: 'dashed', or change dimOpacity and stroke.

Open the highlight connected lines demo to compare immediate neighbors with tracing paths in and out.

Edit bends and reconnect endpoints

Edit bends

  1. Select Edit bends. The edge starts with two saved interior waypoints, pinned side anchors, and a label above the route.
  2. Click the wire to select it, then click its selected body away from an endpoint to insert another waypoint.
  3. Drag an interior waypoint handle. The route follows the bend while its endpoints remain attached.

This scene opts into enableWaypointEditing; showWaypointHandles is already enabled. waypoints contains interior world-coordinate bends, not endpoint coordinates. Use waypoints to restore bends that the renderer preserves as manual routing intent. A hand-bent orthogonal line reattaches its ends when a node moves, and its adjacent run stays square.

The label's labelPlacement accepts on, above, and below: on puts it on the line in a box; above and below put it off the line. labelStyle supplies the label's own color, size and weight. Parallel lines and crossing jump styles are renderer configuration; see Label and distinguish edges for those settings.

Use the built-in interaction rather than constructing WaypointEditor. That lower-level editor handles point hit-testing, grid snapping and distance constraints. ControlPointEditor serves Bézier control handles; opt into enableControlPointEditing when your task is editing those controls rather than inserting polyline bends.

Compare with the live editable edge demo.

Reconnect endpoints

  1. Select Reconnect endpoints. The A → B edge pins its source to right and its target to left.
  2. Click the wire to select it, then drag its endpoint handle at B onto C's left port.
  3. Release on the valid target. The existing link becomes A → C; this is an undoable reconnection, not a second edge.

Keep waypoint insertion off in this scene so a path press has endpoint-reconnection intent. The built-in interaction checks endpoint ownership, port direction compatibility and connection-group rules, and draws a preview during the drag. getReconnectionPreview() reads that preview, or null outside a drag. setReconnectionPreview() writes or clears it for the interaction layer; it does not change the link's actual endpoints. You do not call it to reconnect a link.

Reconnect before placing manual bends. Endpoint dragging generates a fresh path from type, replacing hand-edited bends; Undo restores the endpoint ids, not those prior bends. To retain your intended bends, keep their interior coordinates in your app and supply them through waypoints after choosing the new endpoint. The reconnection scene therefore starts with an automatic direct route rather than a hand-bent path.

For unpinned perimeter attachment, omit handles and pass metadata: { connectionPoint: 'smart' } on the edge. A side anchor can also name a position: right@36 means 36 pixels down the right side; left@50% means halfway along it. The anchor moves with the box. Compare the floating edges demo and reconnect edge demo.

Mount the edge editor

Choose one framework. Each mount uses the shared module, starts with the Routing scene, and offers all the task buttons above. The status line lists the mounted engine's registered algorithms; errors from add/remove appear beside it.

Connect the ready callbacks of React's GrafloriaFlow, Vue's GrafloriaFlow, Qwik's GrafloriaFlow, or Angular's DiagramCanvasComponent (with its GrafloriaCanvasInstance) to the shared edge-scene actions below; see Edit nodes for state ownership and instance wiring.

The JavaScript example uses render and a custom element whose disconnection disposes its mounted instance. The framework bindings own their canvas teardown.

ts
// src/edge-editor.ts — import this module from the existing src/main.ts.
import { render } from '@grafloria/element';
import type { DiagramInstance } from '@grafloria/renderer';
import { addConnection, createScene, removeConnection, sceneNames, showScene } from './edge-scenes';

class EdgeEditor extends HTMLElement {
  private instance: DiagramInstance | null = null;

  connectedCallback(): void {
    if (this.instance) return;
    const controls = document.createElement('div');
    const host = document.createElement('div');
    host.style.height = '540px';
    const status = document.createElement('p');
    this.replaceChildren(controls, status, host);
    const scene = createScene('Routing');
    const api = render(scene, host, { highlightConnected: true });
    this.instance = api;
    const add = document.createElement('button');
    add.textContent = 'Add A → C';
    const remove = document.createElement('button');
    remove.textContent = 'Remove A → B';
    for (const name of sceneNames) {
      const button = document.createElement('button');
      button.textContent = name;
      button.onclick = () => {
        status.textContent = showScene(api, name);
        add.hidden = remove.hidden = name !== 'Routing';
      };
      controls.append(button);
    }
    add.onclick = () => { void addConnection(api).catch(error => { status.textContent = String(error); }); };
    remove.onclick = () => { void removeConnection(api).catch(error => { status.textContent = String(error); }); };
    controls.append(add, remove);
    status.textContent = showScene(api, 'Routing');
  }

  disconnectedCallback(): void {
    this.instance?.dispose();
    this.instance = null;
  }
}

customElements.define('edge-editor', EdgeEditor);

The React editor starts with A → B routed below the obstacle and C unconnected.

The Routing scene shows scene buttons, add/remove controls and the registered-algorithm readout above the canvas.

The Vue and Angular editors render the same initial corridor and controls, with the A → B connection bending below the obstacle and C below B.

For JavaScript, put <edge-editor></edge-editor> in your existing page after importing src/edge-editor.ts from its entry module. For the other frameworks, keep the existing root wrapper and add the component rather than replacing the entry file.

Options and pitfalls

OptionTypeDefaultWhat it does
typedirect / smooth / orthogonal / beziersmoothDerives routing and drawing when explicit settings are absent.
routerRouter nameDerived from typeChooses the route geometry.
connectorConnector nameDerived from router/typeChooses the polyline's drawing.
waypointsArray of world-coordinate pointsNo supplied bendsPreserves interior route constraints.
enableWaypointEditingbooleanfalseEnables interactive bend insertion and dragging.
showWaypointHandlesbooleantrueShows handles for waypoint editing.
enableControlPointEditingbooleanfalseEnables Bézier control-point dragging.
enableLinkReconnectionbooleantrueEnables dragging a selected link's endpoint to another port.
highlightConnectedBoolean or optionsfalseEmphasizes connections derived from selected nodes.

showLinkEndpointHandles shows the selected link's endpoint handles for reconnection. waypointEditor configures waypoint hit-testing, snapping, handle appearance and distance constraints. showControlPointHandles shows control-point handles on selected Bézier links; controlPointEditor configures those handles, their guide lines, snapping and symmetric control-point behavior.

  • Choose the router before restoring bends. setRouter() clears cached points, segments and manual-waypoint intent; setPathType() does the same when the type changes. Changing connector with setConnector() preserves routed points.
  • Use waypoints for interior bends. Do not treat the renderer's current polyline as a new automatic-routing specification on every render.
  • Named handles pin attachment. For perimeter-floating attachment, use the smart connection-point metadata rather than a side handle.
  • refreshGroupObstacles() reconciles visible collapsed groups as obstacles and removes hidden members from the obstacle map. Normal group add/remove/collapse/expand already triggers this; reserve the method for a grouping integration's batch reconciliation.
  • For an inspector that changes edge styles, use undoable commands rather than direct setup mutations; see Commands and history. For reconnection rules, see Validate connections.

Was this page helpful?