# Group and collapse objects

Use groups when a frame represents ownership, not decoration: its members travel together, drops change membership, and collapse replaces the contents with a connected placeholder. This example starts with two selected service nodes, an external client, and a loose invoice. A fitted Service frame contains only the selected pair; an Archive zone gives you another drop target.

Start in the project from 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 file, styles, and configuration. Add the files below, then render the new component from the starter's existing root component; the JavaScript tab is an entry file instead.

This example adds grouping controls to a mounted diagram; see the [JavaScript quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start) for package setup.

## Grouping

1. Define typed node and edge specs. `selected: true` seeds the selection with Ingest and Transform, leaving Client and Invoice out.
2. Obtain the mounted [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) from the binding's initialization callback. Its [`DiagramEngine`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-engine) owns the grouping commands.
3. Read the current selection, call `addGroup()`, add each selected node with `addToGroup(groupId, entityId)`, then fit the frame around that pair.

Put this shared module beside each framework component below to seed the selected pair and the Archive drop target; see [Instance and lifecycle](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/instance-and-lifecycle) for input specs and live models.

```ts title="src/grouping.ts"
import type { GroupModel } from '@grafloria/engine';
import type { DiagramInstance, EdgeSpec, GroupSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = [
  { id: 'client', label: 'Client', position: { x: 40, y: 160 }, size: { width: 110, height: 50 } },
  { id: 'ingest', label: 'Ingest', position: { x: 260, y: 130 }, size: { width: 120, height: 50 }, selected: true },
  { id: 'transform', label: 'Transform', position: { x: 260, y: 240 }, size: { width: 120, height: 50 }, selected: true },
  { id: 'invoice', label: 'Invoice', position: { x: 500, y: 350 }, size: { width: 120, height: 50 } },
];

export const edges: EdgeSpec[] = [
  { id: 'request-a', source: 'client', target: 'ingest' },
  { id: 'request-b', source: 'client', target: 'transform' },
  { id: 'internal', source: 'ingest', target: 'transform' },
];

export const groups: GroupSpec[] = [{
  id: 'archive', label: 'Archive',
  bounds: { x: 460, y: 80, width: 260, height: 230 },
  labelPlacement: 'bottom-left',
  style: {
    fill: '#f3f4f6', stroke: '#64748b', strokeDasharray: '5 4',
    color: '#334155', fontWeight: '700', letterSpacing: 1,
  },
}];

export async function groupSelection(instance: DiagramInstance): Promise<GroupModel | undefined> {
  const diagram = instance.getModel();
  const ids = diagram.getSelectedNodes().map(node => node.id);
  if (ids.length === 0) return undefined;
  const engine = instance.getEngine();
  const group = await engine.addGroup({ name: 'Service' });
  for (const id of ids) await engine.addToGroup(group.id, id);
  group.fitToContents(diagram);
  return group;
}

export async function initialize(instance: DiagramInstance): Promise<string | undefined> {
  return (await groupSelection(instance))?.id;
}

export type Action = 'group' | 'collapse' | 'expand' | 'detach' | 'remove';
export const actions: { action: Action; label: string }[] = [
  { action: 'group', label: 'Group selection' },
  { action: 'collapse', label: 'Collapse group' },
  { action: 'expand', label: 'Expand group' },
  { action: 'detach', label: 'Detach Invoice' },
  { action: 'remove', label: 'Remove frame' },
];

export async function act(
  instance: DiagramInstance, groupId: string | undefined, action: Action,
): Promise<string | undefined> {
  const engine = instance.getEngine();
  if (action === 'group') return (await groupSelection(instance))?.id ?? groupId;
  if (action === 'detach') {
    const owner = engine.getGroups().find(group => group.members.has('invoice'));
    if (owner) await engine.removeFromGroup(owner.id, 'invoice');
    return groupId;
  }
  if (!groupId || !engine.getGroup(groupId)) return groupId;
  if (action === 'collapse') {
    await engine.collapseGroup(groupId, { proxyLabel: info => `${info.count}×` });
  } else if (action === 'expand') {
    await engine.expandGroup(groupId);
  } else if (action === 'remove') {
    await engine.expandGroup(groupId);
    await engine.removeGroup(groupId);
    return undefined;
  }
  return groupId;
}
```

`addGroup()` resolves to the live [`GroupModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-groupmodel). `addToGroup()` and `removeFromGroup()` take the group id first and resolve without a value. These engine methods execute commands; direct model mutations are for building or loading data. Fitting writes the group's geometry, not a separate history command. To bundle frame fitting and membership into a single editor action, use the command composition taught in [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history).

### Mount the same example in your framework

Each tab uses the same shared module. React, Vue, and Qwik seed uncontrolled defaults, so the live model owns subsequent node edits. Angular follows the full `render()` host used by the drop-containment demo; its `ready` output supplies the same instance.

- JavaScript: [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core) mounts the spec. Keep your starter's existing HTML and stylesheet imports; add a `<div id="app"></div>` only if it does not already have the host.
- React: [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react) supplies `onInit`; store the instance and group id in refs.
- Vue: [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue) emits `init`; keep the live instance in a shallow ref.
- Qwik: [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik) supplies `onInit$`; keep the instance with `noSerialize()` and the group id as serializable state.
- Angular: [`GrafloriaDiagramComponent`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-overview) mounts the full spec and disposes its instance on destruction.

:::code-group
```ts title="JavaScript — src/main.ts"
/// <reference types="vite/client" />
import { render } from '@grafloria/element';
import { act, actions, edges, groups, initialize, nodes } from './grouping';

const root = document.getElementById('app')!;
const toolbar = document.createElement('div');
const host = document.createElement('div');
host.style.height = '480px';
root.append(toolbar, host);
const instance = render({ nodes, edges, groups }, host);
let groupId: string | undefined;
const ready = initialize(instance).then(id => { groupId = id; });
for (const item of actions) {
  const button = document.createElement('button');
  button.textContent = item.label;
  button.onclick = async () => {
    await ready;
    groupId = await act(instance, groupId, item.action);
  };
  toolbar.append(button);
}
if (import.meta.hot) import.meta.hot.dispose(() => instance.dispose());
```

```tsx title="React — src/GroupingExample.tsx"
import { useRef } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { act, actions, edges, groups, initialize, nodes } from './grouping';
import type { Action } from './grouping';

export default function GroupingExample() {
  const live = useRef<DiagramInstance | null>(null);
  const groupId = useRef<string | undefined>(undefined);
  const ready = useRef<Promise<void> | undefined>(undefined);
  function onInit(instance: DiagramInstance) {
    live.current = instance;
    ready.current = initialize(instance).then(id => {
      if (live.current === instance) groupId.current = id;
    });
  }
  async function run(action: Action) {
    await ready.current;
    const instance = live.current;
    if (instance) groupId.current = await act(instance, groupId.current, action);
  }
  return <>
    <div>{actions.map(item => <button key={item.action}
      onClick={() => void run(item.action)}>{item.label}</button>)}</div>
    <div style={{ height: 480 }}>
      <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges}
        defaultGroups={groups} onInit={onInit} />
    </div>
  </>;
}
```

```vue title="Vue — src/GroupingExample.vue"
<script setup lang="ts">
import { shallowRef } from 'vue';
import { GrafloriaFlow } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { act, actions, edges, groups, initialize, nodes } from './grouping';
import type { Action } from './grouping';

const live = shallowRef<DiagramInstance>();
let groupId: string | undefined;
let ready: Promise<void> | undefined;
function onInit(instance: DiagramInstance) {
  live.value = instance;
  ready = initialize(instance).then(id => { groupId = id; });
}
async function run(action: Action) {
  await ready;
  if (live.value) groupId = await act(live.value, groupId, action);
}
</script>

<template>
  <div>
    <button v-for="item in actions" :key="item.action"
      @click="run(item.action)">{{ item.label }}</button>
  </div>
  <div style="height:480px">
    <GrafloriaFlow :default-nodes="nodes" :default-edges="edges"
      :default-groups="groups" @init="onInit" />
  </div>
</template>
```

```tsx title="Qwik — src/grouping-example.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 { act, actions, edges, groups, initialize, nodes } from './grouping';

export default component$(() => {
  const live = useSignal<NoSerialize<DiagramInstance>>();
  const groupId = useSignal<string>();
  const ready = useSignal(false);
  return <>
    <div>{actions.map(item => <button key={item.action} disabled={!ready.value}
      onClick$={async () => {
        if (live.value) groupId.value = await act(live.value, groupId.value, item.action);
      }}>{item.label}</button>)}</div>
    <div style={{ height: '480px' }}>
      <GrafloriaFlow defaultNodes={nodes} defaultEdges={edges} defaultGroups={groups}
        onInit$={$(async (instance: DiagramInstance) => {
          live.value = noSerialize(instance);
          groupId.value = await initialize(instance);
          ready.value = true;
        })} />
    </div>
  </>;
});
```

```ts title="Angular — src/grouping-example.ts"
import { Component, signal } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { DiagramInstance } from '@grafloria/renderer';
import { act, actions, edges, groups, initialize, nodes } from './grouping';
import type { Action } from './grouping';

@Component({
  selector: 'app-grouping-example',
  standalone: true,
  imports: [GrafloriaDiagramComponent],
  template: `
    <div>
      @for (item of actions; track item.action) {
        <button [disabled]="!initialized()" (click)="run(item.action)">{{ item.label }}</button>
      }
    </div>
    <grafloria-diagram [spec]="spec" (ready)="onReady($event)"
      style="display:block;height:480px" />
  `,
})
export class GroupingExample {
  readonly actions = actions;
  readonly spec = { nodes, edges, groups };
  readonly initialized = signal(false);
  private live?: DiagramInstance;
  private groupId?: string;

  async onReady(instance: DiagramInstance): Promise<void> {
    this.live = instance;
    this.groupId = await initialize(instance);
    this.initialized.set(true);
  }
  async run(action: Action): Promise<void> {
    if (this.initialized() && this.live) {
      this.groupId = await act(this.live, this.groupId, action);
    }
  }
}
```
:::

The JavaScript entry renders the selected pair inside Service, with Archive and Invoice to the right.

![Service contains selected Ingest and Transform; five action buttons sit above the diagram.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/15d46fd88710b26f64b38ec19e9cb851.png)

The React component renders the same nodes, links, and group frames.

The Vue component also leaves Invoice outside both frames.

The binding owns teardown in the component tabs. In a JavaScript application that removes the host itself, call `instance.dispose()` when that view unmounts; the entry above also disposes on Vite hot replacement.

The initial view contains a Service frame around Ingest and Transform, three links, the empty Archive zone, and Invoice below it. Compare [Selection grouping](https://grafloria.com/demos/grouping/selection-grouping.html) for the same selection-to-container operation.

## Group frames

The Service group uses the diagram theme's titled frame. Archive uses a zone: a tinted region with a caption and no title band. `groups` in the shared spec declares its pinned `bounds`, dashed stroke, caption colour, and bottom-left label placement.

1. Use a `GroupSpec` when your application owns frame data. Its `children` array becomes membership, not merely a visual overlay.
2. Omit `bounds` to fit the zone around its children with `padding`.
3. Call `setGroups()` to reconcile a complete replacement list of zones. Omitting a group from that list removes its frame, not its nodes.

For example, this alternate initialization callback replaces Archive's styling while keeping the Service group that the mounted example created:

```ts title="src/style-groups.ts"
import type { DiagramInstance } from '@grafloria/renderer';
import { groups, initialize } from './grouping';

export async function initializeStyled(instance: DiagramInstance): Promise<string | undefined> {
  const id = await initialize(instance);
  const service = id ? instance.getEngine().getGroup(id) : undefined;
  instance.setGroups([
    ...groups.map(group => ({
      ...group,
      style: { ...group.style, fill: '#ecfdf5', stroke: '#059669' },
    })),
    ...(service ? [service] : []),
  ]);
  return id;
}
```

Use `initializeStyled` in place of `initialize` in your framework's callback; it runs on the mounted instance, and Archive changes to green. See [Group frames](https://grafloria.com/demos/grouping/group-frames.html) for frames inside frames, and [Nest containers and lanes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers) for parent-child layout.

## Drop to contain

The same mounted example already accepts drops; group dragging and drop membership default to `true`.

1. Drag Invoice into Archive and release. It joins Archive.
2. Drag Archive by its caption or empty tint, not by a node. Invoice travels with the zone.
3. Drop Invoice inside Service to transfer it, or outside every frame to detach it.
4. Press Ctrl+Z or ⌘+Z to undo a drop: the position change and membership change form one undo step.

The **Detach Invoice** button demonstrates the explicit equivalent: find the owning group with `getGroups()`, then call `removeFromGroup()`. It leaves the node at its current world position. **Remove frame** expands the active group first, then removes the container with `removeGroup()`; its nodes remain.

For frames that are decoration only, disable both behaviors on the mounted instance:

```ts title="src/decorative-groups.ts"
import type { DiagramInstance } from '@grafloria/renderer';
import { initialize } from './grouping';

export async function initializeDecorative(instance: DiagramInstance): Promise<string | undefined> {
  const id = await initialize(instance);
  instance.getEngine().setInteractionConfig({
    enableGroupDrag: false,
    enableGroupMembershipOnDrop: false,
  });
  return id;
}
```

Use this callback instead of `initialize` only when you want that decorative behavior. To retain membership while moving individual nodes, disable only `enableGroupMembershipOnDrop`.

Try [Drop to contain](https://grafloria.com/demos/grouping/drop-to-contain.html) for transfers between frames and [Parent move](https://grafloria.com/demos/interaction/parent-move.html) for dragging a container with its graph.

## Collapse & expand

1. Click **Collapse group** in the mounted example. Ingest and Transform hide; Service shrinks to a placeholder.
2. The internal link disappears from the visible diagram. Both Client-to-Service crossings aggregate into one proxy link labelled `2×` by the sample's `proxyLabel` callback.
3. Click **Expand group**. The original member positions, frame geometry, and three links return.

Use `engine.collapseGroup()` and `engine.expandGroup()` for this reversible operation. The snapshot lives on the group as `collapsedState`; it records member positions, previous visibility, removed links, original boundary endpoints, and the frame geometry. Crossings aggregate separately for each external node and direction.

The bare model methods `collapse()` and `expand()` only change the collapse flag. They do not capture positions or aggregate edges. `setCollapsedState()` writes the snapshot; application collapse controls use the engine methods rather than constructing that snapshot.

When loading a group whose collapse state is only a flag, you can change that flag on the mounted model explicitly. These functions leave link endpoints and member visibility untouched:

```ts title="src/collapse-flag.ts"
import type { DiagramInstance } from '@grafloria/renderer';

export function markCollapsed(instance: DiagramInstance, groupId: string): void {
  instance.getEngine().getGroup(groupId)?.collapse();
}

export function markExpanded(instance: DiagramInstance, groupId: string): void {
  instance.getEngine().getGroup(groupId)?.expand();
}
```

See [Collapse & expand](https://grafloria.com/demos/grouping/collapse-expand.html) for boundary-link aggregation, and [Expand / collapse](https://grafloria.com/demos/layout/expand-collapse.html) for the layout-focused example. To persist a collapsed diagram, save the whole versioned document through [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore), not only its group.

## Build and fit containers as data

Use direct model methods when preparing a document, not for edits made by an inspector. The following alternate initialization callback creates a nested Retry frame, detaches Transform from Service, and puts Transform inside Retry. The parent frame fits around the child frame; Transform remains visible.

It also reads back the group serialization into a separate preview. That preview uses its own nodes and links, so no current edits are replaced. `serialize()` / `fromJSON()` copy a group, not an entire diagram: membership ids need matching entities in the destination.

```ts title="src/build-containers.ts"
import { GroupModel } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
import { edges, initialize, nodes } from './grouping';

export async function initializeContainers(
  instance: DiagramInstance, preview: DiagramInstance,
): Promise<string | undefined> {
  const id = await initialize(instance);
  const diagram = instance.getModel();
  const service = id ? instance.getEngine().getGroup(id) : undefined;
  if (!service) return id;

  service.removeMember('transform', diagram);
  const retry = new GroupModel({ id: 'retry', name: 'Retry' });
  diagram.addGroup(retry);
  retry.addMember('transform', diagram);
  retry.fitToContents(diagram);
  retry.setParent(service.id, diagram);
  service.fitToContents(diagram, { mode: 'grow-only', deepRecursive: true });
  retry.bringToFront(diagram);
  service.sendToBack(diagram);

  const outer = service.getOuterBounds();
  const inner = service.getInnerBounds();
  instance.container.setAttribute('aria-label',
    `Service frame ${outer.width} by ${outer.height}; inner width ${inner.width}`);

  preview.setNodes(nodes);
  preview.setEdges(edges);
  const restored = GroupModel.fromJSON(retry.serialize());
  restored.setParent(undefined);
  restored.constrainChildren = true;
  restored.setFrame({ x: 200, y: 100, width: 260, height: 200 });
  preview.getModel().addGroup(restored);
  restored.clampChildToExtent('transform', preview.getModel());
  return id;
}
```

Mount the preview beside the primary diagram, then call this initializer with both live instances. This complete browser entry mounts both diagrams with `render()`:

```ts title="src/container-preview.ts"
/// <reference types="vite/client" />
import { render } from '@grafloria/element';
import { edges, groups, nodes } from './grouping';
import { initializeContainers } from './build-containers';

const root = document.getElementById('app')!;
const mainHost = document.createElement('div');
const previewHost = document.createElement('div');
mainHost.style.height = '480px';
previewHost.style.height = '400px';
root.append(mainHost, previewHost);
const main = render({ nodes, edges, groups }, mainHost);
const preview = render({ nodes, edges }, previewHost);
void initializeContainers(main, preview);
if (import.meta.hot) import.meta.hot.dispose(() => {
  main.dispose();
  preview.dispose();
});
```

The main view has nested Service and Retry frames; the preview has one restored Retry frame with Transform clamped into its inner rectangle. A group's serialization keeps its geometry, members, layout, metadata, and collapse snapshot, but does not serialize `memberValidation`, transient hover state, or the runtime diagram reference. Reattach application validation after loading.

### Arrange members inside a frame

`setLayout()` stores a container layout. Call `applyLayout()` for its initial application; subsequent membership and frame changes request layout automatically. This alternate initializer arranges the two Service members in columns and gives the frame a fixed size:

```ts title="src/layout-group.ts"
import type { DiagramInstance } from '@grafloria/renderer';
import { initialize } from './grouping';

export async function initializeGrid(instance: DiagramInstance): Promise<string | undefined> {
  const id = await initialize(instance);
  const group = id ? instance.getEngine().getGroup(id) : undefined;
  if (!group) return id;
  group.setFrame({ x: 220, y: 80, width: 320, height: 230 });
  group.setLayout('grid', {
    templateColumns: 'repeat(2, 1fr)', templateRows: 'auto',
    columnGap: 20, rowGap: 20, autoFlow: 'row',
  });
  group.applyLayout(instance.getModel());
  instance.container.setAttribute('aria-label', `Service uses ${group.getLayout().type}`);
  return id;
}
```

Use `initializeGrid` in your framework's initialization callback. `getLayout()` returns `{ type, config }`; `hasLayout()` checks for a configured layout. `getGridLayout()` and `getFlexboxLayout()` return the respective config and throw if the group has a different layout type. `clearLayout()` removes that configuration. `isAutoLayoutEnabled()` reports whether push-driven reflow is active; `requestLayout()` respects that policy, whereas `applyLayout()` explicitly runs the configured layout. See [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram) for whole-diagram layout.

## Swimlanes

A pool tiles child lane groups into bands. Horizontal lanes are rows stacked along Y; vertical lanes are columns along X. Lane groups reuse membership, inner bounds, and child constraints rather than implementing separate node ownership.

Follow [Nest containers and lanes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers) for the runnable pool-and-lane construction, weighted bands, and resizing. The container preview above shows the underlying extent check with `getInnerBounds()` and `clampChildToExtent()`.

## Options and geometry queries

Only set interaction flags to change the defaults. Use [`FitToContentsOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-interfaces) to choose whether fitting can shrink or grow an authored frame.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `enableGroupDrag` | `boolean` | `true` | Moves the frame and recursive members together when you drag empty frame area. |
| `enableGroupMembershipOnDrop` | `boolean` | `true` | Transfers a dropped node into a group or detaches it outside all frames. |
| `GroupModel.padding` | Number or per-side object | Resolved to 16 for an authored group | Adds space around members during fitting. |
| `GroupModel.headerHeight` | `number` | `24` | Reserves the top title band in inner bounds and fitting. |
| `GroupModel.constrainChildren` | `boolean` | `false` | Enables clamping direct member nodes into the inner extent. |
| `FitToContentsOptions.mode` | `'exact' \| 'grow-only' \| 'shrink-only'` | The group's `fitMode`, initially `'exact'` | Overrides the fit policy for one call. |
| `FitToContentsOptions.deepRecursive` | `boolean` | Unset | Fits descendant groups deepest first, then the parent. |
| `GroupSpec.padding` | `number` | `20` | Spaces the fitted zone around its children when bounds are omitted. |
| `GroupSpec.labelPlacement` | Caption position | `'top-left'` | Places the zone caption without a title band. |
| `CollapseOptions.proxyLabel` | Callback returning `string` | Count for bundles larger than one; otherwise no synthetic label | Labels each aggregate crossing; return `''` to suppress the label. |

Fit policies are distinct:

| Value | Result |
| --- | --- |
| `exact` | Fits to the content rectangle plus padding and header. |
| `grow-only` | Unions that rectangle with the existing frame; never shrinks it. |
| `shrink-only` | Clamps fitting inside the current frame; never grows it. |

Zone caption positions are `top-left`, `top`, `top-right`, `bottom-left`, `bottom`, and `bottom-right`. Container layout types are `none`, `flexbox`, and `grid`.

For geometry, `getOuterBounds()` prefers explicit position and size, then derived bounds. `getInnerBounds()` subtracts resolved `getPadding()` and the header band. `calculateBounds()` computes a tight node-only bounding box without padding; use `fitToContents()` when you want a frame. `growToFitMembers()` never shrinks and returns whether geometry changed. `ownsItsFrame()` excludes collapsed groups, layout containers, lanes, constrained containers, and frameless groups from automatic growth on membership changes.

`setFrame()` writes authoritative position, size, and hit-test bounds. It does not, by itself, translate ordinary member nodes: use the built-in group drag to move them together. `restoreGeometry()` restores raw saved geometry, including an absent size. `setZIndex()` sets stacking directly; `bringToFront()` and `sendToBack()` place a group above or below the other groups.

For admission policy, `canAddMember()` rejects self-membership, containment cycles, capacity overflow, and candidates vetoed by `memberValidation`. `setCapacity(undefined)` clears the WIP limit. `getWipState()` returns a count and one of `unlimited`, `under`, `full`, or `over`; `isOverCapacity()` is true for both `full` and `over`. `setHovered()` changes transient drop-target highlighting, not persistent document state. See [Build a Kanban board](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/build-kanban-board) for capacity-aware UI.

## Pitfalls and related tasks

- Group membership uses ids, not geometric overlap. With drop membership disabled, moving a node outside a frame does not detach it.
- `setParent()` maintains both the child's parent pointer and the containing groups' membership sets; it returns `false` when a cycle or admission rule rejects reparenting.
- A constrained child's inner rectangle can be smaller than the node. Make the frame large enough for the node and its padding before expecting it to fit fully.
- Do not save only groups when you need links and member nodes restored. Use [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore).
- Use [Theme a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/theme-diagram) for shared theme tokens, and [Select, copy and add actions](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/selection-and-actions) for selection controls that follow the live model.
