Skip to content
D
Documentation

Animate flow and execution

how-to
7 min readUpdated

Use animation to distinguish a wire carrying data from an inactive connection, and show which workflow steps run, finish or fail. The samples render animated strokes, dots travelling along the painted paths, and execution states on a mounted diagram.

Start in the project from your framework's quick start: JavaScript, React, Vue, Angular or Qwik. Keep its entry point, configuration and stylesheet imports. These examples add modules and a component; they do not bootstrap a second application. The quick starts already install the packages used here.

1. Animate edge strokes and glowing borders

Put animation in an EdgeSpec's style.animation. Use typed NodeSpec data for the boxes. This shared file draws Source → Fetch → Transform → Save with three animated connections. The gradient stroke and shadow follow the authors' Turbo flow demo: the gradient is SVG paint, the glow is a drop-shadow filter, and the node borders animate their SVG strokes.

Create the shared files in src/ in JavaScript, React, Vue and Qwik projects; in Angular, put them in src/app/.

ts
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = ['Source', 'Fetch', 'Transform', 'Save'].map(
  (label, index) => ({
    id: `n${index}`,
    label,
    position: { x: 40 + index * 210, y: 140 },
    size: { width: 150, height: 70 },
    style: {
      fill: '#111528', stroke: '#2a8af6', strokeWidth: 2,
      animatedBorder: true, borderAnimationType: 'gradient',
      shadow: { offsetX: 0, offsetY: 0, blur: 6, color: '#a853ba' },
    },
  }),
);

export const edges: EdgeSpec[] = [
  { id: 'e0', source: 'n0', target: 'n1', style: { animation: { type: 'marching-ants' } } },
  { id: 'e1', source: 'n1', target: 'n2', style: { animation: { type: 'flow' } } },
  {
    id: 'e2', source: 'n2', target: 'n3',
    style: {
      strokeWidth: 3,
      stroke: {
        type: 'linear', x1: 0, y1: 0, x2: 1, y2: 0,
        stops: [
          { offset: 0, color: '#2a8af6' },
          { offset: 0.5, color: '#a853ba' },
          { offset: 1, color: '#e92a67' },
        ],
      },
      shadow: { offsetX: 0, offsetY: 0, blur: 6, color: '#a853ba' },
      animation: { type: 'dash-flow', speed: 'fast' },
    },
  },
];

The mounted examples below use DARK_THEME against a dark stage so labels contrast with the node fill. The Pulse wires button changes all three connections to the fourth stroke style, pulse.

2. Move tokens along the painted paths

A stroke animation changes the wire itself. A moving token is a separate shape. Follow the Animating edges demo: place an SVG sibling beside the renderer's SVG, copy the painted paths into hidden guides, and bind each dot to a guide with <animateMotion><mpath>.

Keep the rider SVG outside the renderer-owned subtree. Mirror its viewBox and observe path changes so tokens follow the same geometry after a node moves. The helper returns cleanup for unmount; it never adds foreign children to the renderer's SVG.

ts
let nextGuideId = 0;

export function mountRiders(host: HTMLElement): {
  setPaused(paused: boolean): void;
  destroy(): void;
} {
  const engineSvg = host.querySelector('path.diagram-link')?.closest('svg');
  if (!engineSvg) throw new Error('Mount riders after the diagram paints.');
  const ns = 'http://www.w3.org/2000/svg';
  const overlay = document.createElementNS(ns, 'svg');
  overlay.style.cssText =
    'position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible';
  engineSvg.parentElement!.appendChild(overlay);
  const guides = new Map<string, SVGPathElement>();

  for (const [index, id] of ['e0', 'e1', 'e2'].entries()) {
    const guide = document.createElementNS(ns, 'path');
    guide.id = `flow-rider-${++nextGuideId}`;
    guide.setAttribute('fill', 'none');
    guide.setAttribute('stroke', 'none');
    overlay.appendChild(guide);
    guides.set(id, guide);

    const dot = document.createElementNS(ns, 'circle');
    dot.setAttribute('r', '6');
    dot.setAttribute('fill', '#ec4899');
    dot.setAttribute('stroke', '#fff');
    const motion = document.createElementNS(ns, 'animateMotion');
    motion.setAttribute('dur', '2.4s');
    motion.setAttribute('begin', `-${0.6 + index * 0.6}s`);
    motion.setAttribute('repeatCount', 'indefinite');
    const path = document.createElementNS(ns, 'mpath');
    path.setAttribute('href', `#${guide.id}`);
    motion.appendChild(path);
    dot.appendChild(motion);
    overlay.appendChild(dot);
  }

  const sync = () => {
    const viewBox = engineSvg.getAttribute('viewBox') ?? '0 0 800 400';
    if (overlay.getAttribute('viewBox') !== viewBox) overlay.setAttribute('viewBox', viewBox);
    for (const [id, guide] of guides) {
      const painted = engineSvg.querySelector(`[data-link-id="${id}"] path.diagram-link`);
      const pathData = painted?.getAttribute('d') ?? '';
      if (guide.getAttribute('d') !== pathData) guide.setAttribute('d', pathData);
    }
  };
  sync();
  const observer = new MutationObserver(sync);
  observer.observe(engineSvg, {
    attributes: true, attributeFilter: ['d', 'viewBox'], subtree: true, childList: true,
  });
  return {
    setPaused(paused) {
      if (paused) overlay.pauseAnimations();
      else overlay.unpauseAnimations();
    },
    destroy() {
      observer.disconnect();
      overlay.remove();
    },
  };
}

Each token starts at a different phase along its wire. This is application-owned SVG motion, not an edge-particle API. The next helper explicitly pauses it when the animation policy suppresses motion.

3. Display running, completed and failed steps

The diagram owns live models; your runner owns execution order and outcomes. Use AnimationPresets for shipped state styling, then update the mounted nodes with setState() and setStyle() and the wires with updateStyle().

The shared controller below follows the Execute flow demo. Execute completes all four steps; Execute with failure stops at Transform and leaves Save pending. Execute with warning marks Transform amber and continues. This is a simulated runner with a 900 ms step delay, not a workflow execution engine.

Use the mounted instance's AnimationService to control motion. Angular's ready instance does not expose animations; the helper creates an application-owned service there. Its policy affects the document body, not only one canvas. The checkbox follows onConfigChange(), including system preference changes.

The helper also shows CustomAnimationRegistry on an application-owned Live flow badge. Go below the instance only for this extra HTML animation; use shipped presets for the diagram's nodes and links.

ts
import { AnimationPresets, AnimationService, CustomAnimationRegistry } from '@grafloria/renderer';
import type { DiagramInstance } from '@grafloria/renderer';
import { mountRiders } from './riders';

export function attachFlowControls(
  instance: Pick<DiagramInstance, 'getModel' | 'batchUpdate'>,
  host: HTMLElement,
  suppliedAnimations?: AnimationService,
): () => void {
  const animations = suppliedAnimations ?? new AnimationService();
  const riders = mountRiders(host);
  const registry = new CustomAnimationRegistry();
  const bar = document.createElement('div');
  bar.style.cssText = 'display:flex;gap:8px;flex-wrap:wrap;padding:8px;color:#fff';
  host.prepend(bar);
  const badge = document.createElement('span');
  badge.textContent = 'Live flow';
  bar.append(badge);
  registry.register({
    name: 'live-flow-badge',
    keyframes: '0%,100% { opacity: 1; } 50% { opacity: .6; }',
    duration: '2s', iterationCount: 'infinite', targetType: 'both',
  });
  registry.applyToElement(badge, 'live-flow-badge');

  const reduced = document.createElement('input');
  reduced.type = 'checkbox';
  const label = document.createElement('label');
  label.append(reduced, ' Reduced motion');
  bar.append(label);
  reduced.onchange = () => animations.updateConfig({ reducedMotion: reduced.checked });
  const syncPolicy = () => {
    const config = animations.getConfig();
    reduced.checked = config.reducedMotion;
    const paused = !config.enabled || config.reducedMotion || config.batterySavingMode;
    riders.setPaused(paused);
    badge.style.animationPlayState = paused ? 'paused' : 'running';
  };
  const offPolicy = animations.onConfigChange(syncPolicy);
  syncPolicy();

  let alive = true;
  let running = false;
  const launchers: HTMLButtonElement[] = [];
  const button = (text: string, action: () => void) => {
    const element = document.createElement('button');
    element.type = 'button';
    element.textContent = text;
    element.onclick = action;
    bar.append(element);
    return element;
  };
  const showStep = (
    id: string,
    preset: typeof AnimationPresets.WORKFLOW[keyof typeof AnimationPresets.WORKFLOW],
  ) => {
    instance.batchUpdate(model => {
      const node = model.getNode(id);
      if (!node) return;
      node.setState({ status: preset.node.status, animateStatus: preset.node.animateStatus });
      const style = preset.node.style;
      node.setStyle({
        animatedBorder: style.animatedBorder,
        ...('borderAnimationType' in style
          ? { borderAnimationType: style.borderAnimationType } : {}),
        ...('borderAnimationSpeed' in style
          ? { borderAnimationSpeed: style.borderAnimationSpeed } : {}),
        ...('borderAnimationColors' in style
          ? { borderAnimationColors: [...style.borderAnimationColors] } : {}),
      });
      for (const link of node.getIncomingLinks()) {
        link.updateStyle({ animation: preset.link });
      }
    });
  };
  const execute = async (outcome: 'completed' | 'error' | 'warning') => {
    if (running) return;
    running = true;
    launchers.forEach(element => { element.disabled = true; });
    instance.batchUpdate(model => {
      for (const node of model.getNodes()) {
        node.setState({ status: 'pending' });
        node.setStyle({ animatedBorder: false });
      }
      for (const link of model.getLinks()) link.updateStyle({ animation: { type: 'none' } });
    });
    try {
      for (const id of ['n0', 'n1', 'n2', 'n3']) {
        if (!alive) return;
        showStep(id, AnimationPresets.WORKFLOW.RUNNING);
        await new Promise<void>(resolve => setTimeout(resolve, 900));
        if (!alive) return;
        const preset = id === 'n2' && outcome === 'error'
          ? AnimationPresets.WORKFLOW.ERROR
          : id === 'n2' && outcome === 'warning'
            ? AnimationPresets.WORKFLOW.WARNING
            : AnimationPresets.WORKFLOW.COMPLETED;
        showStep(id, preset);
        if (id === 'n2' && outcome === 'error') return;
      }
    } finally {
      running = false;
      if (alive) launchers.forEach(element => { element.disabled = false; });
    }
  };
  launchers.push(
    button('Execute', () => { void execute('completed'); }),
    button('Execute with failure', () => { void execute('error'); }),
    button('Execute with warning', () => { void execute('warning'); }),
    button('Pulse wires', () => instance.batchUpdate(model => {
      for (const link of model.getLinks()) link.updateStyle({ animation: { type: 'pulse' } });
    })),
  );
  button('Disable motion', () => animations.setEnabled(false));
  button('Enable motion', () => animations.setEnabled(true));

  return () => {
    alive = false;
    offPolicy();
    riders.destroy();
    registry.destroy();
    bar.remove();
    if (!suppliedAnimations) animations.destroy();
  };
}

batchUpdate() groups changes into one scheduled paint. It is not a history transaction. Execution status here is document state, so it serializes and participates in collaboration; use the run overlay below for a viewer-local run.

Mount the same flow in your framework

Attach attachFlowControls() when your diagram initializes to connect the execution controls, SVG riders and motion policy; see Edit nodes from your UI for the shared mounting APIs and initialization events.

Add the component to the root already mounted by your quick start. For Qwik, put the component in src/AnimatedFlow.tsx, then import and render it in the new src/routes/animate/index.tsx route. Keep the starter's existing root wrapper and imports. The JavaScript tab shows additions to your existing entry file.

ts
// Add to your existing src/main.ts, keeping its stylesheet imports.
import { render } from '@grafloria/element';
import { DARK_THEME } from '@grafloria/renderer';
import { nodes, edges } from './flow-data';
import { attachFlowControls } from './flow-controls';

const host = document.createElement('div');
host.style.cssText = 'height:480px;position:relative;background:#0b1220';
document.body.appendChild(host);
const canvas = document.createElement('div');
canvas.style.height = '400px';
host.appendChild(canvas);
const instance = render({ nodes, edges }, canvas, { theme: DARK_THEME });
const cleanup = attachFlowControls(instance, host, instance.animations);
const close = document.createElement('button');
close.textContent = 'Close flow';
close.onclick = () => {
  cleanup();
  instance.dispose();
  host.remove();
  close.remove();
};
document.body.appendChild(close);

Initially you see four dark cards, animated borders, three animated wires and three pink riders. The toolbar offers the three execution outcomes, Pulse wires, motion switches and the Live flow badge. After Execute with failure, Source and Fetch are completed, Transform is red, and Save remains pending.

4. Keep a run out of the document

Use setOverlay() for execution telemetry that must not enter undo, serialization or collaboration. A RunOverlay maps node IDs to status frames and badges, and link IDs to label chips and optional moving dashes. Each call replaces the previous overlay; include all entries you want to keep.

This browser sample mounts a separate view. Show run draws a green completed Source, a blue running Fetch, a red failed Transform and a dashed pending Save. Inspect Fetch reads the last set overlay with getOverlay(); Clear run removes it with clearOverlay() without changing the diagram data.

Angular's canvas instance exposes model updates rather than the overlay methods; use its execution sample above for node status rendering. The following embedding uses render() and the full instance.

For Angular execution tooling, BreakpointManagerService manages node breakpoints and hit notifications, ExecutionTrackerService records workflow execution history, and SimulationEngineService provides a requestAnimationFrame loop with pause/resume support.

ts
import { render } from '@grafloria/element';
import { DARK_THEME } from '@grafloria/renderer';
import type { RunOverlay } from '@grafloria/renderer';
import { nodes, edges } from './flow-data';

function mountRunView(host: HTMLElement): () => void {
  host.style.background = '#0b1220';
  const canvas = document.createElement('div');
  canvas.style.height = '400px';
  const controls = document.createElement('div');
  const details = document.createElement('output');
  host.append(controls, canvas, details);
  const instance = render({
    nodes: nodes.map(node => ({ ...node, style: { ...node.style, animatedBorder: false } })),
    edges: edges.map(edge => ({ ...edge, style: { ...edge.style, animation: { type: 'none' } } })),
  }, canvas, { theme: DARK_THEME });
  const overlay: RunOverlay = {
    nodes: {
      n0: { status: 'completed', badge: '2 items' },
      n1: { status: 'running' },
      n2: { status: 'error', badge: 'failed' },
      n3: { status: 'pending' },
    },
    links: { e0: { label: '2 items', animate: true } },
  };
  const addButton = (text: string, action: () => void) => {
    const button = document.createElement('button');
    button.textContent = text;
    button.onclick = action;
    controls.appendChild(button);
  };
  addButton('Show run', () => instance.setOverlay(overlay));
  addButton('Inspect Fetch', () => {
    details.textContent = instance.getOverlay().nodes?.['n1']?.status ?? 'not run';
  });
  addButton('Clear run', () => {
    instance.clearOverlay();
    details.textContent = '';
  });
  instance.setOverlay(overlay);
  return () => {
    instance.dispose();
    controls.remove();
    canvas.remove();
    details.remove();
  };
}

const host = document.createElement('div');
document.body.appendChild(host);
const cleanup = mountRunView(host);
const close = document.createElement('button');
close.textContent = 'Close run view';
close.onclick = () => {
  cleanup();
  host.remove();
  close.remove();
};
document.body.appendChild(close);

Use these additions in your existing JavaScript entry instead of the JavaScript tab above. Close run view invokes cleanup when you remove the view. The overlay frames keep their static colors under reduced motion. Its moving dash follows the link's routed points; use the rider helper when a token must follow the exact painted curve.

Options and choices

LinkAnimation defines the per-wire choices:

OptionTypeDefaultWhat it does
style.animationLinkAnimationAbsent: no animationSelects a stroke animation.
style.animation.speed'slow' | 'normal' | 'fast''normal'Slow uses 3 s; fast uses 0.5 s; normal uses the type's base duration.
style.animation.direction'forward' | 'reverse'Forward CSS playbackReverse plays the keyframe backwards.
state.animateStatusbooleanOmitted: status motion allowedfalse retains the static status indication and suppresses its motion.
animatedBorderbooleanNo border animation unless enabledEnables the node's border animation.
Stroke typeEffect at normal speed
marching-antsMoves a 5/5 dash pattern; 1 s cycle.
flowMoves a 10/5 dash pattern; 2 s cycle.
pulseChanges opacity and stroke width; 2 s cycle.
dash-flowMoves an 8/12 dash pattern; 1.5 s cycle.
noneAdds no stroke animation class.

Node border choices are gradient, pulse, breathe, shimmer and none. Pure SVG nodes use the SVG variants; shimmer becomes breathe because SVG cannot paint its HTML pseudo-element effect.

StatusMeaning and rendered indication
idleNo status class; the run overlay hides the frame.
pendingWaiting; node status dims the node, overlay uses a dashed frame.
runningActive; blue indication with motion.
completedFinished; green indication.
errorFailed; red indication. Your runner decides whether to halt.
warningNon-fatal attention state; amber indication. Your runner decides whether to continue.

AnimationPresets.WORKFLOW provides RUNNING, PROCESSING, COMPLETED, ERROR, WARNING and PENDING. PROCESSING pairs a gradient border with fast dash flow; RUNNING pairs a pulsing border with flow. The other four use their named status and inactive links. The helper uses the preset's node state, style and link configuration together.

animateConnectionPreview adds a repeating dash animation to the temporary connection-preview line. It controls the preview while connecting, not the completed edge's style.animation.

applyWorkflowPreset mutates a live node and returns that same node. It does not apply the preset's link configuration. For mounted, observable updates, use the setter-based approach in showStep(); it also updates incoming wires.

debounce returns a wrapper that waits for a quiet interval before calling your function. throttle returns a wrapper that accepts the first call in an interval and drops subsequent calls during it, with no trailing call. Neither drives the renderer's animation loop. Do not throttle a final completion or failure update away.

Pitfalls

  • Reduced motion, disabled animation and battery-saving policy can suppress motion. Leave the static status information visible. The service detects the system motion preference and, where the Battery Status API is available, can engage saving below 20% while not charging.
  • Application-owned SVG riders and custom HTML animations need their own policy connection. syncPolicy() pauses both; CSS animation settings alone do not pause SMIL.
  • The animation policy toggles classes on document.body and persists selected settings. Coordinate it at application level if you mount multiple diagrams.
  • getOverlay() returns copied maps, not a deep clone of each entry. Replace entries rather than mutating an entry obtained from that result.
  • A fixed-height wrapper is part of the mount examples. For nested layouts, follow Nest containers and lanes.

Compare the Animating edges, Execute flow and Turbo flow demos with your mounted view. Continue with Build a workflow editor for execution telemetry beside editing, or Theme a diagram for reusable colors and style rules.

Was this page helpful?

Animate flow and execution — Grafloria