Skip to content
D
Documentation

Arrange ports and connect

how-to
10 min readUpdated

Use explicit ports when readers need to distinguish inputs and outputs, label individual connections, or connect without aiming at a small glyph. Specs describe the ports; the mounted diagram owns their live models, and the engine owns the gestures.

This example draws a labelled output and two inputs, plus three port arrangements. Its buttons switch between port dragging, body connections and proximity connections without replacing the diagram.

Start in the project left by the JavaScript, Angular, Qwik or Vue quick start. Keep the starter's entry wiring, configuration and stylesheet imports. These examples use the packages installed there; no additional package is required.

1. Arrange and label port glyphs

Put each PortSpec in a node's ports array. Give ports explicit IDs when several share a side. A group's configuration belongs in metadata.portGroups; each member names it with group. Members inherit side, layout, shape, style, label, visibility, gating, dataType, fromSpot, toSpot and spread, with their own declarations taking precedence. Set direction type on each member: it does not inherit from the group and defaults to bi when omitted.

The shared file uses NodeSpec for nodes and PortShapeSpec for glyphs. It draws:

  • A square output labelled SEND outside its node, a diamond input labelled RECEIVE inside its node, and a triangular input with an orthogonal label.
  • Four evenly spaced circle ports down a left edge (sideLinear).
  • Four custom-path ports along a diagonal node-local segment (line).
  • Six circle ports around an inscribed ellipse (ellipseSpread), with radial labels.

Start from the shipped LIGHT_THEME and override its port stroke and direction colours. The Theme keeps the rest of the shipped styling. Set portDefaultRadius for the SVG glyph's fallback radius; shape.size, when supplied, is the glyph's full width and height, not its radius.

Add this shared module at src/ports-demo.ts in JavaScript, Angular and Vue, or src/routes/ports-demo.ts in Qwik. It also contains the gesture configurations used by the mounted examples below. DiagramInstance gives it access to the mounted DiagramEngine.

ts
import {
  ConnectionLineStyle,
  InteractionMode,
  PortModel,
  PortVisibilityStrategy,
} from '@grafloria/engine';
import type { InteractionConfig, PortShapeSpec } from '@grafloria/engine';
import { LIGHT_THEME } from '@grafloria/renderer';
import type { DiagramInstance, NodeSpec, Theme } from '@grafloria/renderer';

export const theme: Theme = {
  ...LIGHT_THEME,
  colors: {
    ...LIGHT_THEME.colors,
    port: { input: '#2563eb', output: '#c2410c', bi: '#7c3aed' },
  },
  ports: {
    ...LIGHT_THEME.ports,
    size: 14,
    strokeWidth: 3,
  },
};

const pathGlyph: PortShapeSpec = {
  shape: 'path',
  size: 16,
  path: 'M0,-8 L8,0 L0,8 L-8,0 Z M0,-3 L3,0 L0,3 L-3,0 Z',
};

export const nodes: NodeSpec[] = [
  {
    id: 'source', label: 'Source',
    position: { x: 90, y: 80 }, size: { width: 160, height: 90 },
    ports: [{
      id: 'send', side: 'right', type: 'output',
      shape: { shape: 'square', size: 16 },
      label: { text: 'SEND', layout: 'outside' },
    }],
  },
  {
    id: 'target', label: 'Target',
    position: { x: 510, y: 80 }, size: { width: 180, height: 90 },
    ports: [{
      id: 'receive', side: 'left', type: 'input',
      shape: { shape: 'diamond', size: 16 },
      label: { text: 'RECEIVE', layout: 'inside' },
    }],
  },
  {
    id: 'other', label: 'Other target',
    position: { x: 510, y: 230 }, size: { width: 180, height: 90 },
    ports: [{
      id: 'other-in', side: 'left', type: 'input',
      shape: { shape: 'triangle', size: 16 },
      label: { text: 'IN', layout: 'orthogonal', angle: 160 },
    }],
  },
  {
    id: 'column', label: 'sideLinear',
    position: { x: 90, y: 380 }, size: { width: 150, height: 160 },
    metadata: { portGroups: {
      inputs: { id: 'inputs', side: 'left', type: 'input',
        layout: { strategy: 'sideLinear', args: { padding: 12 } } },
    } },
    ports: Array.from({ length: 4 }, (_, index) => ({
      id: `column-${index}`, group: 'inputs', type: 'input', index,
      shape: { shape: 'circle' },
      label: { text: `IN ${index + 1}`, layout: 'inside' },
    })),
  },
  {
    id: 'diagonal', label: 'line',
    position: { x: 350, y: 380 }, size: { width: 150, height: 160 },
    metadata: { portGroups: {
      diagonal: { id: 'diagonal', layout: { strategy: 'line',
        args: { start: { x: 0, y: 0 }, end: { x: 150, y: 160 } } } },
    } },
    ports: Array.from({ length: 4 }, (_, index) => ({
      id: `diagonal-${index}`, group: 'diagonal', index, shape: pathGlyph,
    })),
  },
  {
    id: 'ring', label: 'ellipseSpread',
    position: { x: 610, y: 380 }, size: { width: 160, height: 160 },
    metadata: { portGroups: {
      ring: { id: 'ring', layout: { strategy: 'ellipseSpread' } },
    } },
    ports: Array.from({ length: 6 }, (_, index) => ({
      id: `ring-${index}`, group: 'ring', index,
      shape: { shape: 'circle', size: 10 },
      label: { text: `${index + 1}`, layout: 'radial' },
    })),
  },
];

export const initialInteraction = {
  mode: InteractionMode.DIRECT,
  portVisibility: PortVisibilityStrategy.ALWAYS,
  portDefaultRadius: 7,
  connectionLineStyle: ConnectionLineStyle.STEP,
  highlightValidTargets: true,
  easyConnectModifier: 'shift',
  proximityConnectRadius: 80,
  enableHelperLines: true,
} satisfies Partial<InteractionConfig>;

export function initialize(instance: Pick<DiagramInstance, 'getModel' | 'getEngine'>): void {
  const node = instance.getModel().getNode('other');
  if (node) {
    node.removePort('other-in');
    node.addPort(new PortModel({
      id: 'other-live', type: 'input', side: 'left',
      shape: { shape: 'triangle', size: 16 },
      label: { text: 'IN', layout: 'orthogonal', angle: 160 },
    }));
  }
  configure(instance, 'ports');
}

export function configure(
  instance: Pick<DiagramInstance, 'getModel' | 'getEngine'>,
  gesture: 'ports' | 'body' | 'proximity',
): void {
  const interaction: Partial<InteractionConfig> = {
    ...initialInteraction,
    enableEasyConnect: gesture === 'body',
    enableProximityConnect: gesture === 'proximity',
  };
  instance.getEngine().setInteractionConfig(interaction);
}

export function inspect(instance: Pick<DiagramInstance, 'getModel' | 'getEngine'>): void {
  const engine = instance.getEngine();
  console.log('Interaction snapshot', engine.getInteractionConfig());
  console.log('Connection drag', engine.getConnectionStateManager().getState());
  console.log('Proximity proposal', engine.getProximityPreview());
  const source = instance.getModel().getNode('source');
  const port = source?.getPort('send');
  if (source && port) {
    console.log('Source port position', port.getAbsolutePosition(source.getBoundingBox()));
  }
}

getInteractionConfig() returns a frozen snapshot: read it, and change settings with setInteractionConfig(). The setter merges a partial configuration and emits config:interaction-changed. It does not replace your nodes or edges.

The inspection button prints a snapshot when you request it. getConnectionStateManager() exposes the live connection drag manager; getState() includes the current source, target and valid target ports. PortModel's getAbsolutePosition() takes the owning node's bounding box. For a position that includes the renderer's layout and shape anchoring, use SnapController's portPosition(node, port) instead.

initialize() replaces Other target's seeded input with a live port during setup. On the mounted NodeModel, removePort(id) returns the removed port or undefined; addPort(port) sets its owning node ID and rejects duplicate IDs. The replacement keeps the triangular IN glyph on screen. These direct model mutations construct data; for user-facing edits, use commands and history.

For port queries, getPortsByType(type) filters by exact direction type; getPortsBySide(side) returns matching ports sorted by index. getAvailablePorts(type?) returns ports that can accept more connections, including bidirectional ports when a type filter is supplied. getConnectedPorts() returns ports with at least one connection.

setPortRenderingConfig(config) stores the node's port rendering configuration and emits port-rendering:changed; getPortRenderingConfig() returns that configuration or undefined. getPortRenderingMode() resolves svg, html or auto, checking the node's portRenderingMode metadata before the stored configuration.

2. Mount the diagram and choose a gesture

Mount the same data in your binding. Each tab starts in port-drag mode and includes buttons for the next two tasks. Pass initialInteraction at mount in JavaScript, Qwik and Vue so the first paint includes the port glyphs and labels. No existing edge is needed: create one by dragging SEND toward RECEIVE.

ts
// src/main.ts — retain the starter's stylesheet import.
import './style.css';
import { render } from '@grafloria/element';
import { configure, initialInteraction, initialize, inspect, nodes, theme } from './ports-demo';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = `
  <button id="ports" type="button">Port drag</button>
  <button id="body" type="button">Shift + body connect</button>
  <button id="proximity" type="button">Proximity connect</button>
  <button id="inspect" type="button">Inspect now</button>
  <div id="canvas" style="height: 620px; width: 100%"></div>
`;
const instance = render({ nodes }, '#canvas', { theme, interaction: initialInteraction });
initialize(instance);
document.querySelector('#ports')?.addEventListener('click', () => configure(instance, 'ports'));
document.querySelector('#body')?.addEventListener('click', () => configure(instance, 'body'));
document.querySelector('#proximity')?.addEventListener('click', () => configure(instance, 'proximity'));
document.querySelector('#inspect')?.addEventListener('click', () => inspect(instance));

The canvas shows labelled square, diamond and triangular ports above a four-port column, diagonal custom-path glyphs and a six-port ring. Four gesture and inspection controls sit above the canvas.

These mounts add gesture-switching and inspection buttons; see Validate connections for JavaScript mounting and Angular instance and edge-state wiring. Keep the quick start's root component importing FlowComponent.

Qwik uses GrafloriaFlow and stores its browser-created instance with noSerialize(). Vue uses GrafloriaFlow and a shallowRef. In both bindings, defaultNodes seeds an uncontrolled diagram once. Keep the quick start's entry and route layout; only replace the diagram content shown here.

For Qwik, keep the shared module beside src/routes/index.tsx at src/routes/ports-demo.ts; the route imports it as ./ports-demo.

Compare the arrangements in the live Port groups & layouts, Port labels and Port shapes demos.

3. Reveal ports and use target magnets

  1. Click Port drag. The sample explicitly uses PortVisibilityStrategy.ALWAYS, so every glyph is visible before you hover.
  2. Press SEND and drag toward either input. Valid target ports highlight during the connection drag.
  3. Release near RECEIVE. The default snapToPortRadius is 30 pixels; the connection latches onto the nearest valid port within that radius. A release away from valid ports in this direct-mode configuration creates no link.

The sample uses ConnectionLineStyle.STEP: the preview follows an orthogonal step rather than the default Bézier curve. This config controls the drag preview, not the routing of every stored edge. See Route and edit edges for persistent edge geometry.

To hide glyphs until the pointer reaches a node, change initialInteraction.portVisibility to PortVisibilityStrategy.ON_HOVER. That is the engine's default. HIDDEN suppresses ordinary glyphs, but highlighted or valid-target ports still render. Port hit-testing remains active, so visibility does not disable connections. Use connection validation to control which connections are allowed.

The live Magnet & highlight demo includes an output that cannot accept another output, alongside two valid input targets.

4. Connect from node bodies

  1. Click Shift + body connect. configure(instance, 'body') enables enableEasyConnect and requires easyConnectModifier: 'shift'.
  2. Hold Shift, press the Source body rather than its port, drag to the Target body and release there. A connection joins their ports; the Source does not move during this gesture.
  3. Drag a body without Shift to move the node. Release a Shift-body connection over empty canvas away from valid ports to leave it unconnected.

The modifier preserves ordinary body dragging while reserving body connections for a deliberate gesture. With easyConnectModifier: 'none', every body press starts a connection while easy connect is enabled. The other supported values are alt, ctrl and meta, requiring Alt, Control and Meta respectively; ctrl and meta are separate choices, not a platform-adaptive pair.

The Angular button invokes createAddConnectionAction for the mounted Source node. The action emits connection:start-from-node; the sample handles that custom notification through the engine's event bus to enable Shift-body connections, and unsubscribes when the component is destroyed. Click the button, then perform the Shift-body gesture above; the button does not create an edge itself.

See Easy connect (body) for the built-in body gesture without a modifier. The Easy connect demo also illustrates whole-body handles; use the built-in enableEasyConnect configuration in your application rather than registering a tool for this task.

5. Connect by proximity

  1. Click Proximity connect. configure(instance, 'proximity') disables easy connect and enables enableProximityConnect with an 80-world-unit radius.
  2. Drag Source until SEND approaches RECEIVE. While a compatible port pair is within the radius, a dashed proposal wire appears.
  3. Drop the node there. The engine creates the proposed link through an undoable command and clears the proposal. A drop outside the radius adds no link.

enableHelperLines: true also snaps a single top-level node to sibling edge/centre alignment and equal spacing, drawing dashed guides while you drag. The guides end with the drag; they are not diagram edges.

getProximityPreview() returns the current proposal or null. setProximityPreview() accepts a proposal with source/target node and port IDs, or null to clear it. It changes overlay state, not the diagram, and emits no event. The built-in drag path manages it, so you do not call the setter to enable proximity connections.

Compare Proximity connect (live), which uses the engine's drag path, with Proximity connect, which demonstrates host-driven proposals. Use the built-in flag for a normal canvas.

Apply an application-owned snap and connection policy

Use SnapController directly when your application positions nodes and decides when to commit a nearby connection, rather than delegating that decision to a drag gesture. This JavaScript entry uses the shared theme from step 1 and keeps the quick start's stylesheet import. It aligns Target with Source, then draws one undoable link between their ports.

Start from DEFAULT_SNAP_CONFIG, increase snapThreshold to 8 world units and disable equalSpacing for edge/centre alignment only. These fields belong to SnapConfig; they configure this controller, not the canvas's built-in drag controller.

ts
import './style.css';
import { render } from '@grafloria/element';
import { DEFAULT_SNAP_CONFIG, SnapController } from '@grafloria/renderer';
import type { NodeSpec } from '@grafloria/renderer';
import { theme } from './ports-demo';

const nodes: NodeSpec[] = [
  {
    id: 'source', label: 'Source',
    position: { x: 60, y: 80 }, size: { width: 160, height: 90 },
    ports: [{ id: 'send', side: 'right', type: 'output' }],
  },
  {
    id: 'target', label: 'Target',
    position: { x: 250, y: 83 }, size: { width: 180, height: 90 },
    ports: [{ id: 'receive', side: 'left', type: 'input' }],
  },
];

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = '<div id="canvas" style="height: 400px; width: 100%"></div>';
const instance = render({ nodes }, '#canvas', { theme });
const engine = instance.getEngine();
const snap = new SnapController({
  ...DEFAULT_SNAP_CONFIG,
  snapThreshold: 8,
  equalSpacing: false,
});
const target = instance.getModel().getNode('target');
if (!target) throw new Error('Missing Target');
const aligned = snap.computeSnap(
  { x: target.position.x, y: target.position.y,
    width: target.size.width, height: target.size.height },
  snap.siblingBoxes(engine, ['target']),
);
target.setPosition(aligned.box.x, aligned.box.y);
const candidate = snap.findProximityConnection(engine, target.id);
if (candidate) {
  engine.commandManager.execute(snap.buildProximityLinkCommand(candidate));
}

computeSnap() returns a corrected box and guide data without moving a node; this setup applies the box to the mounted Target. findProximityConnection() returns the nearest compatible port pair within the controller's radius, or null. buildProximityLinkCommand() turns that pair into the command you execute on the mounted engine. The candidate search uses renderer-aware port positions; the command creates the stored link, not a preview overlay.

Options that matter

InteractionConfig separates gesture behaviour from the port's own presentation.

OptionTypeDefaultWhat it does
modeInteractionModeSMARTSelects the node-drag and connection mode.
dragThresholdnumber4Screen-pixel movement required to distinguish a click from a node drag.
portVisibilityPortVisibilityStrategyON_HOVERControls when glyphs appear.
portHoverScaleFactornumber1.5Enlarges a hovered fallback glyph by this factor.
portDefaultRadiusnumber6Fallback glyph radius; an explicit shape.size supplies its own size.
snapToPortRadiusnumber30Magnet radius for a connection or dragged link endpoint.
showConnectionPreviewbooleantrueDraws the connection drag preview.
connectionLineStyleConnectionLineStyleBEZIERChooses the preview line shape.
highlightValidTargetsbooleantrueHighlights valid connection targets during dragging.
enableSmartAutoConnectbooleantrueIn smart mode, resolves a body drop to a valid port.
enableEasyConnectbooleanfalseStarts a connection from a body press instead of moving the node.
easyConnectModifier'none' | 'shift' | 'alt' | 'ctrl' | 'meta''none'Gates easy-connect body presses behind the named key.
enableProximityConnectbooleanfalseProposes compatible port pairs while moving nodes and connects on drop.
proximityConnectRadiusnumber0World-unit radius; zero uses the shipped snap controller's fallback.
enableHelperLinesbooleanfalseSnaps and displays alignment/equal-spacing guides during a single top-level node drag.

Choose the interaction mode and preview

The sample chooses InteractionMode.DIRECT rather than the engine's smart default.

ChoiceBehaviour
InteractionMode.DIRECTA body drag moves the node; a port drag connects.
InteractionMode.DELIBERATESelect the node before dragging it to move.
InteractionMode.SMARTSupports smart nearest-port auto-connect; use portVisibility to control glyph visibility independently.
PortVisibilityStrategy.ALWAYSShows ports continuously.
PortVisibilityStrategy.ON_HOVERShows ports when hovering over the node.
PortVisibilityStrategy.HIDDENSuppresses ordinary glyphs; highlighted or valid-target ports still render, and port hit-testing remains active.
ConnectionLineStyle.STRAIGHTDraws a straight drag preview.
ConnectionLineStyle.BEZIERDraws a smooth Bézier drag preview.
ConnectionLineStyle.STEPDraws an orthogonal step preview.

Choose glyphs, labels and layouts

SettingValues and effect
shape.shapecircle, square, diamond, triangle, path. path uses your SVG path data centred on the anchor.
label.layoutinside pulls text into the body; outside pushes it away (default); orthogonal offsets along the edge; radial offsets on the ray from the node centre through the port.
layout.strategyshape uses the shape registry's anchor (default); absolute uses declared coordinates; line spaces ports along a segment; sideLinear spaces them along an edge; ellipse uses an ellipse angle; ellipseSpread fans them around an arc.
sidetop, right, bottom, left. Names the node edge.
typeinput, output, bi. Supplies direction identity for connection rules and theme colours.

label.offset defaults to a 6-pixel gap from the glyph edge. angle adds rotation; keepUpright defaults to true and flips text whose rotation would leave it upside down. The sample's 160° label therefore stays upright.

  • Use portDefaultRadius or shape.size to size SVG glyphs. The theme's ports.size is present in its configuration; the SVG glyph path reads the interaction radius and resolved shape size. ports.strokeWidth sets the ordinary outline, while highlighted ports use a 3-pixel outline. Set theme.colors.port.input, output and bi for SVG direction colours; ports.colors is also part of the theme configuration, but the SVG renderer reads colors.port.
  • Keep easy connect and proximity connect as distinct tasks. Easy connect starts a connection instead of a move; proximity connect needs a node move to propose a link. The sample switches the flags accordingly.
  • A port layout changes where glyphs are drawn. Use renderer-aware SnapController.portPosition() when you need coordinates for those arrangements, rather than assuming a bounding-box midpoint.
  • For group dragging and drop membership, see Nest containers and lanes. For keyboard nudging, see Navigate accessible canvases.
  • Endpoint reconnection and Bézier/waypoint handles belong to Route and edit edges; moving dots on previews belong to Animate flow.

The factory-level CreateDiagramOptions.connection configures a different target policy: snapToNode accepts a node's first valid input when the pointer is over its body or within snapRadius of its box (default radius 40 world pixels). It does not make a source body into a connection handle. For the body-to-body gesture shown here, use enableEasyConnect.

Was this page helpful?