Skip to main content

Phase 1 — Foundations

Every Affinity script, no matter how sophisticated, is built on three pieces of knowledge: how the script runtime works, how a document is structured, and how the objects inside it are organised. Phase 1 covers all three.

This is not a phase you should rush. The patterns established here — getting the current document, guarding against null, iterating the node tree, exploring unfamiliar objects with inspect — appear in virtually every script you will ever write. Developers who skip ahead and try to write something complex before understanding these foundations consistently hit the same walls: confusing errors about undefined properties, scripts that work on one document and fail silently on another, loops that miss nodes or visit them twice. The three lessons in this phase exist specifically to prevent those problems.

The Affinity SDK is not a browser API and not a Node.js API. It is a JavaScript environment embedded inside a running design application, with its own rules about what is allowed, what modules exist, and how the document model is exposed. Lesson 01 orients you in that environment and introduces the Application API. Lesson 02 introduces the document itself — the entry point for every script — and explains the spread and page model that underpins every Affinity file. Lesson 03 maps the node tree: the structure that holds every layer, group, shape, and text frame in the document, and teaches inspect as the primary discovery tool for any unfamiliar SDK object.

These three lessons have no dependencies on each other — but every later phase depends on them.

Lessons​

LessonTopicKey skill you'll gain
01 — Environment setupExecution model, module system, Application APIRunning your first script; app info, dialogs, document listing
02 — App & documentEntry point, current doc, spreadsAccessing any open document
03 — Node modelTree traversal, node types, selection, /inspectIterating layers; exploring any SDK object

What to expect​

By the end of Phase 1 you should be able to write a script that:

  • Runs without throwing errors when pasted into Affinity's script panel
  • Guards against no document being open (handles the case where Document.current returns null)
  • Walks every layer in the document
  • Logs the name, type, and visibility of each node
  • Uses inspect to explore any unknown object and map it back to the SDK primer
  • Works correctly on multi-spread (multi-page) documents

You will also understand why every SDK modification requires a command, why the selection must be read before setCurrentSpread is called, and why doc.layers gives you top-level nodes across all spreads while doc.layers.all descends recursively into every group. These are not edge cases — they are core SDK behaviours that every script author encounters within their first hour.