# Nest containers and lanes

Use containers when part of a graph travels together, or use a pool when nodes belong to named bands. You get real membership, bounded movement, and a compound layout that includes edges crossing container boundaries.

Start in the project from the [JavaScript](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start), [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start), or [Vue quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start). Keep that project's entry file, styles, and configuration. The examples below add a shared module and a view; mount the view from your existing entry or route.

## 1. Define the container scenes

There are two different relationships:

- A [`GroupModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-groupmodel) holds node or group ids in `members`. Nodes keep world coordinates. Adding a group as a member sets its `parentGroupId`.
- A [`NodeModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-nodemodel) uses `parentId` for a node hierarchy. Call `setParent(parent.id)` on an attached model, then position the child with local coordinates.

Populate container membership before requesting the compound layout; see [Model and document](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/model-and-document) for the relationship between specs, live models, and the engine.

Create this module in each project at `src/containers.ts`. The Qwik view below lives beside it.

```ts title="src/containers.ts"
import { GroupModel, SwimlaneService, GroupCollapseService } from '@grafloria/engine';
import type { DiagramModel, DiagramEngine, FlexboxLayoutConfig } from '@grafloria/engine';
import type { NodeSpec, EdgeSpec } from '@grafloria/renderer';

export const scene: 'subflow' | 'pool' | 'page' = 'subflow';

export function nodesForScene(name: 'subflow' | 'pool' | 'page'): NodeSpec[] {
  if (name === 'pool') {
    return ['design', 'build', 'review', 'release'].map((id, index) => ({
      id, label: id, position: { x: 160 + index * 130, y: 80 },
      size: { width: 110, height: 44 },
    }));
  }
  if (name === 'page') {
    return [
      { id: 'section', label: 'Section', position: { x: 40, y: 40 }, size: { width: 560, height: 300 } },
      { id: 'row', label: 'Row', position: { x: 0, y: 0 }, size: { width: 500, height: 200 } },
      { id: 'heading', label: 'Welcome', position: { x: 0, y: 0 }, size: { width: 150, height: 44 } },
      { id: 'button', label: 'Get started', position: { x: 0, y: 0 }, size: { width: 150, height: 44 } },
    ];
  }
  return [
    { id: 'start', label: 'Start', position: { x: 80, y: 80 }, size: { width: 100, height: 44 } },
    { id: 'retry', label: 'Retry', position: { x: 240, y: 80 }, size: { width: 100, height: 44 } },
    { id: 'finish', label: 'Finish', position: { x: 440, y: 80 }, size: { width: 100, height: 44 } },
  ];
}

export function edgesForScene(name: 'subflow' | 'pool' | 'page'): EdgeSpec[] {
  return name === 'subflow' ? [
    { id: 'internal', source: 'start', target: 'retry' },
    { id: 'cross', source: 'retry', target: 'finish', label: 'continue' },
  ] : [];
}

export async function initialize(
  model: DiagramModel,
  engine: DiagramEngine,
  name: 'subflow' | 'pool' | 'page',
): Promise<void> {
  if (name === 'page') {
    buildPage(model);
    return;
  }
  engine.setInteractionConfig({
    enableGroupDrag: true,
    enableGroupMembershipOnDrop: true,
  });
  if (name === 'pool') {
    buildPool(model);
    return;
  }

  // Populate membership before requesting a compound graph layout.
  const pipeline = new GroupModel({ id: 'pipeline', name: 'Pipeline' });
  const retryHandler = new GroupModel({ id: 'retry-handler', name: 'Retry handler' });
  const output = new GroupModel({ id: 'output', name: 'Output' });
  for (const group of [pipeline, retryHandler, output]) {
    model.addGroup(group);
    group.padding = 16;
    group.constrainChildren = true;
  }
  pipeline.addMember('start', model);
  retryHandler.addMember('retry', model);
  pipeline.addMember(retryHandler.id, model);
  output.addMember('finish', model);
  await engine.layout('dagre', { direction: 'LR', nodeSpacing: 30, rankSpacing: 60 });
}

function buildPool(model: DiagramModel): void {
  const service = new SwimlaneService(model);
  const { pool, lanes } = service.createPool({
    id: 'delivery', name: 'Delivery', orientation: 'horizontal',
    bounds: { x: 40, y: 40, width: 720, height: 380 },
    headerSize: 40,
    lanes: [
      { id: 'work', name: 'Work', weight: 2 },
      { id: 'done', name: 'Done', weight: 1 },
    ],
  });
  const work = lanes[0]!;
  const done = lanes[1]!;
  const flex: FlexboxLayoutConfig = {
    direction: 'row', wrap: 'wrap', gap: 16, padding: 16,
    justifyContent: 'start', alignItems: 'start', alignContent: 'start',
    columns: 4,
  };
  work.setLayout('flexbox', flex);
  model.getNode('design')!.setFlexItem({ order: 2 });
  model.getNode('build')!.setFlexItem({ order: 1 });
  work.addMember('design', model);
  work.addMember('build', model);

  done.setLayout('grid', {
    templateColumns: 'repeat(2, 1fr)', templateRows: '1fr',
    columnGap: 16, rowGap: 16, autoFlow: 'row', padding: 16,
  });
  const review = model.getNode('review')!;
  review.setGridItem({ columnStart: 2, rowStart: 1 });
  model.getNode('release')!.setGridItem({ columnStart: 1, rowStart: 1 });
  done.addMember('review', model);
  done.addMember('release', model);

  // Query the layout intent stored on the live models.
  console.log('Review placement', review.getGridItem());
  console.log('Lane roles', service.getLanes(pool).map(lane => lane.laneConfig?.role));
}

function buildPage(model: DiagramModel): void {
  const section = model.getNode('section')!;
  const row = model.getNode('row')!;
  const heading = model.getNode('heading')!;
  const button = model.getNode('button')!;

  row.setParent(section.id);
  row.setLocalPosition(30, 60);
  heading.setParent(row.id);
  button.setParent(row.id);
  // addChild writes the parent's collection; setParent writes the relationship.
  row.addChild(heading.id);
  let y = 40;
  for (const child of row.getChildren()) {
    child.setLocalPosition(20, y);
    y += child.size.height + 20;
  }
  console.log('Page children', section.getChildren().map(child => child.id));
}

export function collapseRetry(model: DiagramModel): void {
  const group = model.getGroup('retry-handler');
  if (group) new GroupCollapseService(model).collapse(group);
}
```

The subflow seed has an edge inside Pipeline and an edge from Retry to Finish in Output. Pipeline holds the Retry handler group, not a second direct membership for Retry.

## 2. Mount the subflow

Initialize the container scene on the mounted instance before enabling **Collapse retry**; see [Edit nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-nodes) for mounting and instance access in each binding.

The component owns teardown in Angular, Vue, and Qwik. In JavaScript, add the code below to your existing entry after its stylesheet imports; the Close diagram button tears down the instance.

:::code-group
```ts title="JavaScript"
// Addition to src/main.ts; keep its existing stylesheet imports.
import { render } from '@grafloria/element';
import { scene, nodesForScene, edgesForScene, initialize, collapseRetry } from './containers';

function mountContainers(host: HTMLElement): () => void {
  const button = document.createElement('button');
  button.textContent = 'Collapse retry';
  button.hidden = scene !== 'subflow';
  const canvas = document.createElement('div');
  canvas.style.height = '520px';
  host.append(button, canvas);
  const instance = render({
    nodes: nodesForScene(scene), edges: edgesForScene(scene),
  }, canvas);
  button.disabled = true;
  void initialize(instance.getModel(), instance.getEngine(), scene).then(() => {
    button.disabled = false;
  });
  button.onclick = () => instance.batchUpdate(collapseRetry);
  return () => {
    button.onclick = null;
    instance.dispose();
    button.remove();
    canvas.remove();
  };
}

const host = document.createElement('div');
document.body.append(host);
const unmountContainers = mountContainers(host);
const close = document.createElement('button');
close.textContent = 'Close diagram';
document.body.append(close);
close.onclick = () => {
  unmountContainers();
  host.remove();
  close.remove();
};
```
```ts title="Angular"
// src/app/containers-view.ts
import { Component, signal } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { scene, nodesForScene, edgesForScene, initialize, collapseRetry } from '../containers';

@Component({
  selector: 'app-containers-view',
  imports: [DiagramCanvasComponent],
  template: `
    @if (scene === 'subflow') {
      <button [disabled]="!initialized()" (click)="collapse()">Collapse retry</button>
    }
    <grafloria-diagram-canvas [(nodes)]="nodes" [(edges)]="edges"
      (ready)="ready($event)" style="display:block; height:520px" />
  `,
})
export class ContainersView {
  readonly scene = scene;
  nodes = nodesForScene(scene);
  edges = edgesForScene(scene);
  readonly initialized = signal(false);
  private instance?: GrafloriaCanvasInstance;

  async ready(instance: GrafloriaCanvasInstance): Promise<void> {
    this.instance = instance;
    await initialize(instance.getModel(), instance.getEngine(), scene);
    this.initialized.set(true);
  }

  collapse(): void {
    if (this.instance) this.instance.batchUpdate(collapseRetry);
  }
}
```
```tsx title="Qwik"
// src/ContainersView.tsx
import { component$, noSerialize, useSignal } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import type { DiagramInstance } from '@grafloria/renderer';
import { scene, nodesForScene, edgesForScene, initialize, collapseRetry } from './containers';

export default component$(() => {
  const instance = useSignal<NoSerialize<DiagramInstance>>();
  const initialized = useSignal(false);
  return <>
    {scene === 'subflow' && <button disabled={!initialized.value} onClick$={() => {
      if (instance.value) instance.value.batchUpdate(collapseRetry);
    }}>Collapse retry</button>}
    <div style={{ height: '520px' }}>
      <GrafloriaFlow defaultNodes={nodesForScene(scene)} defaultEdges={edgesForScene(scene)}
        onInit$={async (api: DiagramInstance) => {
          instance.value = noSerialize(api);
          await initialize(api.getModel(), api.getEngine(), scene);
          initialized.value = true;
        }} />
    </div>
  </>;
});
```
```vue title="Vue"
<!-- src/ContainersView.vue -->
<script setup lang="ts">
import { shallowRef, ref } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { scene, nodesForScene, edgesForScene, initialize, collapseRetry } from './containers';

const nodes = nodesForScene(scene);
const edges = edgesForScene(scene);
const instance = shallowRef<DiagramInstance>();
const initialized = ref(false);

async function onInit(api: DiagramInstance): Promise<void> {
  instance.value = api;
  await initialize(api.getModel(), api.getEngine(), scene);
  initialized.value = true;
}

function collapse(): void {
  if (instance.value) instance.value.batchUpdate(collapseRetry);
}
</script>

<template>
  <button v-if="scene === 'subflow'" :disabled="!initialized" @click="collapse">Collapse retry</button>
  <div style="height:520px">
    <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" @init="onInit" />
  </div>
</template>
```
:::

![The Vue view shows Pipeline containing Start and Retry handler, Output containing Finish, and a Collapse retry button.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/2d4aeb6496d7d09766c79d6a6f942df5.png)

In Angular, import `ContainersView` into your existing root component's `imports` and add `<app-containers-view />` to its template. In Vue, import `ContainersView` into your existing `App.vue` and add `<ContainersView />`. In Qwik, import the default component from `src/ContainersView.tsx` into your existing route and render `<ContainersView />`.

You see Pipeline enclosing Start and a nested Retry handler, with Output enclosing Finish. The graph flows left to right. The explicit layout call comes after membership exists: the engine lays out the deepest containers first, fits their frames, then arranges their parents. Cross-container edges are projected onto the units at their lowest common ancestor; the Retry-to-Finish edge participates in the ordering of Pipeline and Output.

Open the [Nested containers demo](https://grafloria.com/demos/layout/nested-containers.html) to compare the two arrangements produced by reversing a cross-boundary edge. The [Sub-flow demo](https://grafloria.com/demos/grouping/sub-flow.html) shows nested membership and fitted frames.

## 3. Keep movement inside a container

The sample enables `enableGroupDrag` so dragging an empty part of a group frame carries its members. It enables `enableGroupMembershipOnDrop` so dropping a loose node into a group assigns it to that group. `constrainChildren = true` confines member movement to the group's inner bounds; a confining group does not detach its member on an outside drop.

For programmatic placement, call `clampChildToExtent(nodeId, model)` on a confining group after moving a direct member. It returns `true` if it changes the position. For a frame sized by its contents, call `fitToContents(model)` on the inner group before its parent. Use `setFrame()` when you want an explicit fixed rectangle instead.

The [Parent & child demo](https://grafloria.com/demos/grouping/parent-child.html) lets you compare attached and detached movement. Group membership is separate from a node's `parentId`: do not set a node parent merely to put a ticket into a lane.

## 4. Build a weighted swimlane pool

Change the exported `scene` in `src/containers.ts` to `'pool'`, then reload the view. The same mount now runs `buildPool()` on the mounted model.

[`SwimlaneService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-interaction) creates Delivery with Work and Done bands. Work has weight 2, so it receives twice Done's cross-axis space. `createPool()` returns `{ pool, lanes }`; `getLanes(pool)` returns the live lane groups in band order. Each lane is a group with `constrainChildren` enabled. Dragging a ticket between sibling lanes changes membership; its confinement covers the pool's lane area so it can cross the lane boundary without leaving the pool.

The Work lane uses [`FlexboxLayoutConfig`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-types-interfaces-b-r) with four columns, a 16-pixel gap, and item `order`: Build precedes Design. The Done lane uses a two-column grid: Release occupies column 1 and Review column 2. `setGridItem()` stores Review's explicit placement, and `getGridItem()` returns that intent rather than measured pixels. Adding members triggers the configured group layout; no repaint or extra layout call is needed.

Use [`CreatePoolOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-interaction) for construction. The service writes the intrinsic [`LaneConfig`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-interfaces) onto the pool and its lanes:

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `id` | `string` | Generated id | Gives the pool a stable identifier. |
| `orientation` | `'horizontal' \| 'vertical'` | Required | Horizontal lanes are rows stacked along Y; vertical lanes are columns stacked along X. |
| `bounds` | World rectangle | Required | Defines the pool frame. |
| `lanes` | Array of lane specs | Required | Defines lane names, ids, weights, and fixed sizes. |
| `headerSize` | `number` | `0` | Reserves a title band on the left for horizontal pools, or on top for vertical pools. |
| `laneHeaderSize` | `number` | `0` | Reserves a title band inside each lane. |
| `LaneConfig.role` | `'pool' \| 'lane'` | Assigned by the service | `pool` owns the bands; `lane` is one band. |
| `LaneConfig.orientation` | `'horizontal' \| 'vertical'` | Copied from the pool | Keeps lane orientation aligned with the pool. |
| `LaneConfig.laneOrder` | `string[]` | Construction order | Stores the ordered child lane ids on the pool. |
| `LaneConfig.headerSize` | `number` | `0` | Stores the pool's title-band thickness. |
| `LaneConfig.weight` | `number` | `1` | Divides the remaining cross-axis space proportionally. |
| `LaneConfig.fixedSize` | `number` | Unset | Pins one lane's cross-axis pixel size, overriding its weight. |

Use `resizeLane()` to pin a lane's size, `resizePool()` to change the pool frame, and `addLane()` or `removeLane()` to change its bands. These calls re-tile automatically. If you directly change `laneConfig`, call `reflow(pool)` to apply the new band configuration.

See the [Swimlanes demo](https://grafloria.com/demos/grouping/swimlanes.html) for weighted lanes, ticket drops, and pool movement.

### Choose the container layout

Group layouts position members; they do not require a node-parent hierarchy. These are the choices in a flex configuration:

| Field | Values | Effect |
| --- | --- | --- |
| `direction` | `row`, `column`, `row-reverse`, `column-reverse` | Selects the main axis and its forward or reversed order. |
| `wrap` | `nowrap`, `wrap`, `wrap-reverse` | Keeps a single line, breaks lines, or reverses the line order. Wrapping needs a bounded main-axis size. |
| `justifyContent` | `start`, `center`, `end`, `space-between`, `space-around`, `space-evenly` | Distributes free main-axis space. |
| `alignItems` | `start`, `center`, `end`, `stretch`, `baseline` | Selects cross-axis alignment within a line. |
| `alignContent` | `start`, `center`, `end`, `space-between`, `space-around`, `stretch` | Stored configuration. Group flex lines start at the content origin and advance by their cross-axis size plus the gap, regardless of this value. |
| `gap` | A number, or `{ row, column }` | Sets gaps in pixels. |
| `columns` | Positive number | Enables column-span layout for a row container; the sample uses four columns. |

`setFlexItem()` stores per-item configuration. `getFlexItem()` reads it, `hasFlexItem()` tests whether it exists, and `clearFlexItem()` removes it. `order` defaults to 0; lower orders precede higher ones. Equal orders retain membership order. The grid counterparts are `setGridItem()`, `getGridItem()`, `hasGridItem()`, and `clearGridItem()`.

## 5. Build a page-component hierarchy

Change `scene` to `'page'` and reload. You see Section containing Row, with Welcome and Get started arranged vertically inside Row. This follows the page-builder pattern: nodes are components, hierarchy expresses containment, and walking `getChildren()` places a component's immediate contents.

The module attaches every node before calling `setParent()`. That lets the model synchronize the parent's child collection. `setParent()` takes an id, not a node object, and switches an attached child to relative positioning. `addChild()` only updates the parent's collection; it does not set the child's `parentId`. Likewise, `removeChild()` and `setChildren()` write only that collection. Use `setParent(undefined)` to clear the child's relationship.

Choose the coordinate/query methods for the question you need to answer:

| Methods | Result |
| --- | --- |
| `getLocalPosition()`, `setLocalPosition()` | Read or write the stored offset; the setter selects relative positioning. |
| `getGlobalPosition()`, `setGlobalPosition()` | Read or write world coordinates, converting through the parent's scale, rotation, and translation for relative children. |
| `getLocalTransformMatrix()`, `getGlobalTransformMatrix()` | Read the local transform or its composition with the parent's global transform. |
| `getGlobalBounds()` | Read an axis-aligned box around the four transformed corners. |
| `getParent()`, `getChildren()` | Read the immediate parent or children. |
| `getAncestors()`, `getDescendants()` | Walk upward, nearest parent first, or recursively downward. |
| `getRoot()`, `getSiblings()` | Read the topmost node, or other children of the same parent. A root returns itself from `getRoot()` and has no siblings from `getSiblings()`. |
| `isAncestorOf(nodeId)`, `getDepth()` | Test ancestry, or count parents; a root has depth 0. |
| `validateHierarchy()` | Test the parent chain for cycles. |
| `updateHierarchyDepth()` | Recalculate the stored depth for this node and its descendants. |
| `getAffectedByTransform()` | Return this node plus descendants reached through relative-positioned children. |

Keep the hierarchy acyclic before recursively walking descendants or updating depths. When reparenting without changing the visible position, read `getGlobalPosition()` first, call `setParent()`, then pass the saved coordinates to `setGlobalPosition()`.

For user-facing reparenting and inspector edits, use [commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) rather than treating construction mutations as undoable edits. For rendered component interiors, continue with [custom rendering](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/custom-rendering).

## 6. Collapse the nested subflow

With `scene` set back to `'subflow'`, click **Collapse retry** after initialization completes. Run the collapse inside `instance.batchUpdate()` so model notifications reach the view after the whole operation completes. [`GroupCollapseService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-interaction) hides Retry, saves the group's geometry and member positions, and replaces its crossing edges with proxy connections at the collapsed group. Pipeline and Output remain visible.

Call `expand(group)` on the same service to restore the snapshot. For an undoable collapse action and the full expand/collapse UI, see [Group and collapse objects](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/group-and-collapse).

## Pitfalls

- Give the canvas host a resolved height. A canvas fills its parent; a parent with no resolved height produces a blank view. The examples use 520 pixels.
- Use explicit membership for subflows and local coordinates for node hierarchies. They are different data models, not interchangeable parent settings.
- Preserve the layout intent when changing live data. See [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram) for declarative layout updates, and [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore) for lossless persistence.

The built-in drop interaction uses [`GroupMembershipService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-interaction) to find the destination and plan membership commands. Reach for it only when implementing your own interaction tool. [`SemanticMembershipService`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-interaction) is the alternative for data-driven membership: `register(group)` evaluates its serialized rule and subscribes to node changes; it removes only rule-added members that stop matching, not manual members. The returned disposer stops managing that group; `dispose()` detaches all its subscriptions.

## Related

- [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram) — Choose graph algorithms and declarative layout requests.
- [Group and collapse objects](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/group-and-collapse) — Add undoable grouping and collapse controls.
- [Size and position nodes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/size-and-position-nodes) — Control node geometry independently of membership.
