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.
-
Use the packages installed by your quick start. If you add this to another project, install the matching binding and its Grafloria peers:
JavaScript:
bashnpm install @grafloria/element @grafloria/renderer @grafloria/engineReact:
bashnpm install @grafloria/react @grafloria/element @grafloria/renderer @grafloria/engineVue:
bashnpm install @grafloria/vue @grafloria/element @grafloria/renderer @grafloria/engineAngular:
bashnpm install @grafloria/angular @grafloria/element @grafloria/renderer @grafloria/engineQwik:
bashnpm install -D @grafloria/qwik @grafloria/element @grafloria/renderer @grafloria/engine -
Add the shared data and rules in
src/connections.ts(Angular:src/app/connections.ts).NodeSpecholds each node'sPortSpec;EdgeSpecpins the initial wires to their handles.Register data types through
portTypeRegistry, the process-widePortTypeRegistry. ItsregisterAll()gives the glyphs their colors. Equal type names are compatible even withoutcompatibleWith; that list permits additional, directional conversions. An untyped port or'*'accepts either data type.registerConnectionValidatoraccepts the renderer'sConnectionValidator: one candidate containing both nodes, nullable ports, and an optionallinkduring reconnection. Returntrueto allow,falseto refuse without a message, or a reason string to refuse with a message. Every registered validator must pass.tsimport { 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
DiagramModelquery uses the current links, not the original edge array. The identity check scopes each process-global validator to this model. -
Mount the view and keep the returned cleanup until unmount.
DiagramInstancegives 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; });tsx// src/ConnectionView.tsx import { useEffect, useRef, useState } from 'react'; import { GrafloriaFlow } from '@grafloria/react'; import type { DiagramInstance } from '@grafloria/renderer'; import { attachRules, edges, nodes, registerDataTypes } from './connections'; export default function ConnectionView() { const [ready, setReady] = useState(false); const [messages, setMessages] = useState<string[]>([]); const cleanup = useRef<(() => void) | null>(null); const report = (message: string): void => { setMessages(previous => [...previous, message].slice(-8)); }; useEffect(() => { registerDataTypes(); setReady(true); return () => { cleanup.current?.(); cleanup.current = null; }; }, []); const onInit = (instance: DiagramInstance): void => { cleanup.current?.(); cleanup.current = attachRules(instance, report); }; return <section> <pre>{messages.join('\n') || 'Drag a port to begin.'}</pre> <div style={{ height: 420 }}> {ready && <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} interaction={{ portVisibility: 'always' }} onInit={onInit} onConnect={({ link }) => report(`connect: ${link.id}`)} />} </div> </section>; }vue<!-- src/ConnectionView.vue --> <script setup lang="ts"> import { onBeforeUnmount, ref } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import type { LinkModel } from '@grafloria/engine'; import type { DiagramInstance } from '@grafloria/renderer'; import { attachRules, edges, nodes, registerDataTypes } from './connections'; registerDataTypes(); const messages = ref<string[]>([]); let cleanup: (() => void) | undefined; function report(message: string): void { messages.value = [...messages.value, message].slice(-8); } function onInit(instance: DiagramInstance): void { cleanup?.(); cleanup = attachRules(instance, report); } function onConnect(event: { link: LinkModel }): void { report(`connect: ${event.link.id}`); } onBeforeUnmount(() => cleanup?.()); </script> <template> <section> <pre>{{ messages.join('\n') || 'Drag a port to begin.' }}</pre> <div style="height:420px"> <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" :interaction="{ portVisibility: 'always' }" @init="onInit" @connect="onConnect" /> </div> </section> </template>ts// src/app/connection-view.component.ts import { Component, DestroyRef, inject, signal } from '@angular/core'; import { DiagramCanvasComponent } from '@grafloria/angular'; import type { GrafloriaCanvasInstance } from '@grafloria/angular'; import { PortVisibilityStrategy } from '@grafloria/engine'; import type { EdgeSpec, NodeSpec } from '@grafloria/renderer'; import { attachRules, edges, nodes, registerDataTypes } from './connections'; @Component({ selector: 'app-connection-view', imports: [DiagramCanvasComponent], template: ` <pre>{{ messages().join('\n') || 'Drag a port to begin.' }}</pre> <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges" (ready)="onReady($event)" style="display:block;height:420px" /> `, }) export class ConnectionViewComponent { readonly nodes = signal<NodeSpec[]>(nodes); readonly edges = signal<EdgeSpec[]>(edges); readonly messages = signal<string[]>([]); private cleanup: (() => void) | undefined; private removeConnect: (() => void) | undefined; constructor() { registerDataTypes(); inject(DestroyRef).onDestroy(() => { this.removeConnect?.(); this.cleanup?.(); }); } onReady(instance: GrafloriaCanvasInstance): void { instance.getEngine().setInteractionConfig({ portVisibility: PortVisibilityStrategy.ALWAYS }); this.removeConnect?.(); this.cleanup?.(); this.cleanup = attachRules(instance, message => this.report(message)); this.removeConnect = instance.on('connect', ({ link }) => this.report(`connect: ${link.id}`)); } private report(message: string): void { this.messages.update(previous => [...previous, message].slice(-8)); } }tsx// src/ConnectionView.qwik.tsx import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik'; import type { NoSerialize } from '@builder.io/qwik'; import { GrafloriaFlow } from '@grafloria/qwik'; import { attachRules, edges, nodes, registerDataTypes } from './connections'; export default component$(() => { const ready = useSignal(false); const messages = useSignal<string[]>([]); const removeRules = useSignal<NoSerialize<() => void>>(); useVisibleTask$(({ cleanup }) => { registerDataTypes(); ready.value = true; cleanup(() => removeRules.value?.()); }); return <section> <pre>{messages.value.join('\n') || 'Drag a port to begin.'}</pre> <div style={{ height: '420px' }}> {ready.value && <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} interaction={{ portVisibility: 'always' }} onInit$={instance => { removeRules.value?.(); removeRules.value = noSerialize(attachRules(instance, (message: string) => { messages.value = [...messages.value, message].slice(-8); })); }} onConnect$={({ link }) => { messages.value = [...messages.value, `connect: ${link.id}`].slice(-8); }} />} </div> </section>; });Render the exported Qwik view from your existing route. Angular sets visibility with
PortVisibilityStrategy:ALWAYSdraws ports continuously,ON_HOVERreveals them on hover, andHIDDENhides 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.
-
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
| Option | Type | Default | What 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.dataType | string | Unset | Gives the port a named data-flow type and registered color. |
PortSpec.maxConnections | number | Unlimited | Caps the total wires attached to this port. |
PortSpec.gating.fromMaxLinks | number | null | Unlimited | Caps outgoing wires. |
PortSpec.gating.toMaxLinks | number | null | Unlimited | Caps incoming wires. |
PortSpec.gating.isConnectableStart / isConnectableEnd | boolean | true | Separately disables starting or receiving a wire. |
PortSpec.gating.allowSelfLink | boolean | false | Permits same-node links when both endpoints allow them. |
PortSpec.gating.allowDuplicateLinks | boolean | true | Set to false to refuse a second link between the same ports, including the reverse direction. |
PortSpec.gating.allowedTypes | string[] | No restriction | Restricts 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
- Keep the
noCyclesvalidator inattachRules()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. - 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. - 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.
tsimport 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
- Keep the lifecycle listeners in the runnable
attachRules()sample. These six events belong to the engine, so subscribe throughgetEngine().on()and remove each listener withoff(). - 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.
- Begin another drag and press Escape, or release over empty canvas. The log records cancellation rather than completion; no wire is added.
| Event | What the reader gets |
|---|---|
connection:start | The source port, start point, and valid target port IDs. |
connection:update | The current point and target, validity, rejection reason, and readable rejectionMessage. |
connection:port-enter | The newly entered port and its validity and rejection information. |
connection:port-leave | The port the pointer left. |
connection:complete | The accepted source and target ports and their IDs. |
connection:cancel | The 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.
Validate existing links
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.
tsimport { 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:
| Method | Scope 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.
clearConnectionValidatorsclears every registered rule: use it only when you intend a clean registry, not when closing one of several views. isValidConnectionevaluates 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.
tsimport './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;
});
Related
- Arrange ports and connect — position and label the ports that expose these rules.
- Commands and history — make edits from your own UI undoable.
- Models and the document — query the live graph rather than stale spec arrays.
Was this page helpful?