Skip to content
D
Documentation

Nest containers and lanes

how-to
8 min readUpdated

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, Angular, Qwik, or 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 holds node or group ids in members. Nodes keep world coordinates. Adding a group as a member sets its parentGroupId.
  • A 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 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
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 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.

ts
// 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();
};
The Vue view shows Pipeline containing Start and Retry handler, Output containing Finish, and a Collapse retry button.

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 to compare the two arrangements produced by reversing a cross-boundary edge. The Sub-flow demo 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 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 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 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 for construction. The service writes the intrinsic LaneConfig onto the pool and its lanes:

OptionTypeDefaultWhat it does
idstringGenerated idGives the pool a stable identifier.
orientation'horizontal' | 'vertical'RequiredHorizontal lanes are rows stacked along Y; vertical lanes are columns stacked along X.
boundsWorld rectangleRequiredDefines the pool frame.
lanesArray of lane specsRequiredDefines lane names, ids, weights, and fixed sizes.
headerSizenumber0Reserves a title band on the left for horizontal pools, or on top for vertical pools.
laneHeaderSizenumber0Reserves a title band inside each lane.
LaneConfig.role'pool' | 'lane'Assigned by the servicepool owns the bands; lane is one band.
LaneConfig.orientation'horizontal' | 'vertical'Copied from the poolKeeps lane orientation aligned with the pool.
LaneConfig.laneOrderstring[]Construction orderStores the ordered child lane ids on the pool.
LaneConfig.headerSizenumber0Stores the pool's title-band thickness.
LaneConfig.weightnumber1Divides the remaining cross-axis space proportionally.
LaneConfig.fixedSizenumberUnsetPins 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 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:

FieldValuesEffect
directionrow, column, row-reverse, column-reverseSelects the main axis and its forward or reversed order.
wrapnowrap, wrap, wrap-reverseKeeps a single line, breaks lines, or reverses the line order. Wrapping needs a bounded main-axis size.
justifyContentstart, center, end, space-between, space-around, space-evenlyDistributes free main-axis space.
alignItemsstart, center, end, stretch, baselineSelects cross-axis alignment within a line.
alignContentstart, center, end, space-between, space-around, stretchStored configuration. Group flex lines start at the content origin and advance by their cross-axis size plus the gap, regardless of this value.
gapA number, or { row, column }Sets gaps in pixels.
columnsPositive numberEnables 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:

MethodsResult
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 rather than treating construction mutations as undoable edits. For rendered component interiors, continue with 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 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.

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 for declarative layout updates, and Save and restore documents for lossless persistence.

The built-in drop interaction uses GroupMembershipService to find the destination and plan membership commands. Reach for it only when implementing your own interaction tool. SemanticMembershipService 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.

Was this page helpful?