# Preserve layout while editing

Use incremental placement when you add a step to an edited diagram and want the existing nodes to stay recognizable. Place only the new node to preserve manual positions, or allow a small neighborhood to move to make room. Animate an explicit rearrangement when the reader needs to follow the change.

The diagram owns live models; the engine owns layout behavior. Read positions from the mounted instance, not from the specs that originally seeded it.

These examples start in the project left by your [JavaScript quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular quick start](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). The quick starts already install the packages imported here. Keep their entry files, configuration, wrappers and stylesheet imports.

## 1. Share the live-model operations

Add `src/layout-actions.ts` in each project. The initial picture is Start → Review → Finish, with explicit positions. [`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) type the seed data. [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) supplies the model, setters and [`DiagramEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine#diagramengine) through `getEngine()`.

The shared module defines operations; it does not mount a canvas. Each binding in the next step supplies its own mounted instance.

```ts title="src/layout-actions.ts"
import type { EdgeSpec, NodeSpec, DiagramInstance } from '@grafloria/renderer';
import type { IncrementalOptions, Point } from '@grafloria/engine';

export const nodes: NodeSpec[] = [
  { id: 'start', label: 'Start', position: { x: 60, y: 100 }, size: { width: 120, height: 50 } },
  { id: 'review', label: 'Review', position: { x: 280, y: 100 }, size: { width: 120, height: 50 } },
  { id: 'finish', label: 'Finish', position: { x: 500, y: 100 }, size: { width: 120, height: 50 } },
];
export const edges: EdgeSpec[] = [
  { id: 'start-review', source: 'start', target: 'review' },
  { id: 'review-finish', source: 'review', target: 'finish' },
];

type Canvas = Pick<DiagramInstance,
  'getModel' | 'getEngine' | 'setNodes' | 'setEdges' | 'batchUpdate'>;

export function createActions(
  api: Canvas,
  place: (id: string) => Promise<void>,
) {
  let disposed = false;
  let frame = 0;
  let nextId = 0;
  let operations = Promise.resolve();

  function enqueue(operation: () => Promise<void>): Promise<void> {
    operations = operations.then(async () => {
      if (!disposed) await operation();
    });
    return operations;
  }

  function addBranch(): string {
    const id = `added-${++nextId}`;
    const node: NodeSpec = {
      id, label: 'New step', position: { x: 0, y: 0 },
      size: { width: 120, height: 50 },
    };
    const edge: EdgeSpec = { id: `${id}-edge`, source: 'review', target: id };
    // Keep the current models, including positions changed by manual drags.
    api.setNodes([...api.getModel().getNodes(), node]);
    api.setEdges([...api.getModel().getLinks(), edge]);
    return id;
  }

  function placeNew(): Promise<void> {
    return enqueue(async () => { await place(addBranch()); });
  }

  function growRegion(): Promise<void> {
    return enqueue(async () => {
      const options: IncrementalOptions = {
        changed: [addBranch()], strategy: 'region', radius: 1,
        budget: { maxPerNode: 100, averagePerNode: 40 },
      };
      const result = await api.getEngine().layoutIncremental({
        ...options, direction: 'LR',
      });
      console.log('Existing-node movement', result.movement);
    });
  }

  function animateRow(): Promise<void> {
    return enqueue(() => new Promise<void>(resolve => {
    const model = api.getModel();
    const entries = model.getNodes().map((node, index) => ({
      id: node.id,
      start: { x: node.position.x, y: node.position.y },
      target: { x: 60 + index * 180, y: 240 } satisfies Point,
    }));
    const duration = matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 900;
    const started = performance.now();
    function tick(now: number): void {
      if (disposed) { resolve(); return; }
      const t = duration === 0 ? 1 : Math.min(1, (now - started) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      api.batchUpdate(diagram => {
        for (const entry of entries) {
          diagram.getNode(entry.id)?.setPosition(
            entry.start.x + (entry.target.x - entry.start.x) * eased,
            entry.start.y + (entry.target.y - entry.start.y) * eased,
          );
        }
      });
      if (t < 1) frame = requestAnimationFrame(tick);
      else resolve();
    }
    frame = requestAnimationFrame(tick);
    }));
  }

  return {
    placeNew, growRegion, animateRow,
    dispose(): void {
      disposed = true;
      cancelAnimationFrame(frame);
    },
  };
}
```

`addBranch()` reconciles new data into the live diagram; it does not record the insertion in history. The custom row animation also writes model positions directly. For user-facing additions and rearrangements that Undo must reverse, use [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history). The instance's `placeNodes()` and `tidy()` already commit their moves as one undo step.

## 2. Mount the canvas and place new nodes

In JavaScript, React, Vue and Qwik, call `placeNodes([id], { after: 'review', duration: 600 })` on the mounted instance. The named node lands one flow step after Review, clear of the other boxes; attachments follow their moving host even when their IDs are not supplied. [`PlaceNodesOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#placenodesoptions) adds `after` to [`FlowPlaceOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-interfaces#flowplaceoptions); `duration` changes the built-in tween from 280 ms to 600 ms.

Angular's [`GrafloriaCanvasInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-types#grafloriacanvasinstance) exposes the engine rather than the flow-placement methods. Use `layoutIncremental()` with `strategy: 'region'`, `radius: 0` and the new ID in `changed` to leave every other node anchored.

Connect the mounted instance to `createActions()` for incremental placement and animation; see [Edit nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-nodes) for mounting and state bindings with React [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriaflow), Vue [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriaflow), Qwik [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriaflow), Angular [`DiagramCanvasComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-components-diagramcanvascomponent), and browser [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render).

Add the framework component below and render it where the quick start renders its flow component. For JavaScript, change `src/main.ts` as shown, retaining the stylesheet import. For Qwik, add `src/LayoutEditor.tsx` and the route shown after the tabs, then open `/layout/`. The shared module stays at `src/layout-actions.ts` in every project.

:::code-group
```ts title="JavaScript — src/main.ts"
import './style.css';
import { render } from '@grafloria/element';
import { createActions, nodes, edges } from './layout-actions';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = `
  <button id="place">Place new step</button>
  <button id="region">Grow neighborhood</button>
  <button id="row">Animate to row</button>
  <button id="close">Close diagram</button>
  <div id="canvas" style="height: 500px; width: 100%"></div>
`;
const host = document.querySelector<HTMLDivElement>('#canvas');
if (!host) throw new Error('Missing canvas');
const api = render({ nodes, edges }, host);
const actions = createActions(api, async id => {
  await api.placeNodes([id], { after: 'review', duration: 600 });
});
document.querySelector<HTMLButtonElement>('#place')!.onclick = () => void actions.placeNew();
document.querySelector<HTMLButtonElement>('#region')!.onclick = () => void actions.growRegion();
document.querySelector<HTMLButtonElement>('#row')!.onclick = () => actions.animateRow();
document.querySelector<HTMLButtonElement>('#close')!.onclick = () => {
  actions.dispose();
  api.dispose();
  app.replaceChildren();
};
```
```tsx title="React — src/LayoutEditor.tsx"
import { useEffect, useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import { createActions, nodes, edges } from './layout-actions';

export function LayoutEditor() {
  const actions = useRef<ReturnType<typeof createActions> | null>(null);
  useEffect(() => () => { actions.current?.dispose(); }, []);
  return (
    <section>
      <button onClick={() => void actions.current?.placeNew()}>Place new step</button>
      <button onClick={() => void actions.current?.growRegion()}>Grow neighborhood</button>
      <button onClick={() => actions.current?.animateRow()}>Animate to row</button>
      <div style={{ height: 500 }}>
        <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
          onInit={api => {
            actions.current = createActions(api, async id => {
              await api.placeNodes([id], { after: 'review', duration: 600 });
            });
          }} />
      </div>
    </section>
  );
}
```
```vue title="Vue — src/components/LayoutEditor.vue"
<script setup lang="ts">
import { shallowRef, onUnmounted } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { createActions, nodes, edges } from '../layout-actions';

const actions = shallowRef<ReturnType<typeof createActions>>();
function onInit(api: DiagramInstance): void {
  actions.value = createActions(api, async (id: string) => {
    await api.placeNodes([id], { after: 'review', duration: 600 });
  });
}
onUnmounted(() => actions.value?.dispose());
</script>

<template>
  <section>
    <button @click="actions?.placeNew()">Place new step</button>
    <button @click="actions?.growRegion()">Grow neighborhood</button>
    <button @click="actions?.animateRow()">Animate to row</button>
    <div style="height: 500px">
      <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" @init="onInit" />
    </div>
  </section>
</template>
```
```ts title="Angular — src/app/layout-editor.component.ts"
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { createActions, nodes, edges } from '../layout-actions';

@Component({
  selector: 'app-layout-editor',
  imports: [DiagramCanvasComponent],
  template: `
    <button (click)="actions()?.placeNew()">Place new step</button>
    <button (click)="actions()?.growRegion()">Grow neighborhood</button>
    <button (click)="actions()?.animateRow()">Animate to row</button>
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      (ready)="onReady($event)" style="display: block; height: 500px" />
  `,
})
export class LayoutEditorComponent {
  readonly nodes = signal<NodeSpec[]>(nodes);
  readonly edges = signal<EdgeSpec[]>(edges);
  readonly actions = signal<ReturnType<typeof createActions> | null>(null);

  constructor() {
    inject(DestroyRef).onDestroy(() => this.actions()?.dispose());
  }

  onReady(api: GrafloriaCanvasInstance): void {
    this.actions.set(createActions(api, async (id: string) => {
      await api.getEngine().layoutIncremental({
        changed: [id], strategy: 'region', radius: 0, direction: 'LR',
      });
    }));
  }
}
```
```tsx title="src/LayoutEditor.tsx"
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import { createActions, nodes, edges } from './layout-actions';

export default component$(() => {
  const actions = useSignal<NoSerialize<ReturnType<typeof createActions>>>();
  useVisibleTask$(({ cleanup }) => {
    cleanup(() => actions.value?.dispose());
  });
  return (
    <section>
      <button onClick$={() => actions.value?.placeNew()}>Place new step</button>
      <button onClick$={() => actions.value?.growRegion()}>Grow neighborhood</button>
      <button onClick$={() => actions.value?.animateRow()}>Animate to row</button>
      <div style={{ height: '500px' }}>
        <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
          onInit$={api => {
            actions.value = noSerialize(createActions(api, async (id: string) => {
              await api.placeNodes([id], { after: 'review', duration: 600 });
            }));
          }} />
      </div>
    </section>
  );
});
```
:::

The initial canvas shows Start, Review and Finish connected left to right, with Place new step, Grow neighborhood and Animate to row buttons above it.

![Look at the initial Start → Review → Finish chain and the three action buttons above it; this is the arrangement before adding or animating steps.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/966b5b74e8e1cf361969eaf7686fee7a.png)

In Qwik, add `src/routes/layout/index.tsx` to render the component: import `LayoutEditor` from `../../LayoutEditor` and re-export it as the route's default export.

Drag Review to another position, then click **Place new step**. The three action buttons share a queue: each click runs after the preceding operation finishes. Repeated placement clicks each add a step. The helper keeps the current live models instead of replaying the original coordinates. In the flow-placement bindings, the new step slides out from Review; Angular places it with the other nodes pinned. The framework components own canvas teardown; the unmount hooks cancel only the sample's animation. JavaScript's Close diagram button tears down both.

## 3. Preserve the mental map with a neighborhood layout

Click **Grow neighborhood** to add a branch and run the shared `growRegion()` sample. [`IncrementalOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-incremental#incrementaloptions) names the changed IDs and the allowed graph-hop radius. With `strategy: 'region'` and `radius: 1`, the new step and its direct neighbor can move; nodes outside that region are anchors that the layered layout works around.

`layoutIncremental()` commits the resulting positions and returns a [`MovementReport`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-incremental#movementreport) plus a [`TweenPlan`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-incremental#tweenplan). Look in your console for the total, average and maximum movement of existing nodes, the moved/unmoved counts, and `withinBudget`. IDs in `changed` are excluded from that movement baseline.

[`MovementBudget`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-incremental#movementbudget) is a measurement threshold: `maxPerNode` checks the largest displacement and `averagePerNode` checks the mean. An exceeded threshold sets `withinBudget` to `false`; it does not reject the layout or clamp its coordinates.

Choose the [`IncrementalStrategy`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-incremental#incrementalstrategy) that matches your editing intent:

| Strategy | What changes |
| --- | --- |
| `'region'` | The changed IDs and their `radius`-hop neighborhood may move; everything outside is anchored. This is the engine method's default. |
| `'pin-existing'` | Only IDs in `changed` may move. Use it when all other manual positions must remain fixed. |
| `'minimal-shift'` | All nodes may move. With no anchors, the result is translated to match the previous centroid, reducing displacement. Movement is reported against the budget. |

See [Dynamic (mental-map) layouting](https://grafloria.com/demos/layout/dynamic-layouting.html) for a measured comparison against a from-scratch layout. Its [source](https://github.com/grafloria/grafloria/blob/5c0b626b42b8ca8ae6de46c7962cf0e8c78fda63/demos/layout/dynamic-layouting.html) records both sets of positions and compares the existing nodes' travel distances.

## 4. Animate between arrangements

Click **Animate to row** to run `animateRow()` from the shared module. The boxes move from their current positions to a horizontal row at world-coordinate `y: 240`, easing out over 900 ms. The sample reads the starts when you click, so a manual move becomes the animation's starting point. It batches `setPosition()` calls once per animation frame; it needs no extra repaint call. Reduced-motion preference skips the tween.

This follows the authors' [Node position animation](https://grafloria.com/demos/nodes/node-position-animation.html) demo: the host drives eased position writes. The [demo source](https://github.com/grafloria/grafloria/blob/5c0b626b42b8ca8ae6de46c7962cf0e8c78fda63/demos/nodes/node-position-animation.html) cycles through grid, ring and row arrangements.

For an undoable flow rearrangement in the instance-based bindings, use `tidy({ duration: 600 })` instead of custom position writes. It lays out linked steps in output-port order, leaves unlinked notes alone, animates by default, and returns the IDs that moved. `layoutIncremental()` itself does not animate: its `tween.at(t)` returns eased positions for normalized time `0` through `1`, which your host can apply with the same frame-writing pattern. New IDs have no previous position in that plan and appear at their targets rather than travelling from `(0, 0)`.

## Options that matter

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `IncrementalOptions.changed` | `string[]` | `[]` | Identifies the new or edited region; excludes those IDs from movement measurement. |
| `IncrementalOptions.strategy` | `IncrementalStrategy` | `'region'` | Selects anchoring behavior for `layoutIncremental()`. |
| `IncrementalOptions.radius` | `number` | `1` | Grows the region by graph hops when using `'region'`. |
| `IncrementalOptions.budget` | `MovementBudget` | Unset | Checks maximum and mean movement in the returned report. |
| `PlaceNodesOptions.after` | `string` | First incoming step | Names the parent to place after. |
| `FlowPlaceOptions.direction` | `'LR' \| 'TB'` | `'LR'` | Arranges flow steps left-to-right or top-to-bottom. |
| `FlowPlaceOptions.rankGap` | `number` | `80` | Gap between consecutive flow steps. |
| `FlowPlaceOptions.nodeGap` | `number` | `40` | Gap between siblings across the flow. |
| `FlowPlaceOptions.animate` | `boolean` | `true` | Tweens flow placement, except under reduced motion. |
| `FlowPlaceOptions.duration` | `number` | `280` | Tween duration in milliseconds. |

## Pitfalls and related tasks

- Use the layered engine for incremental layout. If the current arrangement comes from another engine, the first incremental pass can redraw it rather than make a small adjustment.
- `changed` means “allowed to change,” not “everything in the document.” Passing every ID removes the anchors that preserve your spatial map.
- Do not run a full rearrangement after placing a single new node: that replaces the fixed-position result you asked for.
- For declarative layout, algorithm selection and on-demand layout calls, see [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram). A layout prop does not re-run merely because node data changes.
- For position constraints and node dimensions, see [Size and position nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/size-and-position-nodes).
- For placement algorithm contracts such as [`PlacementOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-layout-interfaces-l-u#placementoptions), see [Extend tools and execution](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/tools-layouts-and-transports).
