Skip to content
D
Documentation

Compute connected data

how-to
5 min readUpdated

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:

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

For Angular:

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

For Qwik, keep the packages in the starter's devDependencies:

bash
npm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer

For React:

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

For Vue:

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

Computing flows

  1. Define the pipeline and its computation.

    The initial flow is 2 → ×3 → +10 → sink: the readout shows 6, 16 and 16. 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.ts in JavaScript, React, Vue and Qwik, or src/app/connected-data.ts in Angular to add numeric and branching graphs with NodeSpec and EdgeSpec, plus an evaluator and preview that follow current connections through DiagramModel; 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 mode as 'compute' for the first run.

ts
import 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.

  1. Mount the graph through your binding.

    The JavaScript tab uses Grafloria. The React, Vue and Qwik tabs use their own GrafloriaFlow component: React reference, Vue reference, Qwik reference. Angular uses DiagramCanvasComponent.

    Read the graph through the ready DiagramInstance; Angular supplies its GrafloriaCanvasInstance. 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(); });
}

The Angular sample initially displays the source number and the computed pipeline above the canvas.

Input is 2; the readout shows ×3=6, +10=16 and sink=16 above four connected nodes.

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.

  1. 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.

  1. In connected-data.ts, replace the mode declaration with:

    ts
    export 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.

  2. 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.

  3. 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.

OptionTypeDefaultWhat it does
NodeSpec.dataRecord<string, any>No payload specified by this interfaceHolds application input, such as the source number.
NodeSpec.portsPortSpec[]OptionalDeclares the endpoints that the flow connects.
PortSpec.dataTypestringUnsetGives a port a data-flow type for glyph colour and connection validity; it does not supply arithmetic.
EdgeSpec.sourceHandlestringOptionalPins the source to a named port, so each chatbot choice follows its own link.
EdgeSpec.targetHandlestringOptionalPins 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.

Was this page helpful?

Compute connected data — Grafloria