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
- Create the shared scene module below. Put it in
src/edge-scenes.tsin JavaScript, React and Vue,src/app/edge-scenes.tsin Angular, orsrc/routes/edges/edge-scenes.tsin Qwik. - 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.
- 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.
tsimport 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
- Select Routing algorithms in the mounted editor.
- Compare the three A → B lanes. Each wall names the edge's
router:orthogonal,manhattan, orelk. - 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 value | What it does |
|---|---|
straight | Joins the endpoints directly; ignores obstacles. |
orthogonal | Uses horizontal/vertical elbows and port exit directions, with obstacle avoidance. |
manhattan | Searches a grid for a right-angle route, including a cost for direction changes. |
avoid | Selects A* obstacle-avoiding routing. |
elk | Selects the ELK edge-routing integration. |
| A registered name | Selects 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.
type | Router when omitted | Connector when omitted and no explicit router intervenes |
|---|---|---|
direct | straight | straight |
smooth | straight | smooth |
orthogonal | orthogonal | rounded |
bezier | straight | bezier |
connector value | What you see |
|---|---|
straight | Straight segments with hard corners. |
rounded | Straight segments joined by corner arcs. |
smooth | Smoothing through the routed points. |
bezier | A cubic Bézier between endpoints. |
| A registered name | The 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
- Select Animating edges.
- 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 type | Effect |
|---|---|
marching-ants | Moves a short repeating dash pattern. |
flow | Moves a longer dash pattern. |
pulse | Varies opacity and stroke width. |
dash-flow | Moves dashes with longer gaps. |
none | Adds 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
- Select Highlight connected lines.
- A starts selected: its A → B and A → C lines come forward, while B → C fades.
- 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
- Select Edit bends. The edge starts with two saved interior
waypoints, pinned side anchors, and a label above the route. - Click the wire to select it, then click its selected body away from an endpoint to insert another waypoint.
- 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
- Select Reconnect endpoints. The A → B edge pins its source to
rightand its target toleft. - Click the wire to select it, then drag its endpoint handle at B onto C's left port.
- 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);
tsx// src/EdgeEditor.tsx — render <EdgeEditor /> from the existing App component.
import { useRef, useState } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { addConnection, createScene, removeConnection, sceneNames, showScene } from './edge-scenes';
import type { SceneName } from './edge-scenes';
const initial = createScene('Routing');
export function EdgeEditor() {
const instance = useRef<DiagramInstance | null>(null);
const [scene, setScene] = useState<SceneName>('Routing');
const [status, setStatus] = useState('');
const [ready, setReady] = useState(false);
return (
<section>
{sceneNames.map(name => <button key={name} disabled={!ready} onClick={() => {
if (!instance.current) return;
setStatus(showScene(instance.current, name));
setScene(name);
}}>{name}</button>)}
{scene === 'Routing' && <>
<button disabled={!ready} onClick={() => {
if (instance.current) void addConnection(instance.current).catch(error => setStatus(String(error)));
}}>Add A → C</button>
<button disabled={!ready} onClick={() => {
if (instance.current) void removeConnection(instance.current).catch(error => setStatus(String(error)));
}}>Remove A → B</button>
</>}
<p>{status}</p>
<div style={{ height: 540 }}>
<GrafloriaFlow defaultNodes={initial.nodes} defaultEdges={initial.edges}
rendererConfig={{ highlightConnected: true }}
onInit={api => {
instance.current = api;
setStatus(showScene(api, 'Routing'));
setReady(true);
}} />
</div>
</section>
);
}
vue<!-- src/EdgeEditor.vue — render <EdgeEditor /> from the existing App component. --> <script setup lang="ts"> import { ref, shallowRef } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import type { DiagramInstance } from '@grafloria/renderer'; import { addConnection, createScene, removeConnection, sceneNames, showScene } from './edge-scenes'; import type { SceneName } from './edge-scenes'; const initial = createScene('Routing'); const instance = shallowRef<DiagramInstance>(); const scene = ref<SceneName>('Routing'); const status = ref(''); function init(api: DiagramInstance) { instance.value = api; status.value = showScene(api, 'Routing'); } function choose(name: SceneName) { if (!instance.value) return; scene.value = name; status.value = showScene(instance.value, name); } async function changeLink(add: boolean) { if (!instance.value) return; try { if (add) await addConnection(instance.value); else await removeConnection(instance.value); } catch (error) { status.value = String(error); } } </script> <template> <section> <button v-for="name in sceneNames" :key="name" :disabled="!instance" @click="choose(name)">{{ name }}</button> <template v-if="scene === 'Routing'"> <button :disabled="!instance" @click="changeLink(true)">Add A → C</button> <button :disabled="!instance" @click="changeLink(false)">Remove A → B</button> </template> <p>{{ status }}</p> <div style="height:540px"> <GrafloriaFlow :default-nodes="initial.nodes" :default-edges="initial.edges" :renderer-config="{ highlightConnected: true }" @init="init" /> </div> </section> </template>
ts// src/app/edge-editor.ts — add EdgeEditor to the existing root's imports/template.
import { Component, signal } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { addConnection, createScene, removeConnection, sceneNames, showScene } from './edge-scenes';
import type { SceneName } from './edge-scenes';
@Component({
selector: 'app-edge-editor',
imports: [DiagramCanvasComponent],
template: `
@for (name of names; track name) {
<button [disabled]="!instance()" (click)="choose(name)">{{ name }}</button>
}
@if (scene() === 'Routing') {
<button [disabled]="!instance()" (click)="changeLink(true)">Add A → C</button>
<button [disabled]="!instance()" (click)="changeLink(false)">Remove A → B</button>
}
<p>{{ status() }}</p>
<grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
[rendererConfig]="{ highlightConnected: true }" (ready)="init($event)"
style="display:block;height:540px" />
`,
})
export class EdgeEditor {
private readonly initial = createScene('Routing');
readonly nodes = signal<NodeSpec[]>(this.initial.nodes);
readonly edges = signal<EdgeSpec[]>(this.initial.edges);
readonly names = sceneNames;
readonly scene = signal<SceneName>('Routing');
readonly status = signal('');
readonly instance = signal<GrafloriaCanvasInstance | null>(null);
init(api: GrafloriaCanvasInstance): void {
this.instance.set(api);
this.status.set(showScene(api, 'Routing'));
}
choose(name: SceneName): void {
const api = this.instance();
if (!api) return;
this.scene.set(name);
this.status.set(showScene(api, name));
}
async changeLink(add: boolean): Promise<void> {
const api = this.instance();
if (!api) return;
try {
if (add) await addConnection(api);
else await removeConnection(api);
} catch (error) { this.status.set(String(error)); console.error(error); }
}
}
tsx// src/routes/edges/index.tsx
import { $, component$, noSerialize, useSignal } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { DiagramInstance } from '@grafloria/renderer';
import { addConnection, createScene, removeConnection, sceneNames, showScene } from './edge-scenes';
import type { SceneName } from './edge-scenes';
export default component$(() => {
const initial = createScene('Routing');
const instance = useSignal<NoSerialize<DiagramInstance>>();
const scene = useSignal<SceneName>('Routing');
const status = useSignal('');
const ready = useSignal(false);
const choose = $((_event: MouseEvent, button: HTMLButtonElement) => {
const api = instance.value;
const name = sceneNames.find(candidate => candidate === button.value);
if (!api || !name) return;
scene.value = name;
status.value = showScene(api, name);
});
return (
<section>
{sceneNames.map(name => <button key={name} value={name} disabled={!ready.value}
onClick$={choose}>{name}</button>)}
{scene.value === 'Routing' && <>
<button disabled={!ready.value} onClick$={async () => {
const api = instance.value;
if (!api) return;
try { await addConnection(api); } catch (error) { status.value = String(error); console.error(error); }
}}>Add A → C</button>
<button disabled={!ready.value} onClick$={async () => {
const api = instance.value;
if (!api) return;
try { await removeConnection(api); } catch (error) { status.value = String(error); console.error(error); }
}}>Remove A → B</button>
</>}
<p>{status.value}</p>
<div style={{ height: '540px' }}>
<GrafloriaFlow defaultNodes={initial.nodes} defaultEdges={initial.edges}
rendererConfig={{ highlightConnected: true }} onInit$={api => {
instance.value = noSerialize(api);
status.value = showScene(api, 'Routing');
ready.value = true;
}} />
</div>
</section>
);
});
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
| Option | Type | Default | What it does |
|---|---|---|---|
type | direct / smooth / orthogonal / bezier | smooth | Derives routing and drawing when explicit settings are absent. |
router | Router name | Derived from type | Chooses the route geometry. |
connector | Connector name | Derived from router/type | Chooses the polyline's drawing. |
waypoints | Array of world-coordinate points | No supplied bends | Preserves interior route constraints. |
enableWaypointEditing | boolean | false | Enables interactive bend insertion and dragging. |
showWaypointHandles | boolean | true | Shows handles for waypoint editing. |
enableControlPointEditing | boolean | false | Enables Bézier control-point dragging. |
enableLinkReconnection | boolean | true | Enables dragging a selected link's endpoint to another port. |
highlightConnected | Boolean or options | false | Emphasizes 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. ChangingconnectorwithsetConnector()preserves routed points. - Use
waypointsfor 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.
Related
- Arrange ports and connect — define the attachment points that edges resolve.
- Label and distinguish edges — configure labels, parallel connections and crossings.
- Save and restore documents — retain routing settings and edited paths in the document format.
Was this page helpful?