Use the live graph to propagate numbers or run a branching chatbot preview. Grafloria owns the nodes, ports and links; your application supplies the arithmetic and the conversation rules.
Start in the project from your JavaScript, Angular, Qwik, React or Vue quick start. Keep its entry point, configuration and stylesheet wiring. The samples below add a shared browser module and a component; render that component in place of the quick start's flow component.
Those projects already install the packages used here. If you add this to another project, install @grafloria/engine and @grafloria/renderer together with your binding.
For JavaScript:
bashnpm install @grafloria/element @grafloria/engine @grafloria/renderer
For Angular:
bashnpm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer
For Qwik, keep the packages in the starter's devDependencies:
bashnpm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer
For React:
bashnpm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer
For Vue:
bashnpm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer
Computing flows
-
Define the pipeline and its computation.
The initial flow is
2 → ×3 → +10 → sink: the readout shows6,16and16. Type another number to recompute it. The evaluator resolves each input through the mounted graph, not through the initial edge array.Create
src/connected-data.tsin JavaScript, React, Vue and Qwik, orsrc/app/connected-data.tsin Angular to add numeric and branching graphs withNodeSpecandEdgeSpec, plus an evaluator and preview that follow current connections throughDiagramModel; see Nest containers and lanes for the shared specs-and-live-model setup.This file includes the chatbot data and preview used in the next section. Leave
modeas'compute'for the first run.
tsimport type { DiagramModel, NodeModel } from '@grafloria/engine';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
export const mode: 'compute' | 'chatbot' = 'compute';
export function makeNodes(kind: 'compute' | 'chatbot'): NodeSpec[] {
if (kind === 'chatbot') {
return [
{
id: 'welcome', label: 'What do you need?',
position: { x: 40, y: 120 }, size: { width: 200, height: 90 },
ports: [
{ id: 'welcome.sales', type: 'output', side: 'right', index: 0 },
{ id: 'welcome.support', type: 'output', side: 'right', index: 1 },
],
},
{
id: 'sales', label: 'Let’s talk about your order.',
position: { x: 340, y: 40 }, size: { width: 230, height: 90 },
ports: [{ id: 'sales.in', type: 'input', side: 'left' }],
},
{
id: 'support', label: 'How can we help?',
position: { x: 340, y: 220 }, size: { width: 230, height: 90 },
ports: [{ id: 'support.in', type: 'input', side: 'left' }],
},
];
}
return [
{
id: 'in', label: 'input', data: { value: 2 },
position: { x: 40, y: 120 }, size: { width: 120, height: 56 },
ports: [{ id: 'in.out', type: 'output', side: 'right', dataType: 'number' }],
},
{
id: 'mul', label: '× 3',
position: { x: 240, y: 120 }, size: { width: 120, height: 56 },
ports: [
{ id: 'mul.in', type: 'input', side: 'left', dataType: 'number' },
{ id: 'mul.out', type: 'output', side: 'right', dataType: 'number' },
],
},
{
id: 'add', label: '+ 10',
position: { x: 440, y: 120 }, size: { width: 120, height: 56 },
ports: [
{ id: 'add.in', type: 'input', side: 'left', dataType: 'number' },
{ id: 'add.out', type: 'output', side: 'right', dataType: 'number' },
],
},
{
id: 'out', label: 'sink',
position: { x: 640, y: 120 }, size: { width: 120, height: 56 },
ports: [{ id: 'out.in', type: 'input', side: 'left', dataType: 'number' }],
},
];
}
export function makeEdges(kind: 'compute' | 'chatbot'): EdgeSpec[] {
if (kind === 'chatbot') {
return [
{ id: 'sales-link', source: 'welcome', target: 'sales',
sourceHandle: 'welcome.sales', targetHandle: 'sales.in', label: 'Sales' },
{ id: 'support-link', source: 'welcome', target: 'support',
sourceHandle: 'welcome.support', targetHandle: 'support.in', label: 'Support' },
];
}
return [
{ id: 'l1', source: 'in', target: 'mul', sourceHandle: 'in.out', targetHandle: 'mul.in' },
{ id: 'l2', source: 'mul', target: 'add', sourceHandle: 'mul.out', targetHandle: 'add.in' },
{ id: 'l3', source: 'add', target: 'out', sourceHandle: 'add.out', targetHandle: 'out.in' },
];
}
function evaluate(model: DiagramModel, node: NodeModel, visiting: Set<string>): number {
if (visiting.has(node.id)) throw new Error('The numeric flow contains a cycle.');
visiting.add(node.id);
let value: number;
if (node.id === 'in') {
value = Number(node.data['value']);
} else {
const feeds = node.getIncomingLinks();
if (feeds.length !== 1) throw new Error(`${node.id} needs exactly one incoming link.`);
const sourceId = feeds[0]?.sourceNodeId;
const source = sourceId ? model.getNode(sourceId) : undefined;
if (!source) throw new Error(`${node.id} has no source node.`);
const input = evaluate(model, source, visiting);
value = node.id === 'mul' ? input * 3 : node.id === 'add' ? input + 10 : input;
}
visiting.delete(node.id);
node.setComputed('value', value);
return value;
}
export function attachReadout(
model: DiagramModel,
host: HTMLElement,
kind: 'compute' | 'chatbot',
): () => void {
host.replaceChildren();
const controls = document.createElement('div');
const result = document.createElement('p');
result.setAttribute('aria-live', 'polite');
host.append(controls, result);
let chosenPort = '';
const stops: Array<() => void> = [];
const report = () => {
if (kind === 'compute') {
try {
const sink = model.getNode('out');
if (!sink) throw new Error('The sink is missing.');
evaluate(model, sink, new Set<string>());
const value = (id: string) => Number(model.getNode(id)?.getComputed('value'));
result.textContent = `×3=${value('mul')} → +10=${value('add')} → sink=${value('out')}`;
} catch (error) {
result.textContent = error instanceof Error ? error.message : 'Cannot evaluate this flow.';
}
return;
}
const welcome = model.getNode('welcome');
const lines = [welcome?.getLabel() ?? 'The welcome step is missing.'];
if (chosenPort) {
const link = model.getLinks().find(edge => edge.sourcePortId === chosenPort);
const target = link ? model.getNodeByPortId(link.targetPortId) : undefined;
lines.push(target?.getLabel() ?? 'No connected reply.');
}
result.textContent = lines.join(' → ');
};
if (kind === 'compute') {
const label = document.createElement('label');
label.textContent = 'Input ';
const input = document.createElement('input');
input.type = 'number';
input.value = String(model.getNode('in')?.data['value'] ?? 2);
const changeInput = () => {
const value = Number(input.value);
model.getNode('in')?.setData('value', Number.isFinite(value) ? value : 0);
};
input.addEventListener('input', changeInput);
stops.push(() => input.removeEventListener('input', changeInput));
label.append(input);
controls.append(label);
} else {
for (const [title, port] of [['Sales', 'welcome.sales'], ['Support', 'welcome.support']]) {
const button = document.createElement('button');
button.type = 'button';
button.textContent = title ?? '';
const choose = () => { chosenPort = port ?? ''; report(); };
button.addEventListener('click', choose);
stops.push(() => button.removeEventListener('click', choose));
controls.append(button);
}
}
for (const event of ['node:changed', 'node:added', 'node:removed',
'link:added', 'link:removed', 'link:changed']) {
stops.push(model.on(event, report));
}
report();
return () => {
stops.forEach(stop => stop());
host.replaceChildren();
};
}
NodeModel separates source data from derived results. setData() records a data change; setComputed() stores a result in the node's computed map, and getComputed() reads it. Computed writes do not emit a data change, so calculating a result does not recursively trigger the evaluator. The application updates its readout explicitly after computing.
The source input is an execution parameter, not a document inspector. For undoable document edits from your own panels, use Edit nodes from your UI.
-
Mount the graph through your binding.
The JavaScript tab uses
Grafloria. The React, Vue and Qwik tabs use their ownGrafloriaFlowcomponent: React reference, Vue reference, Qwik reference. Angular usesDiagramCanvasComponent.Read the graph through the ready
DiagramInstance; Angular supplies itsGrafloriaCanvasInstance. The shared module owns only the contents of the empty readout element. The framework owns the canvas and its lifecycle.
ts/// <reference types="vite/client" />
// src/main.ts — retain the starter's stylesheet import.
import './style.css';
import { Grafloria } from '@grafloria/element';
import { attachReadout, makeEdges, makeNodes, mode } from './connected-data';
const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = '<div id="readout"></div><div id="canvas" style="height:400px"></div>';
const host = app.querySelector<HTMLDivElement>('#readout');
if (!host) throw new Error('Missing readout');
const instance = Grafloria.render(
{ nodes: makeNodes(mode), edges: makeEdges(mode) }, '#canvas',
{ interaction: { enableInPlaceTextEdit: true } },
);
const stop = attachReadout(instance.getModel(), host, mode);
if (import.meta.hot) {
import.meta.hot.dispose(() => { stop(); instance.dispose(); });
}
ts// src/app/connected-flow.component.ts
import { Component, ElementRef, signal, viewChild } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { attachReadout, makeEdges, makeNodes, mode } from './connected-data';
@Component({
selector: 'app-connected-flow',
imports: [DiagramCanvasComponent],
template: `
<div #readout></div>
<grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
(ready)="ready($event)" style="display:block;height:400px" />
`,
})
export class ConnectedFlowComponent implements OnDestroy {
readonly nodes = signal(makeNodes(mode));
readonly edges = signal(makeEdges(mode));
readonly readout = viewChild.required<ElementRef<HTMLDivElement>>('readout');
private stop: (() => void) | undefined;
ready(instance: GrafloriaCanvasInstance): void {
this.stop?.();
this.stop = attachReadout(instance.getModel(), this.readout().nativeElement, mode);
}
ngOnDestroy(): void { this.stop?.(); }
}
tsx// src/ConnectedFlow.tsx
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import { attachReadout, makeEdges, makeNodes, mode } from './connected-data';
export default component$(() => {
const host = useSignal<HTMLDivElement>();
const stop = useSignal<NoSerialize<() => void>>();
useVisibleTask$(({ cleanup }) => { cleanup(() => stop.value?.()); });
return <>
<div ref={host} />
<div style={{ height: '400px' }}>
<GrafloriaFlow defaultNodes={makeNodes(mode)} defaultEdges={makeEdges(mode)}
interaction={{ enableInPlaceTextEdit: true }}
onInit$={instance => {
if (!host.value) return;
stop.value?.();
stop.value = noSerialize(attachReadout(instance.getModel(), host.value, mode));
}} />
</div>
</>;
});
tsx// src/ConnectedFlow.tsx
import { useEffect, useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { attachReadout, makeEdges, makeNodes, mode } from './connected-data';
export default function ConnectedFlow() {
const host = useRef<HTMLDivElement>(null);
const stop = useRef<(() => void) | undefined>(undefined);
useEffect(() => () => stop.current?.(), []);
return <>
<div ref={host} />
<div style={{ height: 400 }}>
<GrafloriaFlow defaultNodes={makeNodes(mode)} defaultEdges={makeEdges(mode)}
interaction={{ enableInPlaceTextEdit: true }}
onInit={instance => {
if (!host.current) return;
stop.current?.();
stop.current = attachReadout(instance.getModel(), host.current, mode);
}} />
</div>
</>;
}
vue<!-- src/ConnectedFlow.vue --> <script setup lang="ts"> import { onBeforeUnmount, ref } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import type { DiagramInstance } from '@grafloria/renderer'; import { attachReadout, makeEdges, makeNodes, mode } from './connected-data'; const nodes = makeNodes(mode); const edges = makeEdges(mode); const host = ref<HTMLDivElement>(); let stop: (() => void) | undefined; function init(instance: DiagramInstance): void { if (!host.value) return; stop?.(); stop = attachReadout(instance.getModel(), host.value, mode); } onBeforeUnmount(() => stop?.()); </script> <template> <div ref="host"></div> <div style="height:400px"> <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" :interaction="{ enableInPlaceTextEdit: true }" @init="init" /> </div> </template>
The Angular sample initially displays the source number and the computed pipeline above the canvas.
React, Vue and Qwik seed an uncontrolled graph once with defaultNodes and defaultEdges. Angular returns model edits through its two-way node and edge signals. The readout subscribes directly to graph changes, including programmatic data writes and link additions, removals and endpoint changes. These subscriptions observe the model because the readout needs in-place data changes, not only a binding's committed node-array changes.
-
Run the application with the quick start's development command.
Change Input to
5: the readout shows×3=15 → +10=25 → sink=25. Moving a node does not change the arithmetic. If the pipeline loses an input link, the readout displays an error instead of presenting an old number as a current result. This evaluator requires one incoming link per transform and rejects cycles; it does not solve feedback loops or aggregate several inputs.
Compare the result with the live Computing flows demo. For the port-drag procedure, see Arrange ports and connect.
Build a branching chatbot preview
Use one output port per choice, rather than choosing a destination from a separate routing table. The preview follows the link attached to that port.
-
In
connected-data.ts, replace the mode declaration with:tsexport const mode: 'compute' | 'chatbot' = 'chatbot';Keep the rest of the shared module and your framework's mounting sample unchanged. Reload the application to seed the new graph.
-
The canvas now shows a welcome step with separate Sales and Support connections. Above it, the preview shows “What do you need?” and two choice buttons. Press Sales to see “Let’s talk about your order.”; press Support to see “How can we help?”.
The
attachReadout()sample resolves the chosen output's current link, then resolves its target port to a node. A missing connection produces “No connected reply.” This is a two-choice, one-reply preview, not a messaging-service integration. -
Double-click a reply node to edit its label. The JavaScript, React, Vue and Qwik samples enable
interaction.enableInPlaceTextEdit; Angular enables in-place editing by default. The preview reads the live label again when the model changes. Change a connection using the canvas's port gestures: the selected choice follows the new destination after the graph changes. See Arrange ports and connect for connection gestures and Edit nodes from your UI for label-editing controls.
The ManyChat-style chatbot builder demo expands this pattern into message cards with a port for each button, reply/no-reply branches and a Preview that follows those links. The sample here keeps that port-to-branch relationship without reproducing the builder's editor chrome.
Options that matter
Each PortSpec describes an endpoint. These optional fields select the data and endpoints used by the samples.
| Option | Type | Default | What it does |
|---|---|---|---|
NodeSpec.data | Record<string, any> | No payload specified by this interface | Holds application input, such as the source number. |
NodeSpec.ports | PortSpec[] | Optional | Declares the endpoints that the flow connects. |
PortSpec.dataType | string | Unset | Gives a port a data-flow type for glyph colour and connection validity; it does not supply arithmetic. |
EdgeSpec.sourceHandle | string | Optional | Pins the source to a named port, so each chatbot choice follows its own link. |
EdgeSpec.targetHandle | string | Optional | Pins the target to a named input port. |
The application's mode has two values: 'compute' seeds the numeric pipeline; 'chatbot' seeds the branching preview. It is not a Grafloria option.
Keep displayed content live
A plain JavaScript custom renderer runs once at mount. Update the DOM you own, as the readout does here, or use widget update/repaint handles when using widgets. Do not expect a data write to re-run the custom renderer.
Vue slots are not re-invoked for every in-place model mutation. Put live slot content in a component that reads its own reactive source, such as a map keyed by node ID. See Vue: state and slots and Customize rendering contracts for custom node bodies.
setComputed() only updates the computed map; the application controls how results appear. The examples display them outside the node bodies and need no redraw call.
Related
- Validate connections constrains which typed ports can connect.
- React: state and content covers controlled state, the node/edge state hooks and sibling consumers.
- Instance and lifecycle covers ready callbacks and subscription cleanup.
Was this page helpful?