Skip to content
D
Documentation

Lay out a diagram

how-to
8 min readUpdated

Use auto layout when you want the engine to arrange a graph instead of authoring every node position. Start with a component's layout prop; use the mounted instance's engine to arrange it again on demand. The samples below turn a stack of nodes into a hierarchy, a force-directed network or a grid, and compose an architecture diagram from zones and relationships.

Start in the project left by your JavaScript, React, Vue, Angular or Qwik quick start. Keep its entry files, configuration and stylesheet imports. Add the components below and render them from the existing app; in Qwik, add the new route shown below.

The quick starts already install the binding and its peers. If you are adding layout to another project, install the matching packages; your framework starter already supplies the framework itself.

JavaScript:

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

React:

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

Vue:

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

Angular:

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

Qwik:

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

Auto layout

  1. Add a small graph. Every node starts at (0, 0), so the arranged result comes from layout, not from saved coordinates. Use the library's NodeSpec and EdgeSpec types in every binding.

    Save this shared module as src/layout-data.ts (src/app/layout-data.ts in Angular).

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

export const nodes: NodeSpec[] = ['root', 'a', 'b', 'a1', 'a2', 'b1'].map(id => ({
  id,
  label: id,
  position: { x: 0, y: 0 },
  size: { width: 120, height: 48 },
}));

export const edges: EdgeSpec[] = [
  { source: 'root', target: 'a' },
  { source: 'root', target: 'b' },
  { source: 'a', target: 'a1' },
  { source: 'a', target: 'a2' },
  { source: 'b', target: 'b1' },
];

export const names = [
  'auto', 'dagre', 'elk', 'layered', 'tree', 'force',
  'grid', 'circular', 'radial', 'spectral', 'community',
];
  1. Share the imperative call. A DiagramInstance owns the rendered view; its DiagramEngine owns layout. layout() returns a promise of UnifiedLayoutResult, with nodePositions, bounds, algorithm and seed. For auto, inspect selection.chosen to see the selected algorithm.

    This helper changes direction and spacing through UnifiedLayoutOptions. It uses a chosen seed for reproducible force, spectral and community layouts. Save it beside the data module.

ts
import type { DiagramEngine, UnifiedLayoutOptions } from '@grafloria/engine';

export async function runLayout(engine: DiagramEngine, name: string): Promise<string> {
  const options: UnifiedLayoutOptions = name === 'grid'
    ? { columns: 3, nodeSpacing: 36 }
    : { direction: 'TB', nodeSpacing: 40, rankSpacing: 80, seed: 42 };
  const result = await engine.layout(name, options);
  const chosen = result.selection?.chosen ?? result.algorithm;
  return `${chosen}: ${result.nodePositions.size} nodes, seed ${result.seed}`;
}
  1. Mount the graph. The framework bindings run layout="auto" on mount. Their buttons call the same engine helper on the live diagram, without replacing its data. JavaScript mounts with render, then runs the helper explicitly.

    React uses GrafloriaFlow: render the exported LayoutExample from your existing app component. Vue uses GrafloriaFlow: import and render LayoutExample.vue. Angular uses DiagramCanvasComponent: add LayoutExampleComponent to the existing root component's imports and place <app-layout-example /> in its template. Qwik uses GrafloriaFlow in the new route. Keep the starter's bootstrapping and configuration intact.

ts
// src/main.ts — add to the existing entry module.
import { render } from '@grafloria/element';
import { nodes, edges, names } from './layout-data';
import { runLayout } from './run-layout';

const panel = document.createElement('section');
const bar = document.createElement('div');
const status = document.createElement('output');
const host = document.createElement('div');
host.style.height = '500px';
panel.append(bar, status, host);
document.body.append(panel);

const instance = render({ nodes, edges }, host);
async function run(name: string): Promise<void> {
  status.textContent = await runLayout(instance.getEngine(), name);
}
for (const name of names) {
  const button = document.createElement('button');
  button.textContent = name;
  button.onclick = () => { void run(name); };
  bar.append(button);
}
void run('auto');

The React sample opens with six separated nodes, their connecting edges and layout buttons.

The nodes appear separated rather than stacked. Choose dagre, elk, layered or tree for a top-to-bottom hierarchy; choose force for a network arrangement, or grid for three columns. The output reports the completed imperative run, not a continuously tracked layout state. See the live Auto layout and Layout portfolio comparisons.

React's onLayoutDone, Qwik's onLayoutDone$ and Angular's layoutDone also update the output when the bound auto layout completes. These callbacks report the declarative request; the buttons await the engine call separately.

Qwik keeps the browser instance with noSerialize(). Angular uses two-way arrays so moved positions return to its signals.

Choose a layout

These are the shipped registry names. Use them through layout or engine.layout(name); no registration step is needed.

NameUse it for
autoClassify the graph and select an algorithm; also the default for engine.layout()
architectureCompose zones, aligned boxes and labelled connections
elkLayered graphs with ports and nesting
dagreLayered flowcharts and pipelines
layeredThe built-in layered ranking algorithm
treeParent-centered hierarchies and org charts
forceForce-directed network placement
spectralSpectral network placement
communityNetworks arranged by detected communities
gridRows and columns of catalog items
circularNodes around a circle
radialA rooted graph arranged in rings

For more hierarchy examples, compare Dagre tree with ELK tree. For networks, inspect Force layout.

Set hierarchy direction and spacing

To arrange on mount with explicit options, replace layout="auto" with an object request. The object has name and options; it is not a LayoutConfiguration.

DirectionFlow
TBTop to bottom
BTBottom to top
LRLeft to right
RLRight to left

Use { name: 'dagre', options: { direction: 'LR', nodeSpacing: 40, rankSpacing: 80 } } as the React or Qwik layout prop, Vue's :layout value, or Angular's [layout] value. The shared runLayout() sample already demonstrates these option fields in a mounted diagram. direction translates to Dagre's rankdir and ELK's elk.direction, so you can switch engines without changing vocabulary.

OptionTypeDefaultWhat it does
direction'TB' | 'BT' | 'LR' | 'RL'Algorithm-specificSets the primary flow direction
nodeSpacingnumberAlgorithm-specificSets spacing within a rank or row
rankSpacingnumberAlgorithm-specificSets spacing between ranks or layers
seednumber0x5eedControls randomized algorithms reproducibly
columnsnumberMath.ceil(Math.sqrt(n))Chooses the grid's column count
removeOverlapsbooleantrueSeparates overlapping node boxes
componentSpacingnumbernodeSpacingSets the gap between disconnected components
nestedbooleantrue when groups existArranges group contents recursively and then their containers

An unknown registry name rejects the call with a list of registered names. Await the promise before reading the result. ELK loads lazily on its first use; you do not import its adapter to use layout('elk').

Architecture layout

Architecture layout is a composition, not a ranking. It puts regions on a grid, sizes boxes to their words, reserves room for captions and line labels, and bends connections in the gutters when they cannot run straight.

  1. Add the zones and relationships below. The sourceHandle: 'top' connection says that Wallets sits above API. A group's direction: 'LR' arranges its boxes in a row. A text node's near relation puts the note beside its subject. None of these is a coordinate.

    Save this shared module as src/architecture-data.ts (src/app/architecture-data.ts in Angular). GroupSpec types the zones.

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

export const nodes: NodeSpec[] = [
  { id: 'customer', label: 'Customer', sublabel: 'phone or browser' },
  { id: 'page', label: 'Payment page', sublabel: 'card entry' },
  { id: 'wallets', label: 'Wallets', sublabel: 'customer balance' },
  { id: 'api', label: 'API', sublabel: 'payment requests' },
  { id: 'db', label: 'Database', sublabel: 'keys and ledger' },
  { id: 'note', label: 'No card data here', shape: { type: 'text' },
    near: { target: 'db', side: 'right' } },
];
export const groups: GroupSpec[] = [
  { id: 'provider', label: 'PAYMENT PROVIDER', children: ['page', 'wallets'],
    direction: 'LR', style: { fill: '#e9f2f3', stroke: '#7aabb3' } },
  { id: 'ours', label: 'OUR SYSTEM', children: ['api', 'db'], direction: 'LR',
    labelPlacement: 'bottom-left', style: { fill: '#f3f4f6', stroke: '#d7dbe0' } },
];
export const edges: EdgeSpec[] = [
  { source: 'customer', target: 'page', label: 'enters card' },
  { source: 'page', target: 'wallets', label: 'adds money' },
  { source: 'api', target: 'wallets', sourceHandle: 'top', targetHandle: 'bottom',
    label: 'requests transfer' },
  { source: 'api', target: 'db', label: 'saves keys' },
  { source: 'api', target: 'customer', label: 'sends link' },
];
  1. Mount with layout: 'architecture'. JavaScript passes the renderer's mount option through render(); React, Vue and Qwik expose the same task as a component prop. In Angular, add GroupModel zones to the ready instance's model and run the engine's composition. Add and render this second component from your app, or add the Qwik route. Angular's ready callback receives a GrafloriaCanvasInstance.
ts
// src/main.ts — add to the existing entry module instead of the auto-layout example.
import { render } from '@grafloria/element';
import { nodes, edges, groups } from './architecture-data';

const host = document.createElement('div');
host.style.height = '600px';
document.body.append(host);
const instance = render({ nodes, edges, groups, layout: 'architecture' }, host);
console.log('Provider container layout', instance.getEngine().getLayout('provider'));
The React architecture sample places Payment provider above Our system, with Customer on the left and a note beside Database.

The payment-provider zone sits above your system; the customer sits to the left. The boxes align within the zones, and the note sits beside Database. To compose an existing diagram again, call instance.getEngine().layout('architecture').

The JavaScript sample logs the provider group's container configuration. getLayout(groupId) returns its type and optional config, or undefined when the group does not exist. It does not report the algorithm selected by layout('architecture'); these groups have container layout type 'none'. Use clearLayout(groupId) to remove a group's container configuration, setting its type to 'none' and clearing its config.

Compare the same structure through architecture and layered layout in the live Architecture layout demo. For the text equivalent, %%grafloria:layout architecture selects this composition in Mermaid; import diagram text covers loading it. Reverse flows use RL and BT; four or more sibling boxes with no connecting lines wrap into a reading-order grid.

Apply an animated adapter layout

Use engine.layout() for named algorithms. When integrating code that uses applyLayout(), attach the shipped LayoutService to the mounted engine first. This path takes adapter and adapter-specific options, rather than a registry name and unified options.

The complete browser entry below mounts the same graph and adds an animated Dagre action. Keep your existing entry module's other imports and setup. Clicking the button moves the live nodes into left-to-right ranks over 600 ms.

ts
import { render } from '@grafloria/element';
import { LayoutService } from '@grafloria/engine';
import { nodes, edges } from './layout-data';

const host = document.createElement('div');
host.style.height = '500px';
const button = document.createElement('button');
button.textContent = 'Arrange left to right';
document.body.append(button, host);

const instance = render({ nodes, edges }, host);
const engine = instance.getEngine();
engine.setLayoutService(new LayoutService());

button.onclick = async () => {
  button.disabled = true;
  try {
    await engine.applyLayout({
      adapter: 'dagre',
      options: { rankdir: 'LR', nodesep: 40, ranksep: 80 },
      animate: true,
      animationDuration: 600,
    });
  } finally {
    button.disabled = false;
  }
};

Import this entry module from your existing JavaScript entry to mount it. In a framework app, attach the service and make the same call using the instance acquired in the Auto layout step; do not create a second engine.

applyDagreLayout(options, canvasDimensions?) and applyELKLayout(options, canvasDimensions?) are convenience methods on this service-backed path. Both request animation and leave fitting off. Dagre accepts rankdir: 'TB' | 'BT' | 'LR' | 'RL'; ELK accepts algorithm: 'layered' | 'force' | 'stress' | 'mrtree' | 'radial' | 'disco' and 'elk.direction': 'RIGHT' | 'LEFT' | 'DOWN' | 'UP'. For new named-layout calls, use layout('dagre', options) or layout('elk', options).

Configure viewport-aware placement

LayoutConfiguration configures the model's placement algorithms, a different task from the engine's named graph layouts. Use it when configuring placement and re-layout together. Select the algorithm with setLayoutAlgorithm() before reLayout(); the latter uses the current algorithm.

This complete browser entry supplies the model viewport explicitly, then animates a left-to-right hierarchy within that viewport. Add it to your existing JavaScript entry by importing the module.

ts
import { render } from '@grafloria/element';
import type { LayoutConfiguration } from '@grafloria/engine';
import { nodes, edges } from './layout-data';

const host = document.createElement('div');
host.style.height = '500px';
const button = document.createElement('button');
button.textContent = 'Place in viewport';
document.body.append(button, host);
const instance = render({ nodes, edges }, host);

button.onclick = async () => {
  const model = instance.getModel();
  const config: LayoutConfiguration = {
    type: 'hierarchical',
    options: { nodeSpacing: 40, rankSpacing: 80 },
    viewport: { x: 0, y: 0, width: host.clientWidth, height: host.clientHeight },
    margins: 30,
    animate: true,
    animationDuration: 600,
    direction: 'LR',
  };
  const viewport = config.viewport;
  if (!viewport) return;
  model.setViewport(viewport.x, viewport.y, viewport.width, viewport.height);
  model.setLayoutAlgorithm('hierarchical', config);
  button.disabled = true;
  try {
    await model.reLayout(config);
  } finally {
    button.disabled = false;
  }
};

The hierarchy uses the configured node and rank spacing. direction in this configuration is a hierarchy shorthand, applied when the selected algorithm is 'hierarchical'.

type valuePlacement algorithm
gridGrid placement
force-directedForce-directed placement
hierarchicalHierarchy placement
hybridHybrid placement
OptionTypeDefaultWhat it does
type'grid' | 'force-directed' | 'hierarchical' | 'hybrid'Current algorithm during reLayout()Identifies a placement algorithm
optionsAlgorithm-specific optionsAlgorithm-specificConfigures columns, forces or hierarchy spacing
direction'TB' | 'BT' | 'LR' | 'RL'UnsetMerges direction into hierarchical options during re-layout
viewportRectangleModel viewport during reLayout()Gives viewport-aware algorithms their available rectangle
marginsnumber50 during reLayout()Reserves space around viewport-fitted content
animatebooleanNo animation unless requestedRequests animated placement changes
animationDurationnumberMust be supplied for model re-layout animationSets the animation's duration in milliseconds

reLayout() reads the viewport from the model, so set that viewport before calling it. Supply both animate and animationDuration for an animated model re-layout. It resolves with no return value; positions change on the mounted model.

Pitfalls

  • Changing node data does not re-run a declarative layout. The binding reacts to changes in the layout's own value, so it does not fight user drags. Request layout through instance.getEngine().layout(...); in Angular, call the canvas's applyLayout() to re-run its bound request.
  • DiagramInstance has no undo() or redo() methods. Call instance.getEngine().undo() or instance.getEngine().redo(); Angular also mirrors those methods on the canvas. See commands and history for undoable edits and controls that follow history state.
  • For host sizing, see nest containers. For preserving an existing arrangement after insertion, use incremental layout instead of a full graph re-layout.

Was this page helpful?