API
Written from the source at each release. The fields of each chart are on its page.
Functions
| Function | From | Does |
|---|---|---|
createChart(host, spec, options?) | nervure | draws a chart and returns its handle |
registerChart(type, definition) | nervure | adds your own type |
createChart, load | nervure/lazy | fetches each type when drawn |
Chart | nervure/react | React component |
NervureChart | nervure/vue | Vue component |
chart | nervure/svelte | Svelte action |
<nervure-chart> | nervure/element | web component |
chartController | nervure/stimulus | Stimulus controller |
live, poll, events, socket, append | nervure/live | live data |
eventStream | nervure/server | event stream for your server |
createDashboard | nervure/dashboard | dashboards |
loadMap, listMaps | nervure/maps | map files |
sample, samples | nervure/samples | made-up data |
fromMermaid, parseMermaid | nervure/mermaid | Mermaid text as a spec |
types3d | nervure/3d | registers the 3D charts when imported |
typesThemes | nervure/themes | registers the theme charts when imported |
Options, handle and basic charts
ts
// Places
// Health
// Sport
/** Colours and fonts. Every field is optional when passed by the caller. */
export interface Theme {
strong: string;
label: string;
muted: string;
grid: string;
halo: string;
surface: string;
font: string;
/** Colours used when a series or a point has none. */ palette: string[];
}
/** A line across the chart: a target, an average, a date. */
export interface ReferenceLine {
value?: number;
/** Vertical line on a category (xy) or on the x axis (scatter). */ at?: string | number | Date;
axis?: number;
label?: string;
color?: string;
dashed?: boolean;
}
/** A shaded zone: a stretch of categories (`from`, `to`), or a range of values (`min`, `max`). */
export interface Zone {
/** A category, or a date on a time axis. */
from?: string | number | Date;
to?: string | number | Date;
min?: number;
max?: number;
axis?: number;
label?: string;
color?: string;
/** 0.08 by default. */
opacity?: number;
}
/** A note pinned on the chart. `at` is a category (xy) or an x value (scatter). */
export interface Annotation {
at: string | number | Date;
value: number;
text: string;
color?: string;
axis?: number;
}
/**
* Colour worked out from a value: `(value, index, category) => colour`, for example red below zero.
* Only from code: a JSON spec (the editor, the MCP server) keeps plain colour texts.
*/
/** Shape of a point: on lines, areas, scatter and radar charts, and in the legend. */
/** How the points of a series are drawn. */
export interface PointStyle {
/** `circle` by default. */
shape?: PointShape;
/** Radius in pixels, 4 by default. */
size?: number;
}
export interface Series {
name: string;
data: (number | null)[];
/** A colour, or a function of each value (`(value, index, category) => colour`, from code only). */
color?: string | ColorFn;
kind?: 'line' | 'bar' | 'area' | 'band';
/** Lower bound of a `band` (`data` is the upper one). */
low?: (number | null)[];
/** Colour of one point or bar, when it differs from the series; or a function of each value (from code only). */
colors?: (string | undefined)[] | ColorFn;
/** With `stacked`: bars of the same `stack` pile up, other stacks stand beside them in the category. */
stack?: string;
dashed?: boolean;
gradient?: boolean;
/** Points on a line or an area: `false` hides them, `{ shape, size }` changes them. */
dots?: boolean | PointStyle;
showLabel?: boolean;
/** Text of each label, instead of the formatted value. */
labels?: (string | undefined)[];
/** Joins points with straight segments (default), a smooth curve or steps. */
curve?: 'linear' | 'smooth' | 'step';
/** Index in `axes`. */
axis?: number;
legend?: boolean;
width?: number;
opacity?: number;
/**
* Missing values (`null`) of a line or an area: `break` cuts the line (default),
* `join` links the points on each side, `zero` draws them at 0.
*/
gaps?: 'break' | 'join' | 'zero';
/** Stretches of the line drawn another way, by index: a forecast in dashes from index 9. */
segments?: Segment[];
}
/** A stretch of a line or an area, from the point at index `from` to the one at `to` (the last by default). */
export interface Segment {
from: number;
to?: number;
dashed?: boolean;
color?: string;
/** Opacity of the line, and of the area under it. */
opacity?: number;
/** Said after the value, in the tooltip and to screen readers: `forecast`. */
label?: string;
}
/** Range, ticks and grid of a value axis. */
export interface AxisScale {
/** `log` ignores zero and negative values. */ scale?: 'linear' | 'log';
/** Fixed ends: the data cannot move them. */
min?: number;
max?: number;
/** Ends the axis reaches at least; data beyond them still widens it. */
suggestedMin?: number;
suggestedMax?: number;
/** Gap between two ticks, such as 5 (linear scale). */
step?: number;
/** About how many ticks (linear scale). */
ticks?: number;
/** A function, or options: { currency: 'EUR', compact: true }. */
format?: Format;
/** Text of each tick, before `format`: (value, index) => string. */
tickFormat?: (value: number, index: number) => string;
/** Grid lines of this axis: `false` hides them; `dashed` and `color` change them. */
grid?: boolean | { dashed?: boolean; color?: string };
title?: string;
}
export interface Axis extends AxisScale {
side?: 'left' | 'right';
}
/** Where the legend goes, and what a click on a name does. */
export interface LegendOptions {
/** `bottom` by default. `left` and `right` fall back to `bottom` on narrow charts. */
position?: 'top' | 'bottom' | 'left' | 'right';
align?: 'start' | 'center' | 'end';
/** Called with the name and the state it is about to take; return `false` to keep it as it is. */
onClick?: (name: string, visible: boolean) => unknown;
}
/** A name of the legend, for a legend written outside the chart. */
export interface LegendItem {
name: string;
color: string;
visible: boolean;
}
/** What a mark stands for: given to `onClick`, `onHover` and the tooltip options. */
export interface ChartPoint {
/** Type of the chart: `xy`, `pie`… */
type: string;
/** Series or group of the mark, when the chart has several. */
series?: string;
/** Stack of a bar (`xy` with `stack` on its series). */
stack?: string;
/** Label of the segment of a line the mark is on (`xy` with `segments`). */
segment?: string;
/** Category, name or label of the mark. */
label: string;
value?: number;
/** Place of the mark in its series (or among the categories); -1 when the chart does not say. */
index: number;
/** The item of the spec the mark comes from, when there is one. */
item?: unknown;
color?: string;
/** What the tooltip writes by default: a title, then lines. */
title: string;
rows: { name: string; value?: string; color?: string }[];
}
export interface ChartPointEvent extends ChartPoint {
/** The pointer or keyboard event behind it. */
event: Event;
}
export interface TooltipOptions {
/** Lines of the tooltip: the first is its title. Written as text. */
format?: (point: ChartPoint) => string | string[];
/**
* HTML of the tooltip, trusted as it is: escape every value that comes from data with `escape`.
* Scripts and event attributes are removed.
*/
html?: (point: ChartPoint, escape: (text: string) => string) => string;
/** Side of the pointer where the tooltip opens; `auto` keeps it inside the chart. */
position?: 'auto' | 'top' | 'bottom' | 'left' | 'right';
}
/** Rectangle in the coordinates of the SVG. */
export interface Area {
x: number;
y: number;
width: number;
height: number;
}
/** What a plugin receives at each drawing. */
export interface PluginContext {
svg: SVGSVGElement;
width: number;
height: number;
/** Where the data is drawn (inside the axes); the whole drawing for charts that do not say. */
area: Area;
/** Middle and radius of the hole of a donut, a pie or a gauge. */
hole?: { x: number; y: number; r: number };
spec: ChartSpec;
theme: Theme;
/** True when the spec has no value to show. */
empty: boolean;
/** Layers of the plugins: under the chart (grid and marks), and above it. Emptied at each drawing. */
below: SVGGElement;
above: SVGGElement;
/** Adds an SVG element to a layer (`above` by default); `text` is written as text. */
add: (
tag: string,
attributes: Record<string, string | number | undefined>,
layer?: 'below' | 'above',
text?: string,
) => SVGElement;
}
/** Draws something more on every chart it is given to. See `nervure/plugins`. */
export interface NervurePlugin {
/** Name, unique: a plugin registered twice runs once. */
id: string;
beforeDraw?: (context: PluginContext) => void;
afterDraw?: (context: PluginContext) => void;
onDestroy?: (context: PluginContext) => void;
}
export interface DecorateContext {
svg: SVGSVGElement;
width: number;
height: number;
theme: Theme;
}
export interface Base {
title?: string;
description?: string;
/** Writes every figure: a function, or options such as { currency: 'EUR', compact: true }. */
format?: Format;
/** Text written above the drawing (part of the exports). */
heading?: string;
subheading?: string;
/** Pixels kept free above the drawing, for a header added by `decorate`. */
insetTop?: number;
/** Pixels kept free under the drawing (a watermark). */
insetBottom?: number;
/** Adds your own elements (header, watermark); they are part of the exports. */
decorate?: (context: DecorateContext) => void;
}
export interface XYSpec extends Base {
type: 'xy';
/** Names, or dates: Date objects, ISO texts (`2024-03-01`), or timestamps with `xScale: 'time'`. */
categories: (string | number | Date)[];
/**
* `time`: categories are dates, placed by time (uneven gaps drawn to scale), with ticks by span.
* Chosen alone when every category is a Date or an ISO date; `category` keeps them evenly spaced.
*/
xScale?: 'category' | 'time';
series: Series[];
axes?: Axis[];
horizontal?: boolean;
/** `percent`: each category fills the axis, its bars as shares of 100 %. Series with a `stack` pile up by group. */
stacked?: boolean | 'percent';
/** Rounded corners of the bars, in pixels: 4 by default, 0 for square bars. */
radius?: number;
/** Share of a category taken by its bars, from 0 to 1: 0.72 by default. */
barWidth?: number;
/** Horizontal bars: first category at the top (default) or at the bottom. */
reverse?: boolean;
totals?: boolean;
legend?: boolean | LegendOptions;
labelWidth?: number;
grid?: boolean | 'dashed';
/** Title under the horizontal axis. */
xTitle?: string;
/** Angle of the category labels (vertical charts), for example -45. */
labelAngle?: number;
lines?: ReferenceLine[];
annotations?: Annotation[];
/** Shaded zones behind the series: a period, a forecast, a range of values. */
zones?: Zone[];
/** Drag on the chart to look closer, double click to come back (vertical charts). */
zoom?: boolean;
/** No axis, no legend, no margin: a sparkline. */
bare?: boolean;
/**
* Long series: keeps the lowest and highest points of each stretch, so peaks stay.
* `true`: about one point every 3 pixels; a number: the most points kept. Zooming in brings the detail back.
*/
thin?: boolean | number;
}
export interface PieSpec extends Base {
type: 'pie';
data: { name: string; value: number; color?: string }[];
inner?: number;
outer?: number;
labels?: boolean;
/** Outside label of a slice. */ label?: (name: string, value: number, percent: number) => string;
/** Text in the hole of a donut. */ center?: string;
/** Colour of each slice from its value, `(value, index, name) => colour` (from code only); a slice's own `color` wins. */
color?: ColorFn;
/** Drawn instead of the labels around the pie when they have no room; `true` or options: always; `false`: never. */
legend?: boolean | LegendOptions;
}
export interface RadarSpec extends Base {
type: 'radar';
indicators: { name: string; max?: number }[];
series: {
name: string;
values: number[];
color?: string;
/** Points on the corners: `true`, or `{ shape, size }`. */ dots?: boolean | PointStyle;
}[];
/** Drawn with two series or more; `false` hides it. */
legend?: boolean | LegendOptions;
}
export interface GaugeSpec extends Base {
type: 'gauge';
value: number;
max?: number;
color?: string;
/** Mark on the arc; several marks with a list (the first one is thicker). */ target?: number | number[];
/** Size of the figure in pixels; it follows the size of the gauge by default. */
figureSize?: number;
name?: string;
unit?: string;
}
export interface ScatterPoint {
x: number;
y: number;
r?: number;
label: string;
color?: string;
id?: string;
/** Radius in pixels, instead of `r`. */ radius?: number;
group?: string;
/** Shape of this point, instead of the chart's `shape`. */ shape?: PointShape;
[key: string]: unknown;
}
export interface ScatterSpec extends Base {
type: 'scatter';
data: ScatterPoint[];
/** A colour, or a function `(y, index, label) => colour` (from code only); a point's own `color` wins. */
color?: string | ColorFn;
/** Shape of the points: `circle` by default. The canvas (`render`) always paints circles. */
shape?: PointShape;
xLabel?: string;
yLabel?: string;
/** Names written above the points. */
labels?: boolean;
legend?: boolean | LegendOptions;
lines?: ReferenceLine[];
annotations?: Annotation[];
/** Range, ticks, format and grid of each axis. */
xAxis?: AxisScale;
yAxis?: AxisScale;
/** Axes crossing at zero, inside the drawing, instead of along its edges. */
center?: boolean;
tooltip?: (point: ScatterPoint, format: (v: number) => string) => string[];
onPointClick?: (point: ScatterPoint) => void;
/**
* Points as SVG circles, or painted on one canvas: much faster with tens of thousands of points.
* `auto` (default) uses a canvas above 3000 points, where there is one. Axes, legend and labels stay SVG.
*/
render?: 'svg' | 'canvas' | 'auto';
}
export interface Item {
name: string;
value: number;
color?: string;
label?: string;
id?: string;
}
interface Clickable {
onItemClick?: (id: string) => void;
}
export interface TreemapSpec extends Base, Clickable {
type: 'treemap';
data: Item[];
}
export interface PackSpec extends Base, Clickable {
type: 'pack';
data: Item[];
}
export interface FunnelSpec extends Base, Clickable {
type: 'funnel';
data: Item[];
/** Share of the first step (default) or of the previous one. */ rate?: 'first' | 'previous' | false;
}
/** Steps from a start to an end; `total: true` restarts from zero. */
export interface WaterfallSpec extends Base {
type: 'waterfall';
data: { name: string; value: number; total?: boolean; color?: string }[];
up?: string;
down?: string;
totalColor?: string;
}
export interface HeatmapSpec extends Base {
type: 'heatmap';
columns: string[];
rows: string[];
values: (number | null)[][];
color?: string;
/** Values written in the cells. */ labels?: boolean;
labelWidth?: number;
}
export interface TimelineBar {
row: string;
start: number;
end: number;
color?: string;
label?: string;
detail?: string;
}
export interface TimelineMark {
row: string;
at: number;
color?: string;
label?: string;
id?: string;
}
/** Dates are timestamps in milliseconds. */
export interface TimelineSpec extends Base, Clickable {
type: 'timeline';
rows: string[];
bars?: TimelineBar[];
marks?: TimelineMark[];
now?: number;
nowLabel?: string;
labelWidth?: number;
formatDate?: (t: number) => string;
}
export interface TreeNode {
name: string;
color?: string;
children?: TreeNode[];
}
/** Radial tree; a click on a node folds or unfolds it. */
export interface TreeSpec extends Base {
type: 'tree';
root: TreeNode;
/** Deepest level whose names are written. */ labelDepth?: number;
}
/** A type added with `registerChart`. */
export interface CustomSpec extends Base {
type: `custom:${string}`;
[key: string]: unknown;
}
| XYSpec
| PieSpec
| RadarSpec
| GaugeSpec
| ScatterSpec
| TreemapSpec
| PackSpec
| FunnelSpec
| WaterfallSpec
| HeatmapSpec
| TimelineSpec
| TreeSpec;
| BasicCharts
| FinanceCharts
| DistributionCharts
| ComparisonCharts
| CircularCharts
| FlowCharts
| DiagramCharts
| GridCharts
| MapCharts
| DomainCharts /* families */
| TimeCharts
// Places
| PlacesCharts
// Health
| HealthCharts
| SportCharts
// 3D, drawn once `nervure/3d` is imported
| ThreeDCharts
// Theme charts (weather, nature, energy; everyday life), drawn once `nervure/themes` is imported
| EnergyThemeCharts
| LivingCharts
| CustomSpec;
'linear' | 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'bounce' | 'elastic' | (string & Record<never, never>);
export interface AnimationOptions {
/** 2 is twice as fast. */
speed?: number;
/** Milliseconds for each element, instead of the timing of the chart. */
duration?: number;
/** Milliseconds before the first element. */
delay?: number;
/** `false`: everything moves together. */
stagger?: boolean;
/** A named easing (`bounce` and `elastic` overshoot), or any CSS easing. */
easing?: Easing;
/** `fade` replaces movement by a fade. */
effect?: 'default' | 'fade';
/** Plays again and again, with a pause between two runs; never when the reader asks for less motion. */
loop?: boolean;
/**
* How the lines of `xy` charts come in: traced along their length (default),
* `grow` up from the axis, or `draw` from left to right at an even pace, points and areas with them.
*/
line?: 'trace' | 'grow' | 'draw';
/** When to play: at once, when first seen on screen, or by `play()`. */
start?: 'load' | 'visible' | 'manual';
}
/** `md`: the data as a Markdown table. `figma`: an SVG made for Figma; the menu copies it, `download` saves it. */
export interface ExportOptions {
/** Written in the file only. */
title?: string;
subtitle?: string;
caption?: string;
background?: string;
padding?: number;
/** PNG only. */
scale?: number;
/**
* SVG made to be pasted in Figma: layers named after the parts of the chart, plain colours instead of CSS
* variables and `currentColor`, text with its font family, size and weight.
*/
figma?: boolean;
}
export interface ToolbarOptions {
formats?: readonly ExportFormat[];
label?: string;
labels?: Partial<Record<ExportFormat, string>>;
icon?: string;
fileName?: string;
options?: ExportOptions;
}
export interface RenderOptions {
/** A named theme, or your own colours. Stylesheets can also set `--nervure-*`. */
theme?: ThemeInput;
locale?: string;
/** `false` draws at once. */
animation?: boolean | AnimationOptions;
/** Short form of `animation`. */
animate?: boolean;
/** The reader shows or hides a series in the legend. */
onToggle?: (name: string, visible: boolean) => void;
/** Zoom and drag of the whole drawing, for any chart. Lines, prices and maps also have `spec.zoom`. */
zoom?: boolean;
/** Export button. */
toolbar?: boolean | ToolbarOptions;
/**
* Linked cursors: charts of the same group show the same category (or x value) under the pointer.
* Any name; leave the group with `destroy`.
*/
sync?: string;
/** With `sync`: zooming an `xy` chart with `zoom` shows the same categories in the others. */
syncZoom?: boolean;
/** Reading with the keyboard (default `true`): Tab reaches the chart, arrows go from mark to mark. Read once. */
keyboard?: boolean;
/**
* The data as an HTML table, formatted like the chart: under the host (`true`, `below`),
* beside the drawing, or behind a Table button of the toolbar (`toggle`). Never in the SVG export.
*/
table?: boolean | 'below' | 'beside' | 'toggle';
/** A click (or Enter) on a mark: a bar, a slice, a point, a cell, a category of a line. */
onClick?: (point: ChartPointEvent) => void;
/** The pointer reaches a mark; `null` when it leaves the marks. */
onHover?: (point: ChartPointEvent | null) => void;
/** `false`: no tooltip (`onHover` still works). Or how to write and place it. */
tooltip?: boolean | TooltipOptions;
/** Run at each drawing of this chart, after those of `registerPlugin`. */
plugins?: NervurePlugin[];
}
export interface ChartHandle {
readonly svg: SVGSVGElement;
/** Draws another spec, with its entrance animation. */
update(spec: ChartSpec, options?: RenderOptions): void;
/** Draws new data at once, without animation (live charts). */
refresh(spec: ChartSpec): void;
resize(): void;
/** Plays the entrance animation (again). */
play(): void;
/** Colour of a series or of an item, by name. Kept until `resetColors`. */
setColor(name: string, color: string): void;
setPalette(colors: string[]): void;
resetColors(): void;
/** Adds a note or a line (`xy` and `scatter`). Kept until `clearNotes`. */
addAnnotation(note: Annotation): void;
addLine(line: ReferenceLine): void;
clearNotes(): void;
/** Shows or hides a series, as the legend does. */
toggle(name: string, visible?: boolean): void;
/** Names of the legend with their colour and state, to write a legend of your own (with `toggle`). */
legendItems(): LegendItem[];
/** Opens the tooltip of a mark: a series name (or its place among the series), and the index of the mark. */
showTooltip(series: string | number, index: number): void;
hideTooltip(): void;
/** Rings a mark as the keyboard does, until `setActive(null)`. */
setActive(series: string | number | null, index?: number): void;
/** Shows the categories from one index to another (`xy` with `zoom`). */
zoom(from: number, to: number): void;
resetZoom(): void;
destroy(): void;
/** Standalone SVG document. */
toSVG(options?: ExportOptions): string;
toPNG(options?: ExportOptions | number, background?: string): Promise<Blob>;
toCSV(): string;
/** The data as a Markdown table, under the title of the chart. */
toMarkdown(): string;
/** Puts the Figma SVG on the clipboard, as `image/svg+xml` and as text: paste it in Figma. */
copyForFigma(options?: ExportOptions): Promise<void>;
/** Saves a file on the reader's computer. */
download(format: ExportFormat, fileName?: string, options?: ExportOptions): Promise<void>;
}Live data
ts
export type LiveStatus = 'connecting' | 'live' | 'paused' | 'retrying' | 'stopped';
/** Where data comes from. `start` is called again after an error; it returns how to stop. */
export interface Source<T> { … }
export interface PollOptions<T> { … }
/** Calls `url` (or your function) every `every` milliseconds. The next call starts after the previous answer. */
export function poll<T = unknown>(
/** Server-sent events: one JSON message per event. */
export function events<T = unknown>(
/** WebSocket; `hello` is sent on opening (a subscription, for example). */
export function socket<T = unknown>(
export interface LiveOptions<T> { … }
export interface Live { … }
/** Feeds a chart from a source. Retries with growing waits, and draws the last message only. */
export function live<T>(chart: ChartHandle, initial: ChartSpec, source: Source<T>, o: LiveOptions<T>): Live { … }
/** Adds one point to an `xy` spec and keeps the last `keep` ones. `values` is by series name; a missing one is a gap. */
export function append(spec: XYSpec, category: string, values: Record<string, number | null>, keep = 60): XYSpec { … }