Skip to content
D
Documentation

Size and position nodes

how-to
8 min readUpdated

Use content sizing for labels whose length varies, size constraints for user-resizable boxes, and a dedicated grip when the node body contains controls. The model owns the geometry; your content paints inside that box. This example shows an auto-sized label, a constrained box, a rotating box, and a window with a draggable title bar.

Start in the project from your JavaScript, React, Vue, Angular, or Qwik quick start. Keep its entry file, styles, and configuration. The examples below use the packages those quick starts install; no additional package is required.

Auto-sizing

  1. Create src/node-geometry/nodes.ts. Type the data with NodeSpec. The first node opts into content sizing through metadata.sizing.auto; the second is a fixed-size comparison.
  2. Mount these nodes with the framework code below. Both start with the same declared width, but only the first grows to accommodate the label.
ts
import type { NodeSpec } from '@grafloria/renderer';

export function makeNodes(): NodeSpec[] {
  const label = 'A comfortably long label that does not fit in sixty pixels';
  return [
    {
      id: 'auto', position: { x: 40, y: 40 },
      size: { width: 60, height: 36 }, label,
      metadata: { sizing: { auto: true, padding: 10 } },
    },
    {
      id: 'fixed', position: { x: 40, y: 130 },
      size: { width: 60, height: 36 }, label,
    },
    {
      id: 'bounded', position: { x: 40, y: 240 },
      size: { width: 160, height: 100 }, label: 'Select, then resize',
      metadata: {
        sizing: { minWidth: 80, minHeight: 60, maxWidth: 260, maxHeight: 200 },
      },
    },
    {
      id: 'ratio', position: { x: 350, y: 240 },
      size: { width: 160, height: 100 }, label: 'Ratio 1.6',
      metadata: { sizing: { aspectLock: true } },
    },
    {
      id: 'spin', position: { x: 40, y: 420 },
      size: { width: 180, height: 90 }, label: 'Drag my body to rotate',
    },
    {
      id: 'win', position: { x: 350, y: 420 },
      size: { width: 240, height: 120 }, label: 'Window body',
    },
    {
      id: 'grip', position: { x: 350, y: 420 },
      size: { width: 240, height: 28 }, label: 'Title bar: drag here',
    },
  ];
}

The renderer measures opted-in nodes before drawing the frame and writes the fitted size through the model. A label change participates in the next sizing pass; there is no separate measuring or repaint step to call. The fitted box travels with the node when you drag it.

Compare the behavior in the Auto-sizing demo.

Constrained resizing

  1. Select the bounded node in the mounted example. Its resize handles appear.
  2. Drag a corner or an edge. The opposite side stays anchored, and the size stays within 80–260 by 60–200 during the gesture.
  3. Select ratio and resize it. Its starting width-to-height ratio, 1.6, stays locked without a modifier. Hold Shift on an unlocked node's corner resize to preserve its starting ratio for that gesture.

The node data above supplies the constraints to the built-in resizer. A completed resize records the size change together with any position change needed to keep the opposite side anchored. With default history merging, successive resizes of the same node that leave its position unchanged can share one history entry within the 500 ms merging window; Undo then reverses the combined changes.

For an inspector or a custom size control, read the same contract with getNodeSizing, clampSizeToConstraints, and resolveAspectRatio. desiredNodeSize returns the desired outer size without changing the node. Add this diagnostic module; initialization below calls it on the mounted model, so the console shows the auto-size prediction, the constrained candidate, and the locked ratio.

ts
import type { DiagramModel } from '@grafloria/engine';
import {
  clampSizeToConstraints, desiredNodeSize, getNodeSizing, resolveAspectRatio,
} from '@grafloria/renderer';

export function inspectSizing(diagram: DiagramModel): void {
  const auto = diagram.getNode('auto');
  const bounded = diagram.getNode('bounded');
  const ratio = diagram.getNode('ratio');
  if (!auto || !bounded || !ratio) return;

  console.log('Desired outer size', desiredNodeSize(auto));
  console.log('Candidate constrained to the legal range',
    clampSizeToConstraints(500, 20, getNodeSizing(bounded)));
  console.log('Locked width / height',
    resolveAspectRatio(getNodeSizing(ratio), ratio.size));
}

DiagramModel here is the live diagram, not a second model built for measurement. clampSizeToConstraints() clamps the axes independently; it does not apply an aspect ratio. The built-in resize gesture combines the range constraints and aspect lock. Use compatible ranges when locking a ratio.

See the Node resizer demo for the built-in handles and a custom corner control, and the Node resize gesture demo for the selected-node gesture.

Rotation

  1. Create the rotation module below.
  2. Install it on the mounted engine with initializeGeometry() below.
  3. Press inside spin and orbit the pointer around its center. Its body and label rotate together. Hold Shift to snap to 15-degree increments.

This interaction uses registerTool to claim a body drag, following the Rotatable node demo. Go below the component surface here because the body gesture replaces moving with rotating. The shipped SelectionToolsController supplies the rotation math and the command that records it as one undo step; you do not implement either yourself.

ts
import type { DiagramEngine } from '@grafloria/engine';
import { registerTool, SelectionToolsController } from '@grafloria/renderer';

export function installRotation(engine: DiagramEngine): () => void {
  const diagram = engine.getDiagram();
  const tools = new SelectionToolsController();
  const unregister = registerTool({
    id: `body-rotation-${crypto.randomUUID()}`,
    priority: 10,
    hitTest: (_event, hit) =>
      diagram?.isReadonly() === false && hit.node?.id === 'spin' &&
      hit.node.diagram === diagram,
    onPointerDown: (event, hit) => {
      if (!hit.node) return;
      tools.beginRotate({
        id: 'body-rotate', kind: 'rotate', nodeId: hit.node.id,
        world: event.world, hitRadius: 0, cursor: 'grab', label: 'Rotate',
      }, engine, event.world.x, event.world.y);
    },
    onPointerMove: (event) => {
      tools.updateRotate(engine, event.world.x, event.world.y, event.modifiers);
    },
    onPointerUp: () => {
      const command = tools.endGesture(engine);
      if (command) void engine.commandManager.execute(command);
    },
    onCancel: () => tools.cancelGesture(engine),
  });
  return () => {
    tools.cancelGesture(engine);
    unregister();
  };
}

DiagramEngine owns the history. Live pointer moves update geometry; release commits the controller's returned command. Cancellation restores the starting rotation. The tool claims only this diagram's spin node; other nodes retain their ordinary drag behavior.

Drag handle

  1. Create the initializer below. It makes grip a child of win and positions it at local (0, 0), inside the parent's top strip.
  2. Mount the complete scene with your framework's tab. Each tab calls this initializer after the component has created its live model.
  3. Drag the title bar. The whole window moves, while the grip retains its local position. In JavaScript, React, Vue, and Qwik, dragging the body selects the window but does not move it. In Angular, you can move the window by dragging either its title bar or its body. Focus the canvas and press Ctrl+Z or ⌘Z to undo the move.

The grip is chrome: it does not supply its own connection ports. Keeping it inside the parent leaves the window's outer rectangle as the connection boundary. See the Drag handle demo.

ts
import type { DiagramEngine } from '@grafloria/engine';
import { inspectSizing } from './inspect';
import { installRotation } from './rotation';

export function initializeGeometry(engine: DiagramEngine): () => void {
  const diagram = engine.getDiagram();
  if (!diagram) return () => {};
  diagram.getNode('win')?.sendToBack();
  const grip = diagram.getNode('grip');
  if (grip) {
    grip.setParent('win');
    grip.setPosition(0, 0);
    grip.setBehavior({ dragHandler: { isDragHandler: true } });
    grip.bringToFront();
  }
  inspectSizing(diagram);
  return installRotation(engine);
}

These setup mutations establish the scene; they are not user edits. The drag pipeline records subsequent window moves in history. NodeModel maintains both sides of the parent relationship, and setParent() makes the child's position relative.

sendToBack() places the window behind the other nodes, and bringToFront() places its grip in front. To assign a specific stacking index, use setZIndex(); lower values render further back. getEffectiveZIndex() returns the explicit model index, falling back to style.zIndex, then 0.

Mount the scene

Call initializeGeometry() after mounting to configure the title-bar grip and install the rotation tool; Edit nodes covers framework mounting and access to the live engine.

Keep the quick start's mounting code. In React, render GeometryExample inside its existing app; in Vue, render GeometryExample from the existing app template; in Angular, import GeometryExample into the existing root component's imports and add <geometry-example /> to its template. In Qwik, render the exported component from the existing route. For JavaScript, call mountGeometry() from the existing entry file after creating the host, and call the returned cleanup function when your application removes that view.

ts
import { render } from '@grafloria/element';
import { makeNodes } from './node-geometry/nodes';
import { initializeGeometry } from './node-geometry/initialize';

export function mountGeometry(host: HTMLElement): () => void {
  host.style.height = '650px';
  const instance = render({ nodes: makeNodes(), edges: [] }, host);
  const cleanup = initializeGeometry(instance.getEngine());
  return () => {
    cleanup();
    instance.dispose();
  };
}

The Qwik scene shows the widened auto-sized label above its narrow fixed-size comparison, two resize examples, a rotation example, and the window with its title bar.

EdgeSpec types Angular's two-way edge array. React, Vue, and Qwik use uncontrolled defaults here, so model edits do not need an application-state return path. Angular uses its two-way binding to return changed specs. The framework owns canvas teardown; your cleanup unregisters the additional rotation tool.

Set initial model geometry

Use direct model mutations when loading or establishing geometry, not for user-facing edits that need history. Create the module below and call mountInitialGeometry(host) from your JavaScript entry file with a separate host element. It draws a box moved 40 units right and 20 down, sized to 200 by 100, and rotated 20 degrees. Call the returned cleanup when removing that view.

move() adds a position delta, setSize() replaces dimensions, resize() adds dimension deltas, and setRotation() sets an angle in degrees. getWorldPosition() resolves the parent-position chain; getBoundingBox() returns the world-coordinate box built from that position and the stored size. It does not expand the box to enclose the rotated silhouette.

ts
import { render } from '@grafloria/element';
import type { NodeSpec } from '@grafloria/renderer';

export function mountInitialGeometry(host: HTMLElement): () => void {
  host.style.height = '400px';
  const nodes: NodeSpec[] = [{
    id: 'box', position: { x: 60, y: 60 },
    size: { width: 100, height: 60 }, label: 'Initial geometry',
  }];
  const instance = render({ nodes, edges: [] }, host);
  const box = instance.getModel().getNode('box');
  if (box) {
    box.move(40, 20);
    box.setSize(180, 90);
    box.resize(20, 10);
    box.setRotation(20);
    console.log('World position', box.getWorldPosition());
    console.log('World box before rotation', box.getBoundingBox());
  }
  return () => instance.dispose();
}

The remaining model geometry methods serve queries and loading:

MethodWhat it does
rotate()Adds an angle delta in degrees to the current rotation.
setScale()Replaces the model's x/y scale factors and propagates the transform change.
getCenter()Returns the world position plus half the stored width and height.
containsPoint()Tests whether a point lies inside the world-coordinate bounding box, including its boundary.
intersectsBounds()Tests whether a supplied bounding box overlaps or touches the node's world-coordinate box.
setTransformOrigin()Stores normalized x/y transform-origin coordinates, expressed from 0 to 1.
getAbsoluteTransformOrigin()Converts the stored origin to pixel offsets within the node's size, not world coordinates.
setDragHandlerConfig()Stores the model's drag-handler configuration and emits drag-handler:changed.
getDragHandlerConfig()Returns that stored configuration, or undefined.
isDragHandler()Returns whether that configuration's isDragHandler field is true.

The drag-handler configuration methods access dragHandlerConfig; the title-bar gesture above uses behavior.dragHandler through setBehavior() instead.

Set initial stacking order in Angular

For Angular's toolbar action objects, use createBringToFrontAction and createSendToBackAction. Each factory takes the live engine and returns an action whose onClick() takes the target node. These actions write style.zIndex. Establish this initial order before mounting the canvas, then pass each resulting style.zIndex to setZIndex() to store it as model geometry. Bind that same engine to the canvas rather than reconciling the geometry through node specs.

  1. Add this component to your Angular quick-start project.
  2. Import InitialStackingExample into the existing root component's imports and add <initial-stacking-example /> to its template.

The two boxes overlap. The component's setup sends the background behind the other nodes and brings the foreground above them before the first paint. These calls establish initial geometry rather than user-facing edits; they do not record history.

ts
import { Component } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import {
  createBringToFrontAction, createSendToBackAction, DiagramCanvasComponent,
} from '@grafloria/angular';
import { DiagramEngine, DiagramModel, NodeModel } from '@grafloria/engine';

@Component({
  selector: 'initial-stacking-example',
  imports: [DiagramCanvasComponent],
  template: `
    <grafloria-diagram-canvas [engine]="engine"
      style="display:block;height:400px" />
  `,
})
export class InitialStackingExample implements OnDestroy {
  readonly engine = new DiagramEngine();

  constructor() {
    const diagram = new DiagramModel();
    const foreground = new NodeModel({
      id: 'foreground', type: 'rect', position: { x: 160, y: 120 },
      size: { width: 200, height: 100 },
    });
    foreground.setMetadata('label', 'Foreground');
    const background = new NodeModel({
      id: 'background', type: 'rect', position: { x: 60, y: 60 },
      size: { width: 200, height: 100 },
    });
    background.setMetadata('label', 'Background');
    diagram.addNode(foreground);
    diagram.addNode(background);
    this.engine.setDiagram(diagram);
    createSendToBackAction(this.engine).onClick(background);
    background.setZIndex(background.style.zIndex);
    createBringToFrontAction(this.engine).onClick(foreground);
    foreground.setZIndex(foreground.style.zIndex);
  }

  ngOnDestroy(): void { this.engine.dispose(); }
}

Options that matter

All fields below live in NodeSizing, stored under metadata.sizing.

OptionTypeDefaultWhat it does
autobooleanOff when omittedFits content before rendering.
paddingnumber8Reserves content padding around the label for auto-sizing.
minWidth, minHeightnumberNo per-node constraintSet the lower size bounds; the built-in resizer also enforces its 16-unit floor.
maxWidth, maxHeightnumberNo per-node constraintSet upper bounds; auto-sizing wraps label measurement at maxWidth minus padding.
aspectLockboolean | numberUnlocked when omittedfalse: unlocked; true: preserve the supplied current ratio; a positive number: lock to that explicit width ÷ height. Nonpositive numbers do not establish a lock.

For pointer movement, the dragThreshold creation option sets the distance in element-local CSS pixels before a press becomes a drag; its default is 4. The engine's getSnapGuides() returns the live snap-guide segments shown during a node drag, or null. setSnapGuides() replaces those segments, or clears them with null; it does not emit an event because the driving drag already triggers rendering.

See the Helper lines (snaplines) demo for alignment guides during node positioning.

Pitfalls

  • Manually resizing an auto-sized node turns auto off: the user's size takes ownership instead of the next content-sizing pass replacing it.
  • A size prediction is not a mutation. desiredNodeSize() returns dimensions; the renderer applies automatic sizing for opted-in nodes. Its measurement options can differ from the active theme and reserved panel space, so do not treat an unconfigured prediction as an exact pixel assertion for every node.
  • Keep custom content inside the engine-owned box. For HTML rendering and registration, follow Custom rendering.
  • If you switch React to controlled nodes, also wire the change return path described in React state and content.
  • For programmatic Undo/Redo controls, use the engine as described in Lay out a diagram; the instance is not the history owner.
  • Nest containers explains parent-child coordinates and canvas sizing.
  • Edit nodes covers programmatic changes to live data.
  • Save and restore preserves the document rather than a selected projection of node specs.

Was this page helpful?

Size and position nodes — Grafloria