Skip to content
D
Documentation

Select, copy and add actions

how-to
7 min readUpdated

Use selection to choose the objects an action affects, copy them into independent duplicates, and place new nodes where a palette item lands. The examples below render Alpha and Beta joined by an edge, with buttons for selection, copying, pasting and deletion.

Start in the project left by your JavaScript, React, Vue, Angular or Qwik quick start. Keep its entry file, styles and framework configuration; mount the new editor from that entry in place of the quick start's editor. These examples use the packages those projects already install.

1. Add actions to the mounted diagram

The diagram owns live models; the engine owns behavior. Obtain the DiagramInstance from the binding's initialization callback, then use its getEngine() for undoable edits. The shared module below receives that live engine and its camera rather than creating a second model.

Type the starting data with NodeSpec and EdgeSpec.

ts
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = [
  { id: 'a', position: { x: 100, y: 120 }, size: { width: 130, height: 60 }, label: 'Alpha' },
  { id: 'b', position: { x: 400, y: 120 }, size: { width: 130, height: 60 }, label: 'Beta' },
];
export const edges: EdgeSpec[] = [{ id: 'e', source: 'a', target: 'b' }];

The module uses DiagramEngine to select and delete. Its ViewportController converts palette drops from client pixels into world coordinates. Construct a NodeModel to label a palette node before inserting it. The action panel stays in screen space, outside the camera-transformed layer.

ts
import { NodeModel } from '@grafloria/engine';
import type { DiagramEngine } from '@grafloria/engine';
import type { ViewportController } from '@grafloria/renderer';

export function attachActions(
  engine: DiagramEngine,
  viewport: ViewportController,
  host: HTMLElement,
  copy: () => Promise<void>,
  paste: () => Promise<void>,
): () => void {
  const panel = document.createElement('div');
  panel.style.cssText = 'position:absolute;top:8px;left:8px;z-index:10;display:flex;gap:6px;flex-wrap:wrap;background:white;padding:8px';
  const status = document.createElement('span');
  status.setAttribute('role', 'status');
  const report = (error: Error) => { status.textContent = error.message; };
  const run = (action: () => Promise<void>) => {
    void action().catch(report);
  };
  const button = (label: string, action: () => void) => {
    const element = document.createElement('button');
    element.textContent = label;
    element.onclick = action;
    panel.append(element);
    return element;
  };
  button('Select Alpha', () => {
    const diagram = engine.getDiagram();
    if (!diagram) return;
    for (const node of diagram.getNodes()) {
      if (node.id === 'a') node.setSelected(true);
      else node.setState({ selected: false });
    }
    engine.selectNodes(diagram.getNodes().filter((node) => node.isSelected()).map((node) => node.id));
  });
  button('Select both', () => engine.selectNodes(['a', 'b']));
  button('Clear selection', () => engine.clearSelection());
  button('Copy', () => run(copy));
  button('Paste', () => {
    if (engine.hasClipboardData()) run(paste);
  });
  button('Duplicate Alpha', () => {
    if (!engine.getDiagram()?.getNode('a')) return;
    engine.selectNodes(['a']);
    run(() => engine.duplicate());
  });
  button('Delete selected', () => {
    const diagram = engine.getDiagram();
    if (!diagram) return;
    const selectedNodes = diagram.getSelectedNodes().map((node) => node.id);
    const selectedLinks = diagram.getLinks()
      .filter((link) => link.state === 'selected').map((link) => link.id);
    if (!selectedNodes.length && !selectedLinks.length) return;
    engine.selectNodes(selectedNodes);
    engine.selectLinks(selectedLinks);
    run(() => engine.deleteSelection());
  });
  button('Delete Alpha', () => {
    if (engine.getDiagram()?.getNode('a')) run(() => engine.removeNode('a'));
  });
  button('Delete edge', () => {
    if (engine.getDiagram()?.getLink('e')) run(() => engine.removeLink('e'));
  });

  const palette = document.createElement('span');
  palette.textContent = 'Drag Filter';
  palette.draggable = true;
  palette.addEventListener('dragstart', (event) => {
    event.dataTransfer?.setData('text/plain', 'filter');
  });
  panel.append(palette, status);
  host.append(panel);

  const dragover = (event: DragEvent) => {
    if (event.dataTransfer?.types.includes('text/plain')) event.preventDefault();
  };
  const drop = (event: DragEvent) => {
    if (event.dataTransfer?.getData('text/plain') !== 'filter') return;
    event.preventDefault();
    const point = viewport.clientToWorld(
      event.clientX, event.clientY, host.getBoundingClientRect(),
    );
    const node = new NodeModel({
      type: 'rect',
      position: { x: point.x - 55, y: point.y - 22 },
      size: { width: 110, height: 44 },
    });
    node.data = { kind: 'filter' };
    node.setMetadata('label', 'Filter');
    run(async () => { await engine.addNode(node); });
  };
  host.addEventListener('dragover', dragover);
  host.addEventListener('drop', drop);
  return () => {
    host.removeEventListener('dragover', dragover);
    host.removeEventListener('drop', drop);
    panel.remove();
  };
}

NodeModel lets you set the palette node's label before addNode() records it in history. removeNode() and removeLink() also execute commands: the actions use the same undo stack as diagram gestures.

Mount the editor in your framework. The JavaScript entry uses render. The other entries render GrafloriaFlow for React, GrafloriaFlow for Vue, GrafloriaFlow for Qwik or Angular's DiagramCanvasComponent. React, Vue and Qwik use uncontrolled defaults: they seed the instance once, and subsequent edits belong to the live model. Angular uses two-way nodes and edges bindings so model changes return to the component's arrays.

For Vue, use the canvas mounting pattern from Edit nodes with the selection, clipboard and palette actions in place of the inspector.

ts
import { render } from '@grafloria/element';
import { nodes, edges } from './action-data';
import { attachActions } from './actions';

const host = document.createElement('div');
host.style.cssText = 'height:460px;position:relative';
document.body.append(host);
const instance = render({ nodes, edges }, host);
const detach = attachActions(
  instance.getEngine(), instance.viewport, host,
  async () => { await instance.copy(); },
  async () => { await instance.paste(); },
);
const pasteOffset = document.createElement('button');
pasteOffset.textContent = 'Paste with offset';
pasteOffset.style.cssText = 'position:absolute;bottom:8px;left:8px;z-index:10';
pasteOffset.onclick = async () => {
  await instance.paste(undefined, { offset: { x: 60, y: 100 } });
};
host.append(pasteOffset);
const close = document.createElement('button');
close.textContent = 'Close editor';
close.onclick = () => {
  detach();
  instance.dispose();
  host.remove();
  close.remove();
};
document.body.append(close);

The binding owns disposal of its canvas; your unmount cleanup removes only the listeners and panel you added.

The JavaScript editor renders Alpha connected to Beta, an action panel and a Close editor button.

React renders the same two-node flow.

Alpha and Beta appear below the React editor's action panel.

Vue uses the same starting data.

The Vue editor shows Alpha connected to Beta.

Angular renders the flow through its canvas component.

The Angular editor shows the two nodes and their connecting edge below the action panel.

Qwik initializes the browser-side action panel after the canvas mounts.

The Qwik editor shows Alpha, Beta and the action panel.

Press Duplicate Alpha to select Alpha and call duplicate() without a separate copy step. Clear selection calls clearSelection(). Delete selected reads the live selected nodes and edges, synchronizes them with selectNodes() and selectLinks(), then calls deleteSelection() to remove them through history. selectLinks() selects the supplied link ids and deselects the other links. The Paste button checks hasClipboardData() before requesting a paste.

The panel's node and edge buttons target explicit ids. For a pointer-anchored menu, see the live Context menu. For actions that travel with their target, compare the Node toolbar and Edge toolbar.

For Angular's shipped node-action factories and LinkToolbarComponent, which renders an edge's action overlay, follow Angular state and tooling.

Copy / paste

  1. Press Select Alpha, then Copy. The instance serializes the selected node into the diagram's clipboard.
  2. Press Paste twice. Each paste creates a node with a new id. In Angular, move the pointer to a different canvas position before the second paste to separate the copies; the other samples cascade their default paste positions.
  3. Drag one duplicate. Alpha and the other duplicate stay where they are.

The runnable editor above uses copy() and paste() on the instance; Angular uses copySelection() and pasteClipboard() on its canvas. With the canvas focused, Ctrl/⌘+C and Ctrl/⌘+V reach the clipboard through the library's keyboard handlers. Try the Copy / paste demo to compare independent duplicates.

copy() resolves to the clipboard payload, or null when no nodes are selected. paste() resolves to false when it cannot paste, including a read-only instance or an empty clipboard. cut() copies and deletes the selection as one undo step; it returns null when nothing is cut or the view is read-only.

ClipboardManager is the engine's serialized, in-memory clipboard, not the operating system clipboard. Its get() reads the payload, set() adopts a payload kept by your app, and clear() clears it. Use the instance methods for ordinary editor actions rather than constructing a separate manager. Copied links are remapped to the pasted ports; a link whose endpoint was not copied is omitted.

The engine's getClipboardData() returns that payload or null; clearClipboard() empties the clipboard. getClipboardStats() returns the node, link and group counts and the payload's timestamp, which is null for an empty clipboard.

For explicit placement, pass a payload and PasteOptions as the instance's second argument: paste(payload, options). An offset is a delta from the copied positions, not an absolute destination.

In the JavaScript editor, select Alpha and press Copy, then Paste with offset. This button passes undefined to reuse the clipboard and places the duplicate 60 world units right and 100 down from the copied position. Repeated presses use the same offset rather than cascading.

OptionTypeDefaultWhat it does
offset{ x: number; y: number }Cascading multiples of { x: 20, y: 20 }Adds the supplied delta to every pasted node.
selectPastedbooleantrueSelects the pasted nodes and clears the store's selected link ids; it leaves live link and group selection unchanged. Pasted links retain their serialized selection state.

Angular's pasteClipboard() places the copied bounding box under the last known cursor position; without a known cursor it uses a fixed { x: 20, y: 20 } offset. Repeated pastes with an unchanged cursor position land together.

Call engine.selectLinks([]) to clear live link selection as well.

Drag & drop from a palette

  1. Drag Drag Filter from the editor's action panel onto the canvas.
  2. Drop it away from Alpha and Beta. A Filter node appears with its center at the drop point.
  3. Pan with the wheel, or zoom with Ctrl/⌘+wheel, and drop another Filter. The live camera transform still places its center under the pointer.

The drop handler in actions.ts calls clientToWorld() with a fresh getBoundingClientRect(). Subtracting half the node's width and height changes the position from the intended center to the model's top-left corner. addNode() returns the live node and records the insertion as an undoable command. Each drop constructs a new model, so it does not reuse another node's id.

Compare the Drag & drop from a palette demo. Do not substitute camera-origin arithmetic for clientToWorld(): the visible world rectangle includes center-preserving zoom.

Intersections

Use createDiagramApi to query overlaps on a mounted instance. Its DiagramApi returns live nodes from getIntersectingNodes(); the rectangle is in world coordinates.

  1. Run this browser entry instead of the action editor, then press Open intersections to mount the diagram.
  2. Drag A onto B. The status names B while their boxes overlap.
  3. Compare the contained-node readout: a partial overlap does not qualify for full containment.
ts
import { render } from '@grafloria/element';
import { createDiagramApi } from '@grafloria/renderer';
import type { NodeSpec } from '@grafloria/renderer';

const nodes: NodeSpec[] = [
  { id: 'a', position: { x: 80, y: 120 }, size: { width: 160, height: 100 }, label: 'A' },
  { id: 'b', position: { x: 360, y: 120 }, size: { width: 160, height: 100 }, label: 'B' },
  { id: 's', position: { x: 400, y: 150 }, size: { width: 50, height: 40 }, label: 'S' },
];
const open = document.createElement('button');
open.textContent = 'Open intersections';
document.body.append(open);
open.onclick = () => {
open.remove();
const host = document.createElement('div');
host.style.height = '400px';
const status = document.createElement('p');
status.setAttribute('role', 'status');
document.body.append(status, host);
const instance = render({ nodes, edges: [] }, host);
const api = createDiagramApi(instance);
const model = instance.getModel();
function update(id: string) {
  const node = model.getNode(id);
  if (!node) return;
  const position = node.getWorldPosition();
  const rect = { x: position.x, y: position.y, width: node.size.width, height: node.size.height };
  const names = (fully: boolean) => api.getIntersectingNodes(rect, { fully })
    .filter((other) => other.id !== id).map((other) => other.id).join(', ') || 'none';
  status.textContent = `${id}: overlaps ${names(false)}; contains ${names(true)}`;
}
const moved = ({ nodeId }: { nodeId: string }) => update(nodeId);
const stopMoved = model.on('node:moved', moved);
update('b');
const close = document.createElement('button');
close.textContent = 'Close intersections';
close.onclick = () => {
  stopMoved();
  api.dispose();
  instance.dispose();
  host.remove();
  status.remove();
  close.remove();
};
document.body.append(close);
};

The initial readout reports S inside B. The query also finds its own node, so the sample filters that id out. It listens to the model's node:moved event to recompute during movement rather than waiting for a committed nodes:change event. The Intersections demo uses the same query to highlight overlapping neighbors.

A sits apart from the larger box containing S; the readout reports that B overlaps and contains S.

OptionTypeDefaultWhat it does
fullybooleanfalsefalse finds any positive-area overlap; true requires the node's whole box inside the query rectangle.
visibleOnlybooleantruetrue ignores hidden nodes; false includes them.

Touching borders alone do not count as overlap. Full containment includes a node whose border coincides with the query border.

Selection beyond individual nodes

For hierarchy, group-member or filtered node selection, use the live engine's SelectionManager through selectionManager. Hierarchical selection includes selectChildren(), selectDescendants(), selectAncestors(), selectSiblings() and selectTree(). selectGroupMembers() selects a group's member nodes; filters use selectByType(), selectByFilter() or selectInRectangle().

For graph selection on these mounted specs, resolve each link's sourcePortId and targetPortId with the model's getNodeByPortId(), then pass the owning node ids to selectNodes(). selectConnected(), selectConnectedComponent() and selectPath() interpret endpoints as colon-prefixed node ids instead. Use those methods only with data whose port ids follow that convention.

selectGroupsContaining() returns containing group ids but does not apply group selection. selectAll() and invertSelection() return node, link and group candidates, but apply only node selection. Apply returned link ids through selectLinks() when your action needs selected edges.

The Select Alpha handler uses setSelected(true) for Alpha and setState({ selected: false }) for the other nodes. It reads isSelected() and synchronizes the engine's selected-id store for subsequent commands. isHighlighted() reads a node's highlight state, and setHighlighted() changes that attention state independently of selection. isSelectable() reports whether the node's behavior permits selection; isDraggable() also requires the node to be unlocked.

Selection operations combine with the existing selection through these modes:

modeEffect
replaceReplaces the selected node ids.
addAdds matching ids.
subtractRemoves matching ids.
toggleReverses membership for matching ids.

For selectConnected(), direction accepts incoming, outgoing or both. Rectangle selection's intersectionMode accepts intersect or contain.

  • Do not keep a selection count current only in a button handler. React's onSelectionChange, Vue's @selection-change, Qwik's onSelectionChange$ and Angular's (selectionChange) report the selected nodes and edges after changes; a plain instance exposes selection:change through on().
  • Keep programmatic edits undoable through engine commands. See Commands and history for batching inspector edits.
  • If you switch the React example to controlled inputs, follow React state and content for the return path from the live model.
  • For floating world-space content, use createViewportPortal. It takes the transformed HTML layer, so its content pans and scales with the canvas. A fixed-size screen toolbar instead projects its anchor with worldToClient() outside that layer.
  • See container sizing when embedding the editor in a nested layout, and saving and restoring for persistent documents rather than clipboard payloads.

Was this page helpful?

Select, copy and add actions — Grafloria