Field Notes

Writing a plugin

By the end of this page you have your own element type on the board, a tool that places it, and one plugin that installs both.

A plugin adds element types, tools, render hooks, actions and services to a board when its viewport is created. This page builds a first one: a marker element and a tool that places markers. EXTENDING.md covers the rest of the extension API.

Define an element type

interface Marker extends BaseElement {
  type: 'my-app:marker';
  label: string;
  size: Size;
}

const markerDefinition: ElementTypeDefinition<Marker> = {
  type: 'my-app:marker',
  legacyTypes: [],
  decodeLegacy: () => {
    throw new Error('my-app:marker has no legacy types');
  },
  validateData: (data) => typeof data['label'] === 'string',
  wrap: (el): ExtensionElementEnvelope => ({
    ...pickBaseFields(el),
    type: 'extension',
    extensionType: 'my-app:marker',
    size: el.size,
    data: { label: el.label },
  }),
  unwrap: (el) => ({
    ...pickBaseFields(el),
    type: 'my-app:marker',
    label: String(el.data['label']),
    size: el.size ?? { w: 40, h: 40 },
  }),
  bounds: (el) => ({ x: el.position.x, y: el.position.y, w: el.size.w, h: el.size.h }),
  render(ctx, el) {
    ctx.fillStyle = '#2f55a4';
    ctx.fillRect(el.position.x, el.position.y, el.size.w, el.size.h);
    ctx.fillStyle = '#ffffff';
    ctx.font = '14px sans-serif';
    ctx.fillText(el.label, el.position.x + 6, el.position.y + 24);
  },
};
  • The board stores your element as an envelope: type: 'extension', your definition’s type as extensionType, and your own fields in data, which must be JSON. wrap builds the envelope and unwrap reads your element back out of it. pickBaseFields copies the fields every element has, such as id, position and layerId.
  • validateData checks data when a board is loaded and when an element arrives from another person.
  • bounds returns the area the element covers, in board units. Culling, selection, the minimap and exports use it. An envelope with size gets resize handles from the select tool, so bounds must read size.
  • render draws in board coordinates, with the camera already applied. It must depend only on its arguments, because the board caches each layer’s drawing.
  • render gets a fifth argument, context. context.theme is the theme of this drawing, which in an export can differ from the board’s. Use context.theme.tokens for chrome such as handles, and context.theme.adapt(color) for colours stored on the element. Don’t keep the theme between calls.
  • legacyTypes lists older type strings the definition reads. A new type has none, so decodeLegacy is never called.
  • An SVG export leaves the element out unless the definition has emitSvg.

Add a tool

const markerTool: Tool = {
  name: 'marker',
  onPointerDown(state, ctx) {
    ctx.store.add(
      markerDefinition.wrap({
        id: crypto.randomUUID(),
        type: 'my-app:marker',
        position: ctx.camera.screenToWorld({ x: state.x, y: state.y }),
        index: '',
        version: 1,
        locked: false,
        layerId: ctx.activeLayerId ?? '',
        label: 'A1',
        size: { w: 40, h: 40 },
      }),
    );
  },
  onPointerMove: () => undefined,
  onPointerUp: () => undefined,
};
  • ctx.camera.screenToWorld turns the pointer position into board coordinates. index: '' puts the new element on top of its layer, and version starts at 1.
  • Each pointer gesture is one history transaction, so whatever a tool changes between press and release undoes in one step.
  • When a second finger turns the gesture into a pinch, the tool gets onPointerCancel if it has one, and onPointerUp if not. To keep a pinch from leaving a marker, remove it in onPointerCancel.

Install it with a plugin

export const markerPlugin: ViewportPlugin = {
  name: 'my-app:markers',
  configure(ctx) {
    ctx.registerElementType(markerDefinition);
    ctx.registerTool(markerTool);
  },
};

const viewport = new Viewport(document.getElementById('board')!, {
  tools: 'default',
  plugins: [markerPlugin],
});
viewport.setTool('marker');
  • configure runs while the viewport is created. The types and tools it registers belong to that viewport and are removed when it is destroyed.
  • name must be unique on the viewport. A second plugin with the same name is skipped with a warning.
  • A plugin that throws is rolled back with a warning, and the others carry on. With required: true, the viewport throws instead.
  • start(ctx) gives a plugin the running board, and its returned handle can save plugin state with the board. EXTENDING.md section 6 has the details.

Save and share markers

  • exportJSON, loadJSON, exportImage and exportSVG on the viewport use its registry, so they know the marker type. The standalone exportImage and exportSvg functions need elementRegistry: viewport.elementRegistry.
  • A board without the plugin keeps the markers in a saved board, logs a warning and doesn’t check their data.
  • SyncClient runs migrate on incoming elements with an older dataVersion and keeps newer data as is. A peer on an older definition can still edit newer data in its old shape, so everyone in a room should run the same version of the definition. When data changes shape, raise dataVersion and add migrate, as EXTENDING.md section 4 shows.