# Lay out a diagram

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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start) or [Qwik quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec) and [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec) types in every binding.

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

```ts title="src/layout-data.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',
];
```

2. Share the imperative call. A [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) owns the rendered view; its [`DiagramEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine#diagramengine) owns layout. `layout()` returns a promise of [`UnifiedLayoutResult`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-interfaces-l-u#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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-unifiedlayoutoptions). It uses a chosen seed for reproducible force, spectral and community layouts. Save it beside the data module.

```ts title="src/run-layout.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}`;
}
```

3. 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render), then runs the helper explicitly.

   React uses [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriaflow): render the exported `LayoutExample` from your existing app component. Vue uses [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriaflow): import and render `LayoutExample.vue`. Angular uses [`DiagramCanvasComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-diagramcanvascomponent): add `LayoutExampleComponent` to the existing root component's `imports` and place `<app-layout-example />` in its template. Qwik uses [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriaflow) in the new route. Keep the starter's bootstrapping and configuration intact.

:::code-group
```ts title="JavaScript"
// 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');
```
```tsx title="React"
// src/LayoutExample.tsx
import { useRef, useState } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges, names } from './layout-data';
import { runLayout } from './run-layout';

export function LayoutExample() {
  const instance = useRef<DiagramInstance | null>(null);
  const [status, setStatus] = useState('Auto layout');
  const [ready, setReady] = useState(false);

  async function run(name: string): Promise<void> {
    if (instance.current) {
      setStatus(await runLayout(instance.current.getEngine(), name));
    }
  }

  return (
    <section>
      <div>{names.map(name => (
        <button key={name} disabled={!ready} onClick={() => { void run(name); }}>
          {name}
        </button>
      ))}</div>
      <output>{status}</output>
      <div style={{ height: 500 }}>
        <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} layout="auto"
          onLayoutDone={() => { setStatus('Bound auto layout completed'); }}
          onInit={value => { instance.current = value; setReady(true); }} />
      </div>
    </section>
  );
}
```
```vue title="Vue"
<!-- src/LayoutExample.vue -->
<script setup lang="ts">
import { shallowRef, ref } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { nodes, edges, names } from './layout-data';
import { runLayout } from './run-layout';

const instance = shallowRef<DiagramInstance | null>(null);
const status = ref('Auto layout');
function init(value: DiagramInstance): void { instance.value = value; }
async function run(name: string): Promise<void> {
  if (instance.value) status.value = await runLayout(instance.value.getEngine(), name);
}
</script>

<template>
  <section>
    <div>
      <button v-for="name in names" :key="name" :disabled="!instance" @click="run(name)">
        {{ name }}
      </button>
    </div>
    <output>{{ status }}</output>
    <div style="height: 500px">
      <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" layout="auto" @init="init" />
    </div>
  </section>
</template>
```
```ts title="Angular"
// src/app/layout-example.component.ts
import { Component, signal, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { nodes, edges, names } from './layout-data';
import { runLayout } from './run-layout';

@Component({
  selector: 'app-layout-example',
  imports: [DiagramCanvasComponent],
  template: `
    <div>
      @for (name of names; track name) {
        <button [disabled]="!ready()" (click)="run(name)">{{ name }}</button>
      }
      <button [disabled]="!ready()" (click)="repeat()">Re-run bound layout</button>
    </div>
    <output>{{ status() }}</output>
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      [layout]="'auto'" (ready)="ready.set(true)"
      (layoutDone)="status.set('Bound auto layout completed')"
      style="display: block; height: 500px" />
  `,
})
export class LayoutExampleComponent {
  readonly canvas = viewChild.required(DiagramCanvasComponent);
  readonly nodes = signal<NodeSpec[]>(nodes);
  readonly edges = signal<EdgeSpec[]>(edges);
  readonly names = names;
  readonly ready = signal(false);
  readonly status = signal('Auto layout');

  async run(name: string): Promise<void> {
    const engine = this.canvas().activeEngine();
    if (engine) this.status.set(await runLayout(engine, name));
  }

  async repeat(): Promise<void> {
    await this.canvas().applyLayout();
    this.status.set('Bound auto layout completed');
  }
}
```
```tsx title="Qwik"
// src/routes/layout/index.tsx
import { component$, noSerialize, useSignal } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { DiagramInstance, EdgeSpec, NodeSpec } from '@grafloria/renderer';
import type { DiagramEngine, UnifiedLayoutOptions } from '@grafloria/engine';

const nodes: NodeSpec[] = ['root', 'a', 'b', 'a1', 'a2', 'b1'].map(id => ({
  id, label: id, position: { x: 0, y: 0 }, size: { width: 120, height: 48 },
}));
const edges: EdgeSpec[] = [
  { source: 'root', target: 'a' },
  { source: 'root', target: 'b' },
  { source: 'a', target: 'a1' },
  { source: 'a', target: 'a2' },
  { source: 'b', target: 'b1' },
];
const names: string[] = [
  'auto', 'dagre', 'elk', 'layered', 'tree', 'force',
  'grid', 'circular', 'radial', 'spectral', 'community',
];
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}`;
}

export default component$(() => {
  const instance = useSignal<NoSerialize<DiagramInstance>>();
  const ready = useSignal(false);
  const status = useSignal('Auto layout');

  return (
    <section>
      <div>{names.map((name: string) => (
        <button key={name} disabled={!ready.value} onClick$={async () => {
          if (instance.value) {
            status.value = await runLayout(instance.value.getEngine(), name);
          }
        }}>{name}</button>
      ))}</div>
      <output>{status.value}</output>
      <div style={{ height: '500px' }}>
        <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} layout="auto"
          onLayoutDone$={() => { status.value = 'Bound auto layout completed'; }}
          onInit$={value => { instance.value = noSerialize(value); ready.value = true; }} />
      </div>
    </section>
  );
});
```
:::

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](https://grafloria.com/demos/layout/auto-layout.html) and [Layout portfolio](https://grafloria.com/demos/layout/layout-portfolio.html) 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.

| Name | Use it for |
| --- | --- |
| `auto` | Classify the graph and select an algorithm; also the default for `engine.layout()` |
| `architecture` | Compose zones, aligned boxes and labelled connections |
| `elk` | Layered graphs with ports and nesting |
| `dagre` | Layered flowcharts and pipelines |
| `layered` | The built-in layered ranking algorithm |
| `tree` | Parent-centered hierarchies and org charts |
| `force` | Force-directed network placement |
| `spectral` | Spectral network placement |
| `community` | Networks arranged by detected communities |
| `grid` | Rows and columns of catalog items |
| `circular` | Nodes around a circle |
| `radial` | A rooted graph arranged in rings |

For more hierarchy examples, compare [Dagre tree](https://grafloria.com/demos/layout/dagre-tree.html) with [ELK tree](https://grafloria.com/demos/layout/elk-tree.html). For networks, inspect [Force layout](https://grafloria.com/demos/layout/force-layout.html).

### 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`.

| Direction | Flow |
| --- | --- |
| `TB` | Top to bottom |
| `BT` | Bottom to top |
| `LR` | Left to right |
| `RL` | Right 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.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `direction` | `'TB' \| 'BT' \| 'LR' \| 'RL'` | Algorithm-specific | Sets the primary flow direction |
| `nodeSpacing` | `number` | Algorithm-specific | Sets spacing within a rank or row |
| `rankSpacing` | `number` | Algorithm-specific | Sets spacing between ranks or layers |
| `seed` | `number` | `0x5eed` | Controls randomized algorithms reproducibly |
| `columns` | `number` | `Math.ceil(Math.sqrt(n))` | Chooses the grid's column count |
| `removeOverlaps` | `boolean` | `true` | Separates overlapping node boxes |
| `componentSpacing` | `number` | `nodeSpacing` | Sets the gap between disconnected components |
| `nested` | `boolean` | `true` when groups exist | Arranges 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#groupspec) types the zones.

```ts title="src/architecture-data.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' },
];
```

2. 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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-types#grafloriacanvasinstance).

:::code-group
```ts title="JavaScript"
// 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'));
```
```tsx title="React"
// src/ArchitectureExample.tsx
import { GrafloriaFlow } from '@grafloria/react';
import { nodes, edges, groups } from './architecture-data';

export function ArchitectureExample() {
  return (
    <div style={{ height: 600 }}>
      <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
        defaultGroups={groups} layout="architecture" />
    </div>
  );
}
```
```vue title="Vue"
<!-- src/ArchitectureExample.vue -->
<script setup lang="ts">
import { GrafloriaFlow } from '@grafloria/vue';
import { nodes, edges, groups } from './architecture-data';
</script>

<template>
  <div style="height: 600px">
    <GrafloriaFlow :default-nodes="nodes" :default-edges="edges"
      :default-groups="groups" layout="architecture" />
  </div>
</template>
```
```ts title="Angular"
// src/app/architecture-example.component.ts
import { Component, signal } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { GroupModel } from '@grafloria/engine';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { nodes, edges, groups } from './architecture-data';

@Component({
  selector: 'app-architecture-example',
  imports: [DiagramCanvasComponent],
  template: `
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      (ready)="compose($event)"
      style="display: block; height: 600px" />
  `,
})
export class ArchitectureExampleComponent {
  readonly nodes = signal<NodeSpec[]>(nodes);
  readonly edges = signal<EdgeSpec[]>(edges);
  async compose(instance: GrafloriaCanvasInstance): Promise<void> {
    const model = instance.getModel();
    for (const spec of groups) {
      const group = new GroupModel({ id: spec.id, name: spec.label ?? '' });
      group.setMetadata('direction', spec.direction);
      group.setMetadata('frameStyle', {
        ...spec.style, labelPlacement: spec.labelPlacement ?? 'top-left',
      });
      model.addGroup(group);
      for (const id of spec.children ?? []) group.addMember(id, model);
    }
    await instance.getEngine().layout('architecture');
  }
}
```
```tsx title="Qwik"
// src/routes/architecture/index.tsx
import { component$ } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { EdgeSpec, GroupSpec, NodeSpec } from '@grafloria/renderer';

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' } },
];
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' } },
];
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' },
];

export default component$(() => (
  <div style={{ height: '600px' }}>
    <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
      defaultGroups={groups} layout="architecture" />
  </div>
));
```
:::

![The React architecture sample places Payment provider above Our system, with Customer on the left and a note beside Database.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/3e7f754580f30b58533479ccb88f4c70.png)

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](https://grafloria.com/demos/diagrams/architecture-layout.html). For the text equivalent, `%%grafloria:layout architecture` selects this composition in Mermaid; [import diagram text](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-classes#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 title="src/adapter-example.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`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-interfaces-i-l#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 title="src/placement-example.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` value | Placement algorithm |
| --- | --- |
| `grid` | Grid placement |
| `force-directed` | Force-directed placement |
| `hierarchical` | Hierarchy placement |
| `hybrid` | Hybrid placement |

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `type` | `'grid' \| 'force-directed' \| 'hierarchical' \| 'hybrid'` | Current algorithm during `reLayout()` | Identifies a placement algorithm |
| `options` | Algorithm-specific options | Algorithm-specific | Configures columns, forces or hierarchy spacing |
| `direction` | `'TB' \| 'BT' \| 'LR' \| 'RL'` | Unset | Merges direction into hierarchical options during re-layout |
| `viewport` | Rectangle | Model viewport during `reLayout()` | Gives viewport-aware algorithms their available rectangle |
| `margins` | `number` | `50` during `reLayout()` | Reserves space around viewport-fitted content |
| `animate` | `boolean` | No animation unless requested | Requests animated placement changes |
| `animationDuration` | `number` | Must be supplied for model re-layout animation | Sets 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](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) for undoable edits and controls that follow history state.
- For host sizing, see [nest containers](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers). For preserving an existing arrangement after insertion, use [incremental layout](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/incremental-layout) instead of a full graph re-layout.

## Related

- [Group and collapse objects](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/group-and-collapse) — organize graph members into zones.
- [Import Mermaid and draw.io](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/import-diagram-text) — load text with type-aware layout.
- [Extend tools and execution](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/tools-layouts-and-transports) — register an additional algorithm when the shipped choices do not express your task.
