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’stypeasextensionType, and your own fields indata, which must be JSON.wrapbuilds the envelope andunwrapreads your element back out of it.pickBaseFieldscopies the fields every element has, such asid,positionandlayerId. validateDatachecksdatawhen a board is loaded and when an element arrives from another person.boundsreturns the area the element covers, in board units. Culling, selection, the minimap and exports use it. An envelope withsizegets resize handles from the select tool, soboundsmust readsize.renderdraws in board coordinates, with the camera already applied. It must depend only on its arguments, because the board caches each layer’s drawing.rendergets a fifth argument,context.context.themeis the theme of this drawing, which in an export can differ from the board’s. Usecontext.theme.tokensfor chrome such as handles, andcontext.theme.adapt(color)for colours stored on the element. Don’t keep the theme between calls.legacyTypeslists oldertypestrings the definition reads. A new type has none, sodecodeLegacyis 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.screenToWorldturns the pointer position into board coordinates.index: ''puts the new element on top of its layer, andversionstarts 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
onPointerCancelif it has one, andonPointerUpif not. To keep a pinch from leaving a marker, remove it inonPointerCancel.
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');
configureruns while the viewport is created. The types and tools it registers belong to that viewport and are removed when it is destroyed.namemust 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,exportImageandexportSVGon the viewport use its registry, so they know the marker type. The standaloneexportImageandexportSvgfunctions needelementRegistry: viewport.elementRegistry.- A board without the plugin keeps the markers in a saved board, logs a warning and doesn’t check their data.
SyncClientrunsmigrateon incoming elements with an olderdataVersionand 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. Whendatachanges shape, raisedataVersionand addmigrate, as EXTENDING.md section 4 shows.