Skip to content
D
Documentation

Validate connections

how-to
8 min readUpdated

Use connection validation when your editor needs typed wires, per-port capacity limits, or a directed graph that stays acyclic. Declare the ports in specs, let the engine enforce their anatomy and data types, and add a validator for your domain rules.

This page starts from the project in your JavaScript, React, Vue, Angular, or Qwik quick start. Keep its entry files, configuration, and stylesheet imports. The examples below add a shared module and a view; render that view from your existing app or route.

Connection validation

The sample draws A → B → C, with blue number ports, a purple string input, and a destination labelled Restricted. Number-to-string connections are refused by the declared types. C's input accepts at most two wires; the initial B → C wire occupies one slot. A custom rule refuses connections to Restricted with a reason.

  1. Use the packages installed by your quick start. If you add this to another project, install the matching binding and its Grafloria peers:

    JavaScript:

    bash
    npm install @grafloria/element @grafloria/renderer @grafloria/engine
    

    React:

    bash
    npm install @grafloria/react @grafloria/element @grafloria/renderer @grafloria/engine
    

    Vue:

    bash
    npm install @grafloria/vue @grafloria/element @grafloria/renderer @grafloria/engine
    

    Angular:

    bash
    npm install @grafloria/angular @grafloria/element @grafloria/renderer @grafloria/engine
    

    Qwik:

    bash
    npm install -D @grafloria/qwik @grafloria/element @grafloria/renderer @grafloria/engine
    
  2. Add the shared data and rules in src/connections.ts (Angular: src/app/connections.ts). NodeSpec holds each node's PortSpec; EdgeSpec pins the initial wires to their handles.

    Register data types through portTypeRegistry, the process-wide PortTypeRegistry. Its registerAll() gives the glyphs their colors. Equal type names are compatible even without compatibleWith; that list permits additional, directional conversions. An untyped port or '*' accepts either data type.

    registerConnectionValidator accepts the renderer's ConnectionValidator: one candidate containing both nodes, nullable ports, and an optional link during reconnection. Return true to allow, false to refuse without a message, or a reason string to refuse with a message. Every registered validator must pass.

    ts
    import { portTypeRegistry } from '@grafloria/engine';
    import type { DiagramModel } from '@grafloria/engine';
    import { registerConnectionValidator } from '@grafloria/renderer';
    import type {
      ConnectionValidator, DiagramInstance, EdgeSpec, NodeSpec,
    } from '@grafloria/renderer';
    
    export function registerDataTypes(): void {
      portTypeRegistry.registerAll([
        { name: 'number', color: '#2563eb' },
        { name: 'string', color: '#9333ea' },
      ]);
    }
    
    export const nodes: NodeSpec[] = [
      ...['a', 'b', 'c'].map((id, index): NodeSpec => ({
        id, label: id.toUpperCase(),
        position: { x: 60 + index * 220, y: 100 },
        size: { width: 140, height: 70 },
        ports: [
          { id: `${id}.in`, side: 'left', type: 'input', dataType: 'number',
            ...(id === 'c' ? { maxConnections: 2 } : {}) },
          { id: `${id}.out`, side: 'right', type: 'output', dataType: 'number' },
        ],
      })),
      { id: 'text', label: 'String input',
        position: { x: 500, y: 260 }, size: { width: 140, height: 70 },
        ports: [{ id: 'text.in', side: 'left', type: 'input', dataType: 'string' }] },
      { id: 'restricted', label: 'Restricted',
        position: { x: 280, y: 260 }, size: { width: 140, height: 70 },
        ports: [{ id: 'restricted.in', side: 'left', type: 'input', dataType: 'number' }] },
    ];
    
    export const edges: EdgeSpec[] = [
      { id: 'ab', source: 'a', target: 'b', sourceHandle: 'a.out', targetHandle: 'b.in' },
      { id: 'bc', source: 'b', target: 'c', sourceHandle: 'b.out', targetHandle: 'c.in' },
    ];
    
    export function reaches(
      model: DiagramModel, fromId: string, toId: string, excludedLinkId?: string,
    ): boolean {
      const seen = new Set<string>();
      const stack = [fromId];
      while (stack.length) {
        const current = stack.pop()!;
        if (current === toId) return true;
        if (seen.has(current)) continue;
        seen.add(current);
        for (const link of model.getLinks()) {
          if (link.id === excludedLinkId) continue;
          const source = model.getNodeByPortId(link.sourcePortId)?.id;
          const target = model.getNodeByPortId(link.targetPortId)?.id;
          if (source === current && target) stack.push(target);
        }
      }
      return false;
    }
    
    export function attachRules(
      instance: Pick<DiagramInstance, 'getModel' | 'getEngine'>,
      report: (message: string) => void,
    ): () => void {
      const model = instance.getModel();
      const engine = instance.getEngine();
      const restricted: ConnectionValidator = ({ sourceNode, targetNode }) => {
        if (model.getNode(sourceNode.id) !== sourceNode) return true;
        return targetNode.id === 'restricted' ? 'This destination is restricted.' : true;
      };
      const noCycles: ConnectionValidator = ({ sourceNode, targetNode, link }) => {
        if (model.getNode(sourceNode.id) !== sourceNode) return true;
        return reaches(model, targetNode.id, sourceNode.id, link?.id)
          ? 'This connection would create a cycle.' : true;
      };
      const removeRestricted = registerConnectionValidator(restricted);
      const removeCycles = registerConnectionValidator(noCycles);
      const names = [
        'connection:start', 'connection:update', 'connection:port-enter',
        'connection:port-leave', 'connection:complete', 'connection:cancel',
      ];
      const listeners = names.map(name => {
        const listener = (): void => {
          const reason = engine.getConnectionStateManager().getState().rejectionMessage;
          report(`${name}${reason ? `: ${reason}` : ''}`);
        };
        engine.on(name, listener);
        return () => engine.off(name, listener);
      });
      return () => {
        removeRestricted();
        removeCycles();
        listeners.forEach(remove => remove());
      };
    }
    

    The DiagramModel query uses the current links, not the original edge array. The identity check scopes each process-global validator to this model.

  3. Mount the view and keep the returned cleanup until unmount. DiagramInstance gives you the live model and engine. These views keep a bounded event log; they do not replace it with a timer or a click-only counter.

    Add attachRules() and the connection log to the mounted view; see Edit nodes for the framework mounting and state-binding patterns.

    ts
    // src/main.ts — retain the quick start's stylesheet imports.
    import { render } from '@grafloria/element';
    import { attachRules, edges, nodes, registerDataTypes } from './connections';
    import { connectForward } from './connect-forward';
    import { auditLinks } from './audit-links';
    
    const app = document.querySelector<HTMLElement>('#app')!;
    const close = document.createElement('button');
    close.textContent = 'Close diagram';
    const log = document.createElement('pre');
    log.textContent = 'Drag a port to begin.';
    const host = document.createElement('div');
    host.style.height = '420px';
    app.append(close, log, host);
    registerDataTypes();
    const instance = render({ nodes, edges }, host, {
      interaction: { portVisibility: 'always' },
    });
    const messages: string[] = [];
    const report = (message: string): void => {
      messages.push(message);
      log.textContent = messages.slice(-8).join('\n');
    };
    const removeRules = attachRules(instance, report);
    const removeConnect = instance.on('connect', ({ link }) => report(`connect: ${link.id}`));
    const forward = document.createElement('button');
    forward.textContent = 'Connect A to C';
    const audit = document.createElement('button');
    audit.textContent = 'Audit links';
    app.insertBefore(forward, host);
    app.insertBefore(audit, host);
    forward.addEventListener('click', () => {
      report(connectForward(instance) ? 'Forward connection accepted.' : 'Forward connection refused.');
    });
    audit.addEventListener('click', () => {
      report(JSON.stringify(auditLinks(instance), null, 2));
    });
    close.addEventListener('click', () => {
      removeConnect();
      removeRules();
      instance.dispose();
      host.remove();
      close.disabled = true;
      forward.disabled = true;
      audit.disabled = true;
    });
    

    Render the exported Qwik view from your existing route. Angular sets visibility with PortVisibilityStrategy: ALWAYS draws ports continuously, ON_HOVER reveals them on hover, and HIDDEN hides idle ports.

    The JavaScript view starts with the chain and three controls above the canvas.

    A → B → C above Restricted and String input, with Close diagram, Connect A to C, and Audit links controls.

    The React view starts with the drag prompt above the same typed graph.

    React's initial A → B → C chain, blue number ports, and purple String input port.

    The Vue view shows the same initial graph and prompt. The Angular view starts with the chain and both additional destinations.

  4. Press A's right port, drag to C's left port, and release. A → C fills C's remaining slot. A further wire to that input is refused. Try the String input and Restricted destinations: neither attempt creates a wire. The log records the refused drag and its reason during connection:update.

Compare the running Typed ports, Connection limit, and port validation demos. The interaction validation demo shows validation in the connection gesture.

Options that matter

OptionTypeDefaultWhat it does
PortSpec.type'input' | 'output' | 'bi''bi'Sets direction. Two inputs or two outputs cannot attach to one another; a bi port can pair with either.
PortSpec.dataTypestringUnsetGives the port a named data-flow type and registered color.
PortSpec.maxConnectionsnumberUnlimitedCaps the total wires attached to this port.
PortSpec.gating.fromMaxLinksnumber | nullUnlimitedCaps outgoing wires.
PortSpec.gating.toMaxLinksnumber | nullUnlimitedCaps incoming wires.
PortSpec.gating.isConnectableStart / isConnectableEndbooleantrueSeparately disables starting or receiving a wire.
PortSpec.gating.allowSelfLinkbooleanfalsePermits same-node links when both endpoints allow them.
PortSpec.gating.allowDuplicateLinksbooleantrueSet to false to refuse a second link between the same ports, including the reverse direction.
PortSpec.gating.allowedTypesstring[]No restrictionRestricts the data-type or system-type identities that may attach.
interaction.portVisibility'always' | 'on-hover' | 'never' | 'hidden''on-hover'always draws ports continuously; on-hover reveals them on node hover or as connection targets; never and hidden draw only highlighted or valid target ports.

For port positioning, glyphs, labels, groups, and attachment spots, use Arrange ports and connect.

For a node's connection-group identity, setConnectionGroup(group) stores the group string, tracks the change, and emits connection-group:changed; getConnectionGroup() returns that string, or undefined when no group is assigned. These are methods on the live node, not port-group layout settings.

Preventing cycles

  1. Keep the noCycles validator in attachRules() above. It follows directed links from the proposed target to the proposed source. If that path already exists, adding the new edge closes a loop.
  2. In any of the mounted views, drag C's right port to A's left port. The validator returns This connection would create a cycle. and the model retains A → B → C without a back edge.
  3. Try A → C instead while C has capacity. That forward edge is allowed. Moving the boxes does not change reachability.

This cycle guard applies to new-wire connection gestures. Endpoint reconnection checks endpoint identity, direction, and connection groups separately. See the Preventing cycles demo for a longer chain of new-wire attempts.

Connect from your own control

To exercise the same rendered instance from a button, use its InteractionController. Add this module and wire it into the JavaScript view below; do not create a separate controller or model.

ts
import type { DiagramInstance } from '@grafloria/renderer';

export function connectForward(instance: DiagramInstance): boolean {
  const model = instance.getModel();
  const source = model.getNode('a');
  const target = model.getNode('c');
  const sourcePort = source?.getPort('a.out');
  const targetPort = target?.getPort('c.in');
  if (!source || !target || !sourcePort || !targetPort) return false;
  const engine = instance.getEngine();
  const start = sourcePort.getAbsolutePosition(source.getBoundingBox());
  const end = targetPort.getAbsolutePosition(target.getBoundingBox());
  instance.interaction.startConnection(sourcePort, start.x, start.y, engine);
  instance.interaction.handleMouseMove(end.x, end.y, engine);
  instance.interaction.handleConnectionDrag(end.x, end.y, engine);
  return instance.interaction.completeConnection(engine);
}

The JavaScript view above imports this module and binds its Connect A to C button to connectForward(). Add the audit module below too before running that view.

completeConnection() returns a boolean for acceptance; the engine creates and routes the actual link asynchronously. Use the view's connect callback or subscription to react to the created LinkModel, rather than querying for it immediately after the call.

Connection events

  1. Keep the lifecycle listeners in the runnable attachRules() sample. These six events belong to the engine, so subscribe through getEngine().on() and remove each listener with off().
  2. Drag from A's output over an input, move away, and release on a valid input. The log records start, updates, target transitions, and completion.
  3. Begin another drag and press Escape, or release over empty canvas. The log records cancellation rather than completion; no wire is added.
EventWhat the reader gets
connection:startThe source port, start point, and valid target port IDs.
connection:updateThe current point and target, validity, rejection reason, and readable rejectionMessage.
connection:port-enterThe newly entered port and its validity and rejection information.
connection:port-leaveThe port the pointer left.
connection:completeThe accepted source and target ports and their IDs.
connection:cancelThe source of an abandoned or refused drag.

Completion and cancellation split the drag's end by outcome. The component's onConnect, @connect, or onConnect$ callback reports the created link; Angular's instance subscription serves the same purpose because the canvas has no corresponding output. The lower-level lifecycle listeners report the gesture before that link notification. Watch the Connection events demo to see the stream while dragging.

Drag validators decide whether to offer a connection. A ValidationEngine rule instead audits existing entities and returns a ValidationResult containing valid, errors, and warnings.

Use a separate TypeRegistry and validation engine when you need an additional audit policy without changing the canvas's editing policy. The following module audits links in the mounted model; its typed rule returns an error for a same-node edge.

ts
import { TypeRegistry, ValidationEngine } from '@grafloria/engine';
import type { LinkModel, ValidationResult, ValidationRule } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';

export function auditLinks(instance: DiagramInstance): ValidationResult[] {
  const registry = new TypeRegistry();
  const validator = new ValidationEngine(registry);
  const noSelfLoops: ValidationRule<LinkModel> = link => {
    const sameNode = instance.getModel().getNodeByPortId(link.sourcePortId)
      === instance.getModel().getNodeByPortId(link.targetPortId);
    return {
      valid: !sameNode,
      errors: sameNode ? [{
        path: `link.${link.id}`, message: 'A link must join different nodes.',
        code: 'SELF_LOOP', severity: 'error',
      }] : [],
      warnings: [],
    };
  };
  validator.addRule('link', noSelfLoops);
  const model = instance.getModel();
  return model.getLinks().map(link => validator.validateLink(link, model));
}

The JavaScript view's Audit links button prints each current link's audit result; it does not add or remove wires.

addRule() accepts diagram, node, port, and link as its entity categories. This audit uses link because it inspects endpoints. The engine's ConnectionValidator is a different type: it takes two PortModel arguments and returns a boolean or reason string, not a ValidationResult.

For built-in audits, use the canvas's DiagramEngine:

MethodScope and result
validateDiagram(options)Audits the loaded diagram and returns errors and warnings.
validate()Audits the diagram with default options; with no diagram, returns a valid empty result.
validateNode(nodeId, options)Audits one node.
validateLink(linkId, options)Audits one link against the loaded diagram.
validatePort(portId, nodeId, options)Audits a port in its owning node.
validateLayout(groupId, options)Audits a group's layout configuration.
registerNodeType(definition)Registers a node validation definition, not an HTML renderer.
registerPortType(definition)Registers a system port definition; use portTypeRegistry for data-flow colors and compatibility.
registerLinkType(definition)Registers a link validation definition.
registerGroupType(definition)Registers a group validation definition.
enableRealTimeValidation() / disableRealTimeValidation()Switches the validation engine's real-time flag.
isRealTimeValidationEnabled()Reads that flag.

Pitfalls

  • Connection validators are process-global. Keep each disposer and call it on unmount, as these samples do; otherwise the rule can remain after navigation or affect another canvas. clearConnectionValidators clears every registered rule: use it only when you intend a clean registry, not when closing one of several views.
  • isValidConnection evaluates registered host validators, not the built-in anatomy and data-type rules. With no registered host validators it returns { valid: true }. Use the real connection gesture to test the combined policy.
  • For a custom node's rendered content, use Customize rendering contracts, not the validation type registry. For host sizing, see Nest containers and lanes.

Check and clear host rules

Use this JavaScript entry in a single-canvas project, retaining the quick start's stylesheet imports. Check Restricted policy reports the host validator's refusal without creating a wire. Clear host rules removes the custom destination and cycle rules; the declared port rules still apply. Do not clear the registry when another canvas needs its validators.

ts
import './style.css';
import { render } from '@grafloria/element';
import { clearConnectionValidators, isValidConnection } from '@grafloria/renderer';
import { attachRules, edges, nodes, registerDataTypes } from './connections';

const app = document.querySelector<HTMLElement>('#app')!;
const check = document.createElement('button');
check.textContent = 'Check Restricted policy';
const clear = document.createElement('button');
clear.textContent = 'Clear host rules';
const close = document.createElement('button');
close.textContent = 'Close diagram';
const log = document.createElement('pre');
const host = document.createElement('div');
host.style.height = '420px';
app.append(check, clear, close, log, host);
registerDataTypes();
const instance = render({ nodes, edges }, host, {
  interaction: { portVisibility: 'always' },
});
const removeRules = attachRules(instance, message => { log.textContent = message; });
check.addEventListener('click', () => {
  const model = instance.getModel();
  const sourceNode = model.getNode('a');
  const targetNode = model.getNode('restricted');
  if (!sourceNode || !targetNode) return;
  const result = isValidConnection({
    sourceNode, targetNode,
    sourcePort: sourceNode.getPort('a.out') ?? null,
    targetPort: targetNode.getPort('restricted.in') ?? null,
  });
  log.textContent = result.valid ? 'Host rules allow this candidate.'
    : result.reason ?? 'Host rules refuse this candidate.';
});
clear.addEventListener('click', () => {
  clearConnectionValidators();
  log.textContent = 'Host rules cleared. Check the policy again.';
});
close.addEventListener('click', () => {
  removeRules();
  instance.dispose();
  host.remove();
  check.disabled = clear.disabled = close.disabled = true;
});

Was this page helpful?

Validate connections — Grafloria