Scripting Tutorial: Swap Objects

A first script for Affinity. Select two objects, run the script, and the objects trade places. It is short enough to read in one sitting, but it touches the four things almost every script does: find the document, read the selection, build a command, and execute it.

Scripting is currently in beta. Some parts of Affinity are not yet scriptable, and additional features will be added in future updates.

The whole script

JavaScript

'use strict';

// Swaps the positions of two selected objects, keeping their centers.

const { CompoundCommandBuilder, DocumentCommand } = require('/commands.js');
const { Document } = require('/document.js');
const { Transform } = require('/geometry.js');
const { Selection } = require('/selections.js');

function main() {
  const doc = Document.current;
  if (!doc) {
    alert("This script requires an open document");
    return;
  }
  const nodes = doc.selection.nodes.toArray();
  if (nodes.length != 2) {
    alert("Please select exactly two objects");
    return;
  }
  const [a, b] = nodes.map(n => ({ node: n, c: n.getSpreadBaseBox().centre }));
  const builder = CompoundCommandBuilder.create()
    .addCommand(
      DocumentCommand.createTransform(Selection.create(doc, a.node),
      Transform.createTranslate(b.c.x - a.c.x, b.c.y - a.c.y))
    )
    .addCommand(
      DocumentCommand.createTransform(Selection.create(doc, b.node),
      Transform.createTranslate(a.c.x - b.c.x, a.c.y - b.c.y))
    );
  doc.executeCommand(builder.createCommand());
}

main();

Step by step

1. Import what you need

JavaScript

const { CompoundCommandBuilder, DocumentCommand } = require('/commands.js');
const { Document } = require('/document.js');
const { Transform } = require('/geometry.js');
const { Selection } = require('/selections.js');

Affinity's scripting library is split into modules, and you pull in only the pieces you use. Paths starting with / resolve to the built-in library, so these lines work from any script wherever it lives.

  • Document is how you get at the open document.
  • Selection wraps a set of objects so a command knows what to act on.
  • Transform builds the move.
  • DocumentCommand and CompoundCommandBuilder are how changes are made. More on that below.

2. Get the current document

JavaScript

const doc = Document.current;
if (!doc) {
  alert("This script requires an open document");
  return;
}

Document.current is the front document, or null when nothing is open. Checking it first means the script fails with a friendly message rather than an exception. alert is available everywhere and shows a simple message box.

3. Read the selection

JavaScript

const nodes = doc.selection.nodes.toArray();
if (nodes.length != 2) {
  alert("Please select exactly two objects");
  return;
}

Everything on a page is a node: shapes, curves, text, groups, images. doc.selection.nodes gives the selected ones as a collection, and toArray() turns it into a plain JavaScript array so you can use length, map and friends. Swapping only makes sense for exactly two objects, so anything else stops here.

4. Find each object's center

JavaScript

const [a, b] = nodes.map(n => ({ node: n, c: n.getSpreadBaseBox().centre }));

getSpreadBaseBox() returns the object's bounding rectangle in spread coordinates, the shared coordinate space of the page, regardless of how the object is rotated or nested. Rectangles have a handy centre point. We keep each node alongside its center so the next step can read both.

5. Describe the moves as commands

JavaScript

const builder = CompoundCommandBuilder.create()
  .addCommand(
    DocumentCommand.createTransform(Selection.create(doc, a.node),
    Transform.createTranslate(b.c.x - a.c.x, b.c.y - a.c.y))
  )
  .addCommand(
    DocumentCommand.createTransform(Selection.create(doc, b.node),
    Transform.createTranslate(a.c.x - b.c.x, a.c.y - b.c.y))
  );

This is the heart of Affinity scripting. Scripts do not poke at objects directly. They build commands that describe a change, then hand them to the document to execute. That is what makes every script undoable and previewable.

Each line does three things:

  1. Selection.create(doc, a.node) wraps one object so the command knows its target.
  2. Transform.createTranslate(dx, dy) builds a move by the difference between the two centers. Object A moves by "B minus A", object B by "A minus B".
  3. DocumentCommand.createTransform(selection, transform) turns those into a command.

The two commands go into a CompoundCommandBuilder, which bundles them into a single command. Without it, the swap would be two separate steps in the History panel and take two undos to reverse.

6. Execute

JavaScript

doc.executeCommand(builder.createCommand());

createCommand() finalizes the compound and executeCommand runs it. The objects move, the History panel gains one entry, and ⌘Z (Mac) / Ctrl+Z (Windows) puts them back.

7. Run the script

JavaScript

main();

Everything above only defines main; this last line calls it. Wrapping the work in a function rather than writing it at the top level keeps the early exits simple, since a return from main ends the script cleanly when there's no document or the wrong number of objects is selected.

Try the script

  1. Draw two shapes some distance apart, ideally different sizes so the swap is obvious.
  2. Select both and run the script. Each shape's center lands where the other's was.
  3. Press ⌘Z (Mac) / Ctrl+Z (Windows) once. Both objects return to their original positions in a single step, thanks to the compound command.

Ideas for extending the script

  • Swap more than two. Rotate positions around a ring of N objects: each moves to the next one's center.
  • Swap corners instead of centers. Replace .centre with .topLeft to align top-left corners rather than centers.
  • Swap sizes too. Scale each object by the other's width and height ratio using Transform.createScale, combined with the translate.

SEE ALSO:

How would you rate the help you received from this article?