Skip to content

Writing a plugin

This guide builds two small plugins: lantern, a client plugin with a table effect, a menu entry and a tool, and ink-cobalt, a skin that adds an ink without any code. Both are complete in the repository under docs/examples/plugins/, and a test starts them through the real loader (server/taflor_server/tests/js/test_docs_examples.mjs), so what you read here runs.

Installing comes with M2

Taflor 0.3.0 loads only its bundled plugins. Installing your own (folder, zip, release, catalogue) comes with milestone M2. You can write and test a plugin now: Testing a plugin runs it against the same loader, ctx and registries the table page uses.

How plugins fit in explains kinds, tiers, namespaces and loading; this page is the hands-on part.

The folder

lantern/
├── table-plugin.json   the manifest
├── main.js             the entry module (client plugins only)
└── i18n/
    ├── en.json         labels; en is required
    └── de.json

The folder name is the plugin's id: lower case letters, digits and -, 2 to 32 characters. core is reserved.

The manifest

{
  "manifestVersion": 1,
  "id": "lantern",
  "version": "0.1.0",
  "kind": "client",
  "title": {"en": "Lantern", "de": "Laterne"},
  "description": {"en": "A glowing table effect, a menu entry and a tool: the plugin authoring guide's example."},
  "license": "CC0-1.0",
  "api": "^1.0",
  "entry": "main.js",
  "labels": {"en": "i18n/en.json", "de": "i18n/de.json"},
  "contributes": {
    "tableEffects": ["glow"]
  },
  "performance": [{"key": "glow", "cost": {"blink": "low", "gecko": "medium"}}]
}
  • manifestVersion, id, version (strict semver), kind and title (with en) are required; api is required for client and system plugins. Plugin API 1.0 is the current one, so "^1.0".
  • contributes declares, per registry, the short names the plugin registers. Registering a name that isn't declared throws.
  • performance declares the plugin's switches in the Performance tab: cost per engine (blink, gecko) is low, medium or high; "reduce effects" covers the key unless it says "reduced": false.
  • labels names one flat JSON file per language.
  • Unknown fields are refused, with an error naming the field. Extras of your own go in top-level fields named x-<name>.

The schema is manifest/v1.json in @taflor/protocol (protocol/schemas/manifest/v1.json); the testkit's manifestProblems checks a manifest against it and checks that every file it names exists.

The entry module

// The example plugin of the plugin authoring guide (docs/how-to/plugins.md): a table effect,
// a context menu entry and a tool with a key. Its test is
// server/taflor_server/tests/js/test_docs_examples.mjs.
import { effects } from "@taflor/api";

/** @type {import("@taflor/api").EffectDef} */
const glow = {
  label: "effect.glow",
  // One of the core's effect groups (effect-weather, -nature, -water, -sky, -magic, -tech).
  group: "effect-magic",
  fps: 30,
  // The plugin's own Performance switch (manifest `performance`); the core stills the effect
  // when it is off or effects are reduced.
  perfKey: "glow",
  create() {
    let motes = [];
    return {
      resize(view) {
        const random = effects.seeded(7);
        motes = Array.from({ length: effects.particleCount(40, view) }, () => ({
          x: random() * view.width,
          y: random() * view.height,
          phase: random() * Math.PI * 2,
        }));
      },
      frame(ctx, time) {
        for (const mote of motes) {
          ctx.globalAlpha = 0.4 + 0.4 * Math.sin(time * 2 + mote.phase);
          ctx.fillStyle = "#ffd27a";
          ctx.fillRect(mote.x, mote.y, 3, 3);
        }
        ctx.globalAlpha = 1;
      },
      still(ctx) {
        ctx.fillStyle = "#ffd27a";
        for (const mote of motes) ctx.fillRect(mote.x, mote.y, 3, 3);
      },
    };
  },
};

/** @type {import("@taflor/api").Plugin} */
export default {
  activate(ctx) {
    const t = ctx.plugin.t;
    // Stored as `lantern:glow`; the short name is declared in `contributes.tableEffects`.
    ctx.registry.tableEffects.register("glow", glow);

    // An entry of the empty table's context menu, in the default group `plugin`.
    ctx.ui.contextMenu.contribute("table", (_target, _selection, at) => [
      { label: t("menu.here"), action: () => ctx.ui.notify(t("lit", { x: Math.round(at.x), y: Math.round(at.y) })) },
    ]);

    // A tool: with `activate` and a `label` it gets a HUD button in the "tools" group, and
    // presses reach it only while it is the active tool. The key `l` switches it.
    ctx.tools.register({
      id: "lantern",
      slot: "draw",
      label: t("tool"),
      icon: "star",
      activate() {},
      deactivate() {},
      pointerDown(_event, at) {
        ctx.ui.notify(t("lit", { x: Math.round(at.x), y: Math.round(at.y) }));
        return true;
      },
      keys: [{ key: "l", run: () => ctx.tools.activate("lantern") }],
      escape: () => (ctx.tools.isActive("lantern") ? (ctx.tools.deactivate("lantern"), true) : false),
      readOnlyCancel: true,
    });
  },
};

The default export has activate(ctx) and, optionally, deactivate(). activate gets 5 seconds; if it throws or runs out of time, everything the plugin registered is rolled back. You don't need a deactivate to clean up: every registration returns a function that takes it back, and the loader takes them all back when the plugin stops. Use ctx.dispose(fn) for anything else you set up (timers, listeners on your own elements).

A plugin imports nothing from the core except @taflor/api, which the page maps by that name. ctx has the rest; core classes, DOM markup and module internals are not API.

Another plugin's code is reachable only through its entry, @plugin/<id>/<entry> (for example @plugin/lantern/main.js), and only for a plugin your manifest requires, because the page maps only the plugins in the game's lock. Its other modules are not API: once that plugin ships as a bundle, importing one of them by its path would load a second copy with its own state. If your plugin has helpers for others, export them from its entry.

Labels

ctx.plugin.t(key, vars) resolves the plugin's own keys, in the user's language, then English, then the key itself. {name} placeholders take vars. A registry def's label is a key in the same namespace: the effect above shows as "Lantern glow".

Registries

ctx.registry.<name>.register(shortName, def) adds an entry and returns what removes it. The table stores lantern:glow. Readers fall back to the registry's default for an id they don't know, so a table keeps working when your plugin is switched off.

Most registries take defs from code. Data files are limited to seven registries, whose defs the core keeps inert; since a skin or content plugin has no code, those are all it can fill. The registry reference lists all of them with their def shapes.

Rules worth knowing:

  • An animated def names a perfKey, one of the plugin's own performance keys (given short, stored as lantern:glow) or a core switch.
  • Picker groups come from the groups registry. Group ids are <catalogue>-<group> (effect-magic); the core registers the groups several plugins share, such as the effect groups effect-weather, -nature, -water, -sky, -magic and -tech.

Menus, the HUD and other mount points

Plugins never get the core's markup. They contribute entries, and where they show something of their own they get an empty element to fill (mount(el)). Every call returns what takes the entry back.

mount point call notes
context menu ctx.ui.contextMenu.contribute(where, build, {group, order}) where: "table", "object", "selection" (two or more objects) or a kind id. build(target, selection, at, access) returns items {label, action, danger?, checked?, separator?}. Groups in menu order: sheet, dice, marker, visibility, arrange, library, view, combat, light, plugin (default), credits, showcase, delete. No menu opens on a read-only table
Add menu ctx.ui.addMenu.contribute({id, label, icon, group, when?, run(at)}) groups: pieces, content, mark, sources
HUD ctx.ui.hud.button({id, label, icon, group?, gate?, toggle?, run}) groups create, settings, panels, tools (default), find
settings dialog ctx.ui.settings.tab({id, label, gate?, mount(el) → teardown?}) after the core's tabs; mount runs the first time the tab shows
appearance ctx.ui.looks.section({id, label, mount(el, prefs) → show?}) the user's own looks
inspector ctx.ui.inspector.fieldset(kindOrStar, {id, label, when?, mount(el, objects, update) → show?}) after the core's fieldsets; update(patch, final?) patches the objects the user may edit
drawer ctx.ui.drawer.open({id, label, gate?, mount(el) → teardown?}) the side drawer of the pickers, one at a time
modal ctx.ui.modal({id, isOpen}) while isOpen() is true the table's keys stay off
toast ctx.ui.notify(message, level) level "info" or "error"

Without gate or when, an entry shows while the table is not read-only. Labels are your label keys or plain text. mount must be synchronous: a returned promise is not awaited, and its teardown would be lost.

Tools and keys

The table's pointer and keyboard input runs through one ordered tool chain, and the built-in tools (select and pan in the core; the ruler, the pen and the marker tool in their bundled plugins) are in it like yours.

  • The chain asks tools by slot - modal, draw, object, background - then in registration order, the core's first: a press until a pointerDown returns true, a key until a binding takes it, Escape until an escape returns true.
  • A tool with activate gets presses, moves and releases only while it is the active tool. One tool is active at a time; ctx.tools.activate(id) switches, and a tool with a label also gets a HUD button in the tools group. A tool in the modal slot must have activate when it takes presses or Escape.
  • A key binding is {key, mod?, run}: key as in KeyboardEvent.key, mod ctrl (⌘ too), alt, shift, combined with +, or any. Without mod the key counts without Ctrl/⌘ and Alt. run returning false leaves the key to the rest of the chain.
  • No key reaches the chain while a text field has the focus, a ui.modal is open or a tool's modal() is true.
  • gate(access) decides whether the tool takes part (default: while the table is not read-only); readOnlyCancel: true ends it when the table turns read-only.

Key conflicts. If your binding takes a key that another owner's binding takes, yours stays off: the core keeps its keys, and of two plugins neither gets it. The conflict is reported to each plugin in it (plugin.error) and in the console. A management screen where the GM resolves conflicts comes with M2; until then, pick keys the core doesn't use, or alt+ combinations.

Hooks

ctx.hooks has three roles. The names come from a fixed catalogue (Hooks); a name outside it, or a hook used in another role, is refused.

// listener: observe; the return value is ignored
ctx.hooks.on("selection.changed", (ids) => { /* ... */ });

// filter: get a value, return it (changed or not); chained by ascending priority
ctx.hooks.filter("object.create", (props, { kind }) => (kind === "note" ? { ...props, name: props.name || "Note" } : props), { priority: 10 });

// provider: an exclusive slot; a second provider is a conflict
ctx.hooks.provide("dice.summary", (roll) => `Total ${roll.total}`);

Listener payloads are frozen copies. A filter that throws, or returns undefined or a promise, is skipped. In 0.3.0 the core doesn't call the catalogue's filters yet (object.create, menu.object, menu.table, token.overlays): a plugin may add them, and they take effect once the core calls them. Use ctx.ui.contextMenu for menu entries meanwhile. Object hooks never fire during drags, and not while a full state is applied (table.state follows it). The dice providers are explained in Systems and dice.

Drawing every frame

Plugins don't get per-frame events. Something that has to move each frame asks the shared scheduler:

const stop = ctx.frame.request((time, dt) => {
  // draw; time and dt in seconds
}, { fps: 30, perfKey: "glow", still: () => { /* one unmoving rendition */ } });

It pauses while the page is hidden and while the perfKey is off or effects are reduced (then still runs once), caps the callback at fps, and measures it: callbacks over 2 ms per frame on average show up in the Performance tab. Table effects (tableEffects) don't need this: the core's effect engine draws them.

A skin: data and CSS, no code

A pack without JavaScript is a skin (T1), not a client plugin. It can fill the registries that take data files and bring CSS. ink-cobalt adds one ink for text labels:

{
  "manifestVersion": 1,
  "id": "ink-cobalt",
  "version": "0.1.0",
  "kind": "skin",
  "title": {"en": "Cobalt ink", "de": "Kobalttinte"},
  "description": {"en": "One more ink for text labels, data and CSS without code: the plugin authoring guide's skin example."},
  "license": "CC0-1.0",
  "styles": ["inks.css"],
  "labels": {"en": "i18n/en.json", "de": "i18n/de.json"},
  "contributes": {
    "noteInks": {"names": ["cobalt"], "data": "inks.json"}
  }
}
{
  "cobalt": {"label": "ink.cobalt"}
}
/* A text label in this ink, and its tile in the inspector: the note carries the stored id. */
:is(.table-note, .table-inspector__ink)[data-note-ink="ink-cobalt:cobalt"] {
  --note-ink: #3d6fd8;
}

The data file maps short names to defs; the stored id, and so the value in the DOM, is ink-cobalt:cobalt. A skin may not declare entry, sheets, frames or csp: the manifest schema refuses them (on the server and in the testkit), and the page's loader refuses a skin that names an entry. Data for any registry outside the data-file list is refused by the server and the loader.

A table skin is a skin plugin too: a skins data file sets the core's colours, sizes and heading font, each value checked against its token's type (see skin tokens and the harbour-skin example). Taflor 0.3.0 checks and keeps table skins in the registry; the table page doesn't apply one yet. A skin's CSS may also colour the dice effects with --dice-<event> (one, six, explode, crit, megacrit): write them as #rrggbb, since a translucent colour or any other value falls back to the event's own colour.

The @taflor/api module

@taflor/api is the one core module a plugin imports. Its stable part is small: API_VERSION, Emitter and the type definitions (Plugin, PluginContext, EffectDef, ...), which editors read through JSDoc.

Experimental namespaces

The helper namespaces below exist for the bundled plugins and may change within API 1.x, until a third-party plugin needs them and they are settled. Use them if they save you work, pin the Taflor version you test against, and expect to adapt.

namespace for what
effects tableEffects particle counts, seeded randomness, sprites, drifting texture layers
frames tokenFrames, imageFrames frames.token draws along a token's outline, frames.image the image frame layer's contract and helpers
paths pathStyles, pathMotions, pathMarkers paths.decor: stamps along the curve, offset and jittered lines, motions locked to the server clock
pings pingStyles the ping's dot and ring markup and shape helpers
kinds bundled object kinds grid helpers, small UI builders, the dice, path and marker helpers, the server clock, the sound gate
TableObject object kinds the base class of a kind's objects

Object kinds

An object kind has two halves: what the server enforces is declared in the manifest (contributes.objectKinds: layer, snap, sizes, carriedByMaps, defaults, playerFields, and a JSON Schema for data), and the browser half is registered in code (ctx.registry.objectKinds.register(name, {Class, label, ...}), with a class that extends TableObject). The loader merges the two; a code def that repeats a manifest field with a different value throws. The bundled measure, paths, markers, gminfo, dice and media plugins are the worked examples.

The fields that reach into the table itself (attach, container, doubleClick, accessChanged, ownMenu) are for bundled plugins only; a plugin's kind with one of them is refused. Third-party object kinds need the install pipeline (M2) for the server to accept them on a table.

Shipping one module

Write and test your plugin as plain ES modules, which needs no build step. For a release, bundle the code into one module per entry. Every module is one more request each time a table loads, and the install review warns when an entry's graph loads more than 10. The host installs your files as they are and never bundles them itself.

esbuild does it in one command. Pin its version in your own package.json, so the same sources always give the same bytes:

npx esbuild main.js --bundle --format=esm --outfile=dist/main.js \
  --external:@taflor/api '--external:@plugin/*' \
  --sourcemap --charset=utf8 --legal-comments=inline
  • @taflor/api stays external: the page maps it to the core's module, and a copy inside your bundle would have registries and classes of its own. The same holds for @plugin/*, the entries of plugins you require.
  • Leave out --minify. Readable code gives readable stack traces in the GM's error reports, and the web server usually compresses the file anyway.
  • Point the manifest's entry at the bundle ("entry": "dist/main.js") and ship the .map next to it. Shipping the sources too is up to you.
  • The bundle lives in another folder than the sources, so import.meta.url changes its base. Use it only for files whose path you know relative to the bundle, or not at all.
  • Test what you ship: mountPlugin with dir imports the manifest's entry, so it runs the bundle (see Testing a plugin).

Taflor's own bundled plugins are bundled the same way when a release is built: the server runs them from their bundles in production and from their sources while you develop. The format of those release bundles is described in the design specification, which will be published later.