Skip to content

Plugins ​

A plugin draws something more on a chart, at each drawing: a frame, a text in the hole of a donut, a message when there is no data.

ts
import { createChart, registerPlugin } from 'nervure';
import { centerLabel, emptyState, plotAreaBorder } from 'nervure/plugins';

// on one chart
createChart(host, donut, { plugins: [centerLabel({ text: '1,284', sub: 'orders' })] });

// on every chart drawn from now on
const remove = registerPlugin(emptyState({ text: 'Nothing to show yet' }));
remove(); // when no longer wanted

nervure/plugins is a file of its own: the main bundle does not grow when you do not use it.

Ready-made ​

PluginDrawsOptions
plotAreaBorder()a frame around the area where the data is drawn, inside the axescolor, width, radius, dashed, fill (behind the marks)
centerLabel({ text })a text in the hole of a donut, a pie or a gauge; in the middle for other chartstext, sub (a line under it), color, size; text and sub can be functions of the context
emptyState()a message in the middle when the spec has no valuetext (No data), color

Your own ​

A plugin is an object with an id and up to three hooks:

ts
import type { NervurePlugin } from 'nervure';

const watermark: NervurePlugin = {
  id: 'watermark',
  afterDraw(c) {
    c.add('text', {
      x: c.area.x + c.area.width - 6,
      y: c.area.y + c.area.height - 6,
      'text-anchor': 'end',
      'font-size': 10,
      'font-family': c.theme.font,
      fill: c.theme.muted,
    }, 'below', 'Draft');
  },
};
HookWhen
beforeDraw(context)the drawing is empty; area is still the whole drawing
afterDraw(context)the chart is drawn; area and hole are known
onDestroy(context)destroy(): let go of what you hold

The context:

FieldHolds
svg, width, heightthe SVG of the chart and its size in pixels
area{ x, y, width, height } where the data is drawn (inside the axes of xy, scatter, heatmap, waterfall…, the circle of a pie or a radar); the whole drawing for the other charts
hole{ x, y, r } of the hole of a donut, a pie or a gauge
spec, themethe spec drawn, and the colours and font in use
emptytrue when the spec has no value
below, abovetwo layers, under the chart (grid and marks) and above it, emptied at each drawing
add(tag, attributes, layer?, text?)adds an SVG element to a layer, above by default; text is written as text
  • Use c.theme colours: plugins then follow the light and dark themes.
  • What a plugin draws is part of the SVG and PNG exports, and of renderToSVG.
  • One plugin by id: a plugin given to a chart replaces a registered one with the same id.
  • Elements above the marks should take pointer-events="none", so the tooltip keeps working under them.