# Arrange ports and connect

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start), [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start) or [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start) 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) for nodes and [`PortShapeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-ports#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-themes-constants#lighttheme) and override its port stroke and direction colours. The [`Theme`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-types-interfaces-s-v#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) gives it access to the mounted [`DiagramEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine#diagramengine).

```ts title="src/ports-demo.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-portmodel)'s `getAbsolutePosition()` takes the owning node's bounding box. For a position that includes the renderer's layout and shape anchoring, use [`SnapController`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-snapcontroller)'s `portPosition(node, port)` instead.

`initialize()` replaces Other target's seeded input with a live port during setup. On the mounted [`NodeModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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.

:::code-group
```ts title="JavaScript"
// 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));
```

```ts title="Angular"
// src/app/flow.component.ts
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { createAddConnectionAction, DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { configure, initialize, inspect, nodes, theme } from '../ports-demo';

@Component({
  selector: 'app-flow',
  imports: [DiagramCanvasComponent],
  template: `
    <button type="button" (click)="choose('ports')">Port drag</button>
    <button type="button" (click)="choose('body')">Shift + body connect</button>
    <button type="button" (click)="choose('proximity')">Proximity connect</button>
    <button type="button" (click)="inspectNow()">Inspect now</button>
    <grafloria-diagram-canvas
      [(nodes)]="nodes" [(edges)]="edges" [theme]="theme"
      (ready)="onReady($event)" style="display: block; height: 620px"
    />
  `,
})
export class FlowComponent {
  readonly nodes = signal<NodeSpec[]>(nodes);
  readonly edges = signal<EdgeSpec[]>([]);
  readonly theme = theme;
  readonly instance = signal<GrafloriaCanvasInstance | null>(null);
  private readonly destroyRef = inject(DestroyRef);

  onReady(instance: GrafloriaCanvasInstance): void {
    this.instance.set(instance);
    initialize(instance);
    const unsubscribe = instance.getEngine().eventBus.on('connection:start-from-node', () => {
      configure(instance, 'body');
    });
    this.destroyRef.onDestroy(unsubscribe);
  }

  choose(gesture: 'ports' | 'body' | 'proximity'): void {
    const instance = this.instance();
    if (!instance) return;
    if (gesture === 'body') {
      const source = instance.getModel().getNode('source');
      if (source) createAddConnectionAction(instance.getEngine()).onClick(source);
    } else {
      configure(instance, gesture);
    }
  }

  inspectNow(): void {
    const instance = this.instance();
    if (instance) inspect(instance);
  }
}
```

```tsx title="Qwik"
// src/routes/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 { configure, initialInteraction, initialize, inspect, nodes, theme } from './ports-demo';

export default component$(() => {
  const instance = useSignal<NoSerialize<DiagramInstance>>();
  return (
    <div>
      <button type="button" onClick$={() => {
        if (instance.value) configure(instance.value, 'ports');
      }}>Port drag</button>
      <button type="button" onClick$={() => {
        if (instance.value) configure(instance.value, 'body');
      }}>Shift + body connect</button>
      <button type="button" onClick$={() => {
        if (instance.value) configure(instance.value, 'proximity');
      }}>Proximity connect</button>
      <button type="button" onClick$={() => {
        if (instance.value) inspect(instance.value);
      }}>Inspect now</button>
      <div style={{ height: '620px' }}>
        <GrafloriaFlow defaultNodes={nodes} theme={theme} interaction={initialInteraction} onInit$={api => {
          instance.value = noSerialize(api);
          initialize(api);
        }} />
      </div>
    </div>
  );
});
```

```vue title="Vue"
<!-- src/App.vue -->
<script setup lang="ts">
import { shallowRef } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { configure, initialInteraction, initialize, inspect, nodes, theme } from './ports-demo';

const instance = shallowRef<DiagramInstance>();
function onInit(api: DiagramInstance): void {
  instance.value = api;
  initialize(api);
}
function choose(gesture: 'ports' | 'body' | 'proximity'): void {
  if (instance.value) configure(instance.value, gesture);
}
function inspectNow(): void {
  if (instance.value) inspect(instance.value);
}
</script>

<template>
  <button type="button" @click="choose('ports')">Port drag</button>
  <button type="button" @click="choose('body')">Shift + body connect</button>
  <button type="button" @click="choose('proximity')">Proximity connect</button>
  <button type="button" @click="inspectNow">Inspect now</button>
  <div style="height: 620px">
    <GrafloriaFlow :default-nodes="nodes" :theme="theme" :interaction="initialInteraction" @init="onInit" />
  </div>
</template>
```
:::

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/validate-connections) for JavaScript mounting and Angular instance and edge-state wiring. Keep the quick start's root component importing `FlowComponent`.

Qwik uses [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriaflow) and stores its browser-created instance with `noSerialize()`. Vue uses [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#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](https://grafloria.com/demos/ports/port-groups-and-layouts.html), [Port labels](https://grafloria.com/demos/ports/port-labels.html) and [Port shapes](https://grafloria.com/demos/ports/port-shapes.html) demos.

## 3. Reveal ports and use target magnets

1. Click Port drag. The sample explicitly uses [`PortVisibilityStrategy`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-config#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-config#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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/validate-connections) to control which connections are allowed.

The live [Magnet & highlight](https://grafloria.com/demos/ports/magnet-and-highlight.html) 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-functions#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)](https://grafloria.com/demos/interaction/easy-connect-body.html) for the built-in body gesture without a modifier. The [Easy connect](https://grafloria.com/demos/nodes/easy-connect.html) 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)](https://grafloria.com/demos/interaction/proximity-connect-live.html), which uses the engine's drag path, with [Proximity connect](https://grafloria.com/demos/nodes/proximity-connect.html), 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-constants#defaultsnapconfig), increase `snapThreshold` to 8 world units and disable `equalSpacing` for edge/centre alignment only. These fields belong to [`SnapConfig`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-interaction-interfaces-a-t#snapconfig); they configure this controller, not the canvas's built-in drag controller.

```ts title="src/main.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-config#interactionconfig) separates gesture behaviour from the port's own presentation.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `mode` | `InteractionMode` | `SMART` | Selects the node-drag and connection mode. |
| `dragThreshold` | `number` | `4` | Screen-pixel movement required to distinguish a click from a node drag. |
| `portVisibility` | `PortVisibilityStrategy` | `ON_HOVER` | Controls when glyphs appear. |
| `portHoverScaleFactor` | `number` | `1.5` | Enlarges a hovered fallback glyph by this factor. |
| `portDefaultRadius` | `number` | `6` | Fallback glyph radius; an explicit `shape.size` supplies its own size. |
| `snapToPortRadius` | `number` | `30` | Magnet radius for a connection or dragged link endpoint. |
| `showConnectionPreview` | `boolean` | `true` | Draws the connection drag preview. |
| `connectionLineStyle` | `ConnectionLineStyle` | `BEZIER` | Chooses the preview line shape. |
| `highlightValidTargets` | `boolean` | `true` | Highlights valid connection targets during dragging. |
| `enableSmartAutoConnect` | `boolean` | `true` | In smart mode, resolves a body drop to a valid port. |
| `enableEasyConnect` | `boolean` | `false` | Starts 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. |
| `enableProximityConnect` | `boolean` | `false` | Proposes compatible port pairs while moving nodes and connects on drop. |
| `proximityConnectRadius` | `number` | `0` | World-unit radius; zero uses the shipped snap controller's fallback. |
| `enableHelperLines` | `boolean` | `false` | Snaps and displays alignment/equal-spacing guides during a single top-level node drag. |

### Choose the interaction mode and preview

The sample chooses [`InteractionMode`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-config#interactionmode).`DIRECT` rather than the engine's smart default.

| Choice | Behaviour |
| --- | --- |
| `InteractionMode.DIRECT` | A body drag moves the node; a port drag connects. |
| `InteractionMode.DELIBERATE` | Select the node before dragging it to move. |
| `InteractionMode.SMART` | Supports smart nearest-port auto-connect; use `portVisibility` to control glyph visibility independently. |
| `PortVisibilityStrategy.ALWAYS` | Shows ports continuously. |
| `PortVisibilityStrategy.ON_HOVER` | Shows ports when hovering over the node. |
| `PortVisibilityStrategy.HIDDEN` | Suppresses ordinary glyphs; highlighted or valid-target ports still render, and port hit-testing remains active. |
| `ConnectionLineStyle.STRAIGHT` | Draws a straight drag preview. |
| `ConnectionLineStyle.BEZIER` | Draws a smooth Bézier drag preview. |
| `ConnectionLineStyle.STEP` | Draws an orthogonal step preview. |

### Choose glyphs, labels and layouts

| Setting | Values and effect |
| --- | --- |
| `shape.shape` | `circle`, `square`, `diamond`, `triangle`, `path`. `path` uses your SVG path data centred on the anchor. |
| `label.layout` | `inside` 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.strategy` | `shape` 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. |
| `side` | `top`, `right`, `bottom`, `left`. Names the node edge. |
| `type` | `input`, `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.

## Pitfalls and related tasks

- 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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers). For keyboard nudging, see [Navigate accessible canvases](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/navigate-large-diagrams).
- Endpoint reconnection and Bézier/waypoint handles belong to [Route and edit edges](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/route-and-edit-edges); moving dots on previews belong to [Animate flow](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/animate-flow).

The factory-level [`CreateDiagramOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-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`.
