Skip to content
D
Documentation

Group and collapse objects

how-to
9 min readUpdated

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, React, Vue, Angular, or 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 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 from the binding's initialization callback. Its DiagramEngine 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 for input specs and live models.

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

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 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 supplies onInit; store the instance and group id in refs.
  • Vue: GrafloriaFlow emits init; keep the live instance in a shallow ref.
  • Qwik: GrafloriaFlow supplies onInit$; keep the instance with noSerialize() and the group id as serializable state.
  • Angular: GrafloriaDiagramComponent mounts the full spec and disposes its instance on destruction.
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());

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.

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 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
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 for frames inside frames, and Nest containers and lanes 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
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 for transfers between frames and Parent move 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
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 for boundary-link aggregation, and Expand / collapse for the layout-focused example. To persist a collapsed diagram, save the whole versioned document through Save and restore documents, 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
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
/// <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
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 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 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 to choose whether fitting can shrink or grow an authored frame.

OptionTypeDefaultWhat it does
enableGroupDragbooleantrueMoves the frame and recursive members together when you drag empty frame area.
enableGroupMembershipOnDropbooleantrueTransfers a dropped node into a group or detaches it outside all frames.
GroupModel.paddingNumber or per-side objectResolved to 16 for an authored groupAdds space around members during fitting.
GroupModel.headerHeightnumber24Reserves the top title band in inner bounds and fitting.
GroupModel.constrainChildrenbooleanfalseEnables 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.deepRecursivebooleanUnsetFits descendant groups deepest first, then the parent.
GroupSpec.paddingnumber20Spaces the fitted zone around its children when bounds are omitted.
GroupSpec.labelPlacementCaption position'top-left'Places the zone caption without a title band.
CollapseOptions.proxyLabelCallback returning stringCount for bundles larger than one; otherwise no synthetic labelLabels each aggregate crossing; return '' to suppress the label.

Fit policies are distinct:

ValueResult
exactFits to the content rectangle plus padding and header.
grow-onlyUnions that rectangle with the existing frame; never shrinks it.
shrink-onlyClamps 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 for capacity-aware UI.

  • 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.
  • Use Theme a diagram for shared theme tokens, and Select, copy and add actions for selection controls that follow the live model.

Was this page helpful?

Group and collapse objects — Grafloria