Usage guidesPlugins

Custom Plugins

Implement, register, and use a click counter plugin

This example adds a click counter to the graph container. The count increases when you click a node or the button on the panel.

Implement the plugin

Use a factory to create the plugin. Keep the count, panel, and unsubscribe callback inside the factory so each plugin instance has its own state.

MethodWhat it does in the example
init(context, options)Reads options such as the caption.
mount(container)Adds the panel to the graph container and subscribes to node clicks.
destroy()Unsubscribes from clicks and removes the panel. Also release any timers or other resources the plugin creates here.

Register and use the plugin

Register the factory with register('plugin', 'docs-counter', createCounter), then add { type: 'docs-counter', caption: 'Clicks' } to plugins. See the plugin overview for the graph configuration.

Code example

Click a node or Plugin +1 to increment the count. Click Render again to reset the count to zero. The next node click still increments it by one.

Loading example…
Button or node clicks increment once. Render again remounts at zero; repeated remounts must not duplicate subscriptions
export function createCounter(): PluginExtension<CounterOptions> {
  let ui: ReturnType<typeof createDemoPanel> | undefined;
  let unsubscribe: (() => void) | undefined;
  let settings: CounterOptions | undefined;
  let count = 0;
  const report = () => ui?.setStatus(`${settings?.caption ?? 'Clicks'}: ${count}`);
  const increment = () => { count++; report(); };
  return {
    init(_context, options) { settings = options; },
    mount(container) {
      ui = createDemoPanel(container);
      ui.addAction('Plugin +1', increment);
      if (settings?.onRenderAgain) ui.addAction('Render again', settings.onRenderAgain);
      report();
      unsubscribe = settings?.subscribe?.(increment);
    },
    destroy() {
      unsubscribe?.(); unsubscribe = undefined;
      ui?.destroy();
      ui = undefined;
      settings = undefined;
    },
  };
}
register('plugin', NAME, () => createCounter());

Open the full code to see how the application provides a subscribe option. It calls graph.on() and returns a function that calls graph.off(). If a click counts more than once after remounting, check that destroy() calls the unsubscribe function.

See PluginExtension for the full contract.