Synertech Web/ui v0.57.5 Site Storybook

Documentation / Dashboards

Chart foundation

Server-compatible@synertech/ui

The shared foundation of the charts, rendered as plain SVG, with no charting dependency: the frame (ChartContainer, measured by useChartSize), the legend, the tooltip, the twin data table (ChartTableView), the colours and the mechanisms every chart of the kit shares — to configure those charts or to build your own.

The colours live in src/styles/index.css, overridable in one CSS block: eight categorical slots (getSeriesColor) that say which one — the colour follows a series’ position in series, never its rank — and ramps that say how much (createSequentialScale, createDivergingScale, mixed in OKLab). Never paint a magnitude with the categorical palette, and put a ChartScaleLegend on screen as soon as a ramp is.

The charts also share: overlay, the escape hatch that hands over the resolved geometry (ChartPlotContext, coordinates relative to the plot area); annotations to say why the line moved; patterns for readers the hue fails; maxPoints, which thins only the drawing (LTTB) past CHART_POINT_BUDGET; brush; and ChartStatusProps — loading, emptyState, error and onRetry, three exclusive states: an error is never an empty chart.

Examples

A home-made chart on the foundation

ChartContainer measures its width (through useChartSize) and passes it as a render prop; getSeriesColor, ChartLegend and ChartTableView do the rest.

Open in a tab
import { ChartContainer, ChartLegend, ChartTableView, getSeriesColor, toLegendItems } from "@synertech/ui";

const monthly = [
  { month: "Jan", web: 18400, store: 12200, target: 30000 },
  { month: "Fév", web: 21100, store: 13050, target: 32000 },
  { month: "Mar", web: 19800, store: 13600, target: 33000 },
  { month: "Avr", web: 26500, store: 15100, target: 36000 },
  { month: "Mai", web: 29200, store: 15800, target: 40000 },
  { month: "Juin", web: 34800, store: 17400, target: 46000 },
];

const channels = [
  { key: "web", label: "En ligne" },
  { key: "store", label: "Magasin" },
];

export function CustomChart() {
  const max = Math.max(...monthly.map((row) => row.web + row.store));

  return (
    <ChartContainer
      title="Ventes par canal"
      height={160}
      legend={<ChartLegend items={toLegendItems(channels)} />}
      table={<ChartTableView data={monthly} series={channels} xKey="month" xLabel="Mois" />}
      tableView="toggle"
    >
      {({ width, height }) => {
        const step = width / monthly.length;
        return (
          <svg width={width} height={height} role="img" aria-label="Ventes par canal">
            {monthly.map((row, index) => {
              const webHeight = (row.web / max) * height;
              const storeHeight = (row.store / max) * height;
              return (
                <g key={row.month} transform={`translate(${index * step + step / 4}, 0)`}>
                  <rect
                    y={height - webHeight}
                    width={step / 2}
                    height={webHeight}
                    fill={getSeriesColor(0)}
                  />
                  <rect
                    y={height - webHeight - storeHeight}
                    width={step / 2}
                    height={storeHeight}
                    fill={getSeriesColor(1)}
                  />
                </g>
              );
            })}
          </svg>
        );
      }}
    </ChartContainer>
  );
}

Sequential and diverging ramps

A scale is a value → colour function; onDark says whether text placed on it should be light. ChartScaleLegend is mandatory beside it.

Open in a tab
import { ChartScaleLegend, createDivergingScale, createSequentialScale } from "@synertech/ui";

const retention = [92, 81, 74, 66, 58, 51];

const variance = [-12, -4, 0, 3, 9, 15];

export function ColorRamps() {
  const sequential = createSequentialScale([0, 100]);
  const diverging = createDivergingScale([-15, 15], { steps: 5 });
  const textOn = (dark: boolean) =>
    dark ? "text-gray-50 dark:text-gray-900" : "text-gray-900 dark:text-gray-50";

  return (
    <div className="flex flex-col gap-4">
      <div className="flex gap-1">
        {retention.map((value, index) => (
          <span
            key={index}
            className={`flex-1 rounded py-2 text-center text-xs ${textOn(sequential.onDark(value))}`}
            style={{ backgroundColor: sequential(value) }}
          >
            {value} %
          </span>
        ))}
      </div>
      <ChartScaleLegend scale={sequential} label="Rétention (%)" />
      <div className="flex gap-1">
        {variance.map((value, index) => (
          <span
            key={index}
            className={`flex-1 rounded py-2 text-center text-xs ${textOn(diverging.onDark(value))}`}
            style={{ backgroundColor: diverging(value) }}
          >
            {value > 0 ? `+${value}` : value} %
          </span>
        ))}
      </div>
      <ChartScaleLegend scale={diverging} label="Écart au budget (%)" />
    </div>
  );
}

The escape hatch: overlay

The function receives a ChartPlotContext (xAt, yAt, categoryCenters, bandwidth…) and draws over the bars. Reserving the top margin is up to you.

Open in a tab
import { BarChart, type ChartPlotContext } from "@synertech/ui";

const monthly = [
  { month: "Jan", web: 18400, store: 12200, target: 30000 },
  { month: "Fév", web: 21100, store: 13050, target: 32000 },
  { month: "Mar", web: 19800, store: 13600, target: 33000 },
  { month: "Avr", web: 26500, store: 15100, target: 36000 },
  { month: "Mai", web: 29200, store: 15800, target: 40000 },
  { month: "Juin", web: 34800, store: 17400, target: 46000 },
];

const channels = [
  { key: "web", label: "En ligne" },
  { key: "store", label: "Magasin" },
];

const kEuro = (value: number) => `${Math.round(value / 1000)} k€`;

const targetTicks = ({ categoryCenters, bandwidth, yAt, data }: ChartPlotContext) => (
  <g className="stroke-gray-900 dark:stroke-gray-100">
    {categoryCenters.map((center, index) => (
      <line
        key={index}
        x1={center - bandwidth / 2}
        x2={center + bandwidth / 2}
        y1={yAt(Number(data[index].target))}
        y2={yAt(Number(data[index].target))}
        strokeWidth={2}
      />
    ))}
  </g>
);

export function OverlayTargets() {
  return (
    <BarChart
      title="Ventes et objectif mensuel"
      data={monthly}
      series={channels}
      x={{ key: "month" }}
      y={{ domain: [0, 60000], format: kEuro }}
      stack="stacked"
      overlay={targetTicks}
      height={240}
    />
  );
}

Annotations and textures

annotations explains a movement (band, line, point); patterns adds one texture per series, repeated in the legend, for readers who cannot rely on hue.

Open in a tab
import { AreaChart } from "@synertech/ui";

const monthly = [
  { month: "Jan", web: 18400, store: 12200, target: 30000 },
  { month: "Fév", web: 21100, store: 13050, target: 32000 },
  { month: "Mar", web: 19800, store: 13600, target: 33000 },
  { month: "Avr", web: 26500, store: 15100, target: 36000 },
  { month: "Mai", web: 29200, store: 15800, target: 40000 },
  { month: "Juin", web: 34800, store: 17400, target: 46000 },
];

const channels = [
  { key: "web", label: "En ligne" },
  { key: "store", label: "Magasin" },
];

const kEuro = (value: number) => `${Math.round(value / 1000)} k€`;

export function AnnotationsAndPatterns() {
  return (
    <AreaChart
      title="Ventes par canal"
      data={monthly}
      series={channels}
      x={{ key: "month" }}
      y={{ format: kEuro }}
      stack="stacked"
      patterns
      annotations={[
        { type: "band", from: "Avr", to: "Mai", label: "Campagne de printemps" },
        { type: "line", x: "Fév", label: "Nouveau site" },
        { type: "point", x: "Juin", y: 52200, label: "Record" },
      ]}
      height={240}
    />
  );
}

Large volumes and range selection

Past CHART_POINT_BUDGET points, maxPoints thins the drawing (LTTB) without dropping any data. brush lets a window be dragged, onBrush receives it.

Open in a tab
import { useState } from "react";
import { CHART_POINT_BUDGET, LineChart, type ChartBrushRange } from "@synertech/ui";

const sensor = Array.from({ length: 5000 }, (_, index) => ({
  t: index,
  value: Math.round(50 + Math.sin(index / 80) * 20 + Math.sin(index / 7) * 4),
}));

export function LargeSeriesWithBrush() {
  const [range, setRange] = useState<ChartBrushRange | null>(null);

  return (
    <div className="flex flex-col gap-2">
      <LineChart
        title="Capteur de température"
        description={`${sensor.length} mesures (budget : ${CHART_POINT_BUDGET})`}
        data={sensor}
        series={[{ key: "value", label: "Température" }]}
        x={{ key: "t", scale: "linear" }}
        maxPoints={800}
        brush
        onBrush={setRange}
        height={220}
      />
      <p className="text-sm text-gray-600 dark:text-gray-300">
        {range
          ? `Mesures ${range.fromIndex} à ${range.toIndex}`
          : "Glissez pour choisir une plage."}
      </p>
    </div>
  );
}

Loading, empty and error

Three exclusive, ranked states: loading wins, error is never an empty state and offers onRetry, emptyState replaces the empty state — an EmptyState saying why.

Open in a tab
import { useState } from "react";
import { EmptyState, LineChart } from "@synertech/ui";

export function StatusStates() {
  const [status, setStatus] = useState<"error" | "loading" | "empty">("error");
  const retry = () => {
    setStatus("loading");
    setTimeout(() => setStatus("empty"), 1200);
  };

  return (
    <LineChart
      title="Visites"
      data={[]}
      series={[{ key: "visits", label: "Visites" }]}
      x={{ key: "month" }}
      loading={status === "loading"}
      error={status === "error"}
      onRetry={retry}
      emptyState={
        <EmptyState
          size="sm"
          title="Aucune visite sur la période choisie"
          description="Le site n’a pas encore reçu de visite ce mois-ci."
        />
      }
      height={200}
    />
  );
}

API reference

Components

ChartAxis

ComponentServer-compatible

One axis, drawn from the origin of the group it sits in — the caller translates that group to the bottom-left corner of the drawing area.

Labels wear text colours, never a series colour: a light categorical hue is unreadable as text on the surface.

import { ChartAxis } from "@synertech/ui";

Props — ChartAxisProps

PropTypeDefaultDescription
length• number —

Length of the axis in pixels.

orientation• ChartAxisOrientation —

bottom draws the category or time axis, left the value axis.

ticks• ChartTick[] —
label string —

Caption of the axis.

showLine boolean true

Draws the axis line itself.

size ChartSize "md"
tickPadding number 6

Gap between that mark and its label.

tickSize number 4

Length of the small mark next to each label.

+ 485 inherited native attributes from SVGAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

ChartAnnotationLayer

ComponentServer-compatible

The annotation layer: what happened, drawn where it happened.

Laid out behind the marks for the bands and over them for the lines and the points. A band is a region the data sits in and belongs under it; a line is a boundary and is worthless hidden behind an area.

Everything here is chrome by default — grey, thin, dashed. An annotation that draws the eye more strongly than the data has become the chart.

import { ChartAnnotationLayer } from "@synertech/ui";

Props — ChartAnnotationLayerProps

PropTypeDefaultDescription
annotations• readonly ChartAnnotation[] —
height• number —
width• number —

Size of the plot area.

xAt• (value: ChartXValue) => number | null —

Where an x value lands along the category axis, or null when it is not on the plot at all — an annotation for a date outside the window is skipped rather than drawn on the edge.

yAt• (value: number) => number —

Where a value lands along the value axis.

bandwidth number 0

Width of a band on the category axis, 0 on a point placement.

A band annotation covers whole categories, so it reaches half a band past the centres its ends resolve to — otherwise "March to May" is drawn from the middle of March to the middle of May.

layer "under" | "over" "over"

Which half of the layer to draw.

under holds the bands and goes below the marks — a region the data sits in, not over it. over holds the rules and the pinned points, which are worthless hidden behind an area. A chart renders the component twice, once on each side of its series.

spanAt (value: ChartXValue) => number | null —

Where an end of a band lands, even past the edge of the plot — an infinity on the side it lies past. A band with one end outside the window is clipped to it rather than dropped: half of it is still on screen. Left unset, a band reads its ends through xAt and is drawn only when both are on the plot.

ChartBrushLayer

ComponentClient

The window a reader selected, drawn across the plot.

Both edges are drawn as rules rather than left to the wash alone: the ends of the window are the part a reader checks, and the boundary of a 14% translucent band is not a line anybody can point at.

import { ChartBrushLayer } from "@synertech/ui";

Props — ChartBrushLayerProps

PropTypeDefaultDescription
from• number —

Where the window starts and ends along the category axis, in pixels.

height• number —
to• number —
width• number —

Size of the drawing area.

label string —

Names the region for assistive technology.

live boolean false

Dashed while the pointer is still down, solid once the window is set.

minSpan number 0

Narrowest the window is drawn, in pixels.

A window of a single row on a line runs from a point to the same point: it was set, it was published, and nothing on screen showed it. Below this width the window is widened around its middle.

orientation ChartOrientation "vertical"

Which screen axis the categories run along.

ChartGrid

ComponentServer-compatible

The grid behind the marks.

Solid hairlines, one step off the surface. Never dashed: dashing reads as "projection" or "threshold", which is meaning the grid does not carry.

import { ChartGrid } from "@synertech/ui";

Props — ChartGridProps

PropTypeDefaultDescription
height• number —

Height of the drawing area.

width• number —

Width of the drawing area.

horizontal number[] []

Vertical offsets of the horizontal lines — usually the y-axis ticks.

vertical number[] []

Horizontal offsets of the vertical lines.

+ 485 inherited native attributes from SVGAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

ChartLegend

ComponentServer-compatible

The legend.

Present as soon as a chart draws two series or more: it is the identity channel a reader can rely on, colour matching alone never being enough. A single-series chart needs none — its title already says what is plotted.

The labels wear text colours; identity comes from the swatch beside them.

import { ChartLegend } from "@synertech/ui";

Props — ChartLegendProps

PropTypeDefaultDescription
items• ChartLegendItem[] —
marker ChartLegendMarker "line"
onToggle (key: string) => void —

Makes each entry a button that shows or hides its series.

position ChartLegendPosition "bottom"
size ChartSize "md"

+ 278 inherited native attributes from HTMLAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

ChartPatternDefs

ComponentServer-compatible

The <defs> block holding one texture per series.

A mark keeps its colour at full strength and the texture is cut out of it in the surface colour, rather than painted over a washed-down fill: a stacked band has to read as a quantity, and a fill dimmed to make room for stripes stops doing that.

import { ChartPatternDefs } from "@synertech/ui";

Props — ChartPatternDefsProps

PropTypeDefaultDescription
entries• readonly ChartPatternEntry[] —

The marks to declare a texture for.

Keyed by slot rather than by position: a pie sorts its slices and a bar chart hides some of its series, and in both the texture has to keep following the identity it was handed out to.

id• string —

Unique per chart instance — a useId(), so two charts never collide.

ChartTableView

ComponentServer-compatible

The data table twin of a chart.

Every chart of the kit can render one, and that is what keeps the charts honest: no value is reachable through hovering alone, colour never carries meaning on its own, and a screen reader gets the numbers rather than a description of a picture.

import { ChartTableView } from "@synertech/ui";

Props — ChartTableViewProps

PropTypeDefaultDescription
data• ChartDatum[] —
series• ChartSeries[] —
xKey• string —

Field the rows are keyed on — the chart's x axis.

caption string —

Screen-reader caption. Say what the chart shows, not that it is a table.

columnFormats Readonly<Record<string, (value: number) => string>> —

Formatters of the columns whose unit is not the others', by series key — the size of a bubble beside its two coordinates. formatValue writes the rest.

emptyLabel string —
formatValue (value: number) => string —
formatX (value: ChartXValue, index: number) => string —
xLabel string —

Header of the first column. Defaults to xKey.

+ 279 inherited native attributes from HTMLAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

ChartTooltip

ComponentServer-compatible

The hover readout.

Positioned inside the chart container rather than portalled: it needs no focus management, it scrolls with the chart, and it stays out of the floating-layer bookkeeping dialogs rely on. The container must therefore keep its overflow visible.

A tooltip only ever enhances: every value it shows is also reachable from the data table, so nothing is gated behind a hover.

import { ChartTooltip } from "@synertech/ui";

Props — ChartTooltipProps

PropTypeDefaultDescription
x• number —

Position inside the chart container, in pixels.

y• number —
containerWidth number —

Used to flip the tooltip before it runs past the right edge.

offset number 12

Gap between the pointer and the tooltip.

visible boolean true

Renders nothing when false.

+ 279 inherited native attributes from HTMLAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

ChartTooltipContent

ComponentServer-compatible

Default body of a tooltip: one row per series, value first.

The legend puts the name first because the reader is looking for a series; here they already have the series and want the number, so the hierarchy is inverted.

import { ChartTooltipContent } from "@synertech/ui";

Props — ChartTooltipContentProps

PropTypeDefaultDescription
points• ChartPoint[] —

Every visible series at that position.

title ReactNode —

Usually the x value under the pointer.

Hooks

useChartBrush

HookClient

Dragging a window across a chart's category axis.

The gesture the whole of ChartSyncProvider exists for: a reader pulls a fortnight on the line and the dashboard is read over that fortnight. It has to live in the plot rather than in a strip of its own, because the range being chosen is a range of the data on screen — a second miniature chart under the first would be a different picture to aim at.

import { useChartBrush } from "@synertech/ui";
useChartBrush({ enabled, active, centers, xValues, offset, orientation, onCommit, }: UseChartBrushOptions): UseChartBrushResult

useChartSize

HookClient

Follows the width of the element ref is attached to.

Height stays a prop: a chart that also grew vertically with its container would reflow its own axis labels on every resize.

The element is looked at again after every render, and observed again when it is another one: a parent that moves the element in its tree — the frame of a chart does, when its legend goes from the right to the bottom — mounts a new one, and an observer left on the old element reported the zero width of a node out of the document.

import { useChartSize } from "@synertech/ui";
useChartSize<T extends HTMLElement = HTMLDivElement>(options?: UseChartSizeOptions): UseChartSizeResult<T>

Functions

binEdges

Function

The edges a set of values would be bucketed on.

Every edge lands on a round step — a bin running from 17.4 to 23.9 is arithmetically correct and unreadable on an axis — and among the round steps, the one whose bin count lands nearest what was asked for.

import { binEdges } from "@synertech/ui";
binEdges(values: readonly number[], spec?: BinSpec): number[]

binValues

Function

Counts a set of values into buckets.

Every bin is half-open — [from, to) — except the last, which closes on its upper edge. Without that, the single largest observation of a sample falls out of the histogram entirely.

import { binValues } from "@synertech/ui";
binValues(values: readonly (number | null | undefined)[], spec?: BinSpec): HistogramBin[]

boxStats

Function

Turns a set of observations into the box a plot draws.

The whiskers stop at the furthest observation within whisker times the interquartile range — Tukey's rule — rather than at the extremes. Whiskers drawn to the extremes cannot show an outlier at all: the point that matters most becomes the end of a line like any other.

Returns null for an empty set, which a chart draws as a gap. A category with no observations is not a category with a median of zero.

import { boxStats } from "@synertech/ui";
boxStats(values: readonly (number | null | undefined)[], whisker?: number): BoxStats | null

Everything a cartesian chart needs to place a mark, computed once.

A pure function on purpose: it is the part of a chart that can be wrong in a way no rendering test would catch, and it is the part every cartesian chart of the kit shares. Line, area and bar differ in the mark they draw over this, not in how they lay it out.

It speaks in value and category axes rather than x and y, because a horizontal bar chart swaps which screen axis carries which.

import { buildCartesianGeometry } from "@synertech/ui";
buildCartesianGeometry({ width, height, data, x, y, bounds, margin, orientation, placement, bandPaddingInner, formatValue, formatX, extraTop, defaultIncludeZero, locale, }: CartesianGeometryOptions): CartesianGeometry

Where a raw x value lands on the category axis, in pixels.

Two axes, one question. A continuous axis can place a value the data never carries, which is exactly what an annotation on an arbitrary date needs; a list of categories cannot, so a value it does not hold answers null and the caller skips the mark rather than drawing it on the edge.

A position outside the plot answers null for the same reason: overlays are drawn without a clip path, and an out-of-window date would otherwise land in the axis gutter.

import { createCategoryLocator } from "@synertech/ui";
createCategoryLocator(geometry: Pick<CartesianGeometry, "categoryScale" | "xValues" | "categoryCenters" | "categoryLength" | "toCategoryNumber">): (value: ChartXValue) => number | null

Maps a signed gap onto the diverging pair, neutral at the centre.

The ramp says which side of the reference a value falls on and how far — it never says whether that is good news. A schedule slipping is "above", and above is not good; that judgement belongs to the status colours, which are reserved for exactly that and always carry a label.

import { createDivergingScale } from "@synertech/ui";
createDivergingScale(domain: readonly [number, number], options?: DivergingScaleOptions): ChartColorScale

The resolved geometry of a plot, in the shape an application can draw with.

The chart already holds every one of these; this only gathers them behind one type, so that overlay is a contract the kit can keep rather than a bag of whatever a chart happened to have in scope.

import { createPlotContext } from "@synertech/ui";
createPlotContext({ geometry, width, height, data, series, formatValue, formatX, }: { geometry: CartesianGeometry; width: number; height: number; data: readonly ChartDatum[]; series: readonly ChartResolvedSeries[]; formatValue: (value: number) => string; formatX: (value: ChartXValue, index: number) => string; }): ChartPlotContext

Maps a magnitude onto the sequential ramp.

A zero-width domain pins everything to the light end: with a single value on the grid there is no magnitude to show, and painting it as the maximum would invent one.

import { createSequentialScale } from "@synertech/ui";
createSequentialScale(domain: readonly [number, number], options?: SequentialScaleOptions): ChartColorScale

The rows a drawn path keeps, thinned to roughly maxPoints per series.

Indices rather than points, because a band needs its top and its bottom thinned on the very same rows: thin them apart and the fill between them closes on two points that never faced each other.

The gaps are structural and survive: a run of missing measurements is not noise to be smoothed away, it is the series saying it has nothing there. Each run of gaps keeps one row — enough for the path to lift the pen — and the defined runs between them share the budget in proportion to their length.

import { decimateIndices } from "@synertech/ui";
decimateIndices(points: readonly PathPoint[], maxPoints: number): number[]

decimatePath

Function

A drawn path, thinned to roughly maxPoints points per series.

The chart's geometry is untouched — the hover, the crosshair, the tooltip and the data table all keep reading every row. Only the number of points the path is drawn from changes, which is the part that actually costs.

import { decimatePath } from "@synertech/ui";
decimatePath(points: readonly PathPoint[], maxPoints: number): PathPoint[]

The annotations, as one sentence for the chart's accessible name.

An SVG marked role="img" exposes its name and nothing inside it, so a caption drawn on the plot is invisible to a screen reader. The comments are half of what an annotated chart says, so they are appended to the name the chart already carries rather than left on the picture alone.

import { describeAnnotations } from "@synertech/ui";
describeAnnotations(annotations: readonly ChartAnnotation[] | undefined, prefix: string): string

Renders a time tick at the precision its own step carries.

A day step writes "12 Mar" and an hour step writes "14:00": showing the time under a monthly tick, or the year under an hourly one, is noise the reader has to filter out on every label.

import { formatTimeTick } from "@synertech/ui";
formatTimeTick(value: number, unit: TimeUnit, locale?: string): string

Colour of the index-th band of an ordered set.

Spread across the whole ramp rather than taken from its start, so three bands use the light, the middle and the dark end instead of three steps that look alike.

import { getOrdinalColor } from "@synertech/ui";
getOrdinalColor(index: number, count?: number, colors?: readonly string[]): string

getPattern

Function

The texture at index, wrapping around once past the last one.

import { getPattern } from "@synertech/ui";
getPattern(index: number): ChartPattern

Colour of the series sitting at index.

Colour follows the series' position in the series array — its identity — so hiding or filtering one series never repaints the others.

import { getSeriesColor } from "@synertech/ui";
getSeriesColor(index: number, override?: string): string

Label shown for a series — its own, or its key as a fallback.

import { getSeriesLabel } from "@synertech/ui";
getSeriesLabel(series: ChartSeries): string

lttb

Function

Largest-Triangle-Three-Buckets, returning the indices it keeps.

The classic downsampling for a line: the series is cut into as many buckets as there is room for, and each bucket keeps the one point forming the largest triangle with the point already kept before it and the average of the bucket after it. Picking the largest triangle is what keeps the peaks — a stride sample walks straight past them, which is how a decimated series ends up flatter than the data it came from.

Indices rather than points, so a caller can carry along whatever the point belonged to: a row, a screen coordinate, a tooltip payload.

import { lttb } from "@synertech/ui";
lttb(points: readonly XY[], threshold: number): number[]

Ticks covering [min, max], landing on calendar boundaries.

count is a target, not a promise — the same contract as niceTicks: the step is chosen first, and how many ticks fit follows from it.

Steps are walked with Date arithmetic rather than by adding a constant, so a month tick stays on the first of the month across February and a day tick stays at midnight across a daylight saving change.

import { niceTimeTicks } from "@synertech/ui";
niceTimeTicks(min: number, max: number, count?: number): TimeTickScale

The same texture, in CSS, for the HTML swatch of a legend.

The legend and the plot have to carry the same two channels, or the texture becomes noise the reader cannot map onto anything. A gradient reproduces the SVG tile closely enough at swatch size, and it flips with the theme through the same surface variable.

import { patternBackground } from "@synertech/ui";
patternBackground(index: number, color: string): CSSProperties

patternFill

Function

The fill a mark wears.

The texture when they are on and the slot has one, the flat colour otherwise — so a chart calls this once and never branches itself.

import { patternFill } from "@synertech/ui";
patternFill(enabled: boolean, baseId: string, index: number, color: string): string

patternId

Function

Id of the SVG pattern a chart declared for its index-th series.

The base is stripped down to id characters: useId returns :r0: on React 18, and a fill pointing at url(#:r0:-texture-1) is a fragment reference browsers are not obliged to resolve.

import { patternId } from "@synertech/ui";
patternId(baseId: string, index: number): string

quantile

Function

Same, on a list that has not been sorted yet.

import { quantile } from "@synertech/ui";
quantile(values: readonly number[], p: number): number

Quantile p (0 to 1) of an ascending list, interpolating between the two neighbouring observations.

This is the R-7 / numpy.percentile definition — the one a reader will get if they check the numbers in a spreadsheet, which is the only property that matters for a library.

import { quantileSorted } from "@synertech/ui";
quantileSorted(sorted: readonly number[], p: number): number

rampColor

Function

Colour at t (0 to 1) along a ramp.

Between two stops the colour is mixed in OKLab rather than snapped to the nearer one: a ramp cut into six classes reads as six bands, which is a lie about a measure that varies continuously. The mix happens in CSS, so the stops stay overridable variables instead of hex frozen into the bundle.

import { rampColor } from "@synertech/ui";
rampColor(colors: readonly string[], t: number): string

Lets a test watch the warning fire more than once.

import { resetPointBudgetWarning } from "@synertech/ui";
resetPointBudgetWarning(): void

Colour of a series, taking the chart's emphasis into account: the emphasised series keeps its slot, every other one drops to grey.

import { resolveSeriesColor } from "@synertech/ui";
resolveSeriesColor(series: ChartSeries, index: number, emphasis?: string): string

sampleEvenly

Function

An evenly spread sample, keeping the two ends.

What an unordered cloud needs, where LTTB is the wrong tool: a scatter is read for where its points are dense, and keeping the largest triangles would carve out the envelope and throw the density away — a lie about the very thing the chart is for. An even stride keeps the shape of the cloud and thins it uniformly.

Deterministic on purpose, rather than a random sample: the same data has to draw the same picture on the server and in the browser.

import { sampleEvenly } from "@synertech/ui";
sampleEvenly<T>(items: readonly T[], threshold: number): T[]

splitOverlay

Function

An overlay in its two halves, whichever form it was given in.

A bare function draws over the marks, which is what a label, a bracket or a custom threshold wants. Reaching under them is the rarer case and says so by taking the object form.

import { splitOverlay } from "@synertech/ui";
splitOverlay(overlay: ChartOverlay | undefined): { under?: ChartOverlayRenderer; over?: ChartOverlayRenderer; }

sturgesBins

Function

Sturges' rule: ceil(log2 n) + 1.

Not the most refined estimator — Freedman-Diaconis adapts to the spread — but it is the one a reader recognises, it never explodes on a heavy tail, and a histogram whose bin count changes with a single outlier is worse than one that is slightly too coarse.

import { sturgesBins } from "@synertech/ui";
sturgesBins(count: number): number

Builds the legend entries of a series list, colours already resolved.

patterns mirrors the chart's own setting: when the marks are textured the swatches have to be too, since the texture is the channel a reader falls back on when the hue fails them.

import { toLegendItems } from "@synertech/ui";
toLegendItems(series: ChartSeries[], emphasis?: string, patterns?: boolean): ChartLegendItem[]

toTimestamp

Function

Turns a date, a timestamp or a parsable string into a timestamp.

A string without a time — 2026-03-02, 2026-03, 2026 — is read as midnight local time, like one with a time and no offset: the day the string names is the day the reader sees, whatever their time zone.

import { toTimestamp } from "@synertech/ui";
toTimestamp(value: unknown): number | null

Constants

Number of series a chart can carry when any two marks may end up side by side — a scatter or bubble plot. Neighbouring bars and lines only ever compare adjacent slots, which all eight clear; with every pair in play, only the first three do.

import { CHART_ALL_PAIRS_LIMIT } from "@synertech/ui";
const CHART_ALL_PAIRS_LIMIT: 3

Two opposed poles around a neutral middle: a gap to a reference, a Likert scale. Blue on one side, orange on the other — two cool hues never read as opposites.

import { CHART_DIVERGING_COLORS } from "@synertech/ui";
const CHART_DIVERGING_COLORS: readonly ["var(--color-chart-div-1)", "var(--color-chart-div-2)", "var(--color-chart-div-3)", "var(--color-chart-div-4)", "var(--color-chart-div-5)", "var(--color-chart-div-6)", "var(--color-chart-div-7)"]
import { CHART_DIVERGING_DARK_STOPS } from "@synertech/ui";
const CHART_DIVERGING_DARK_STOPS: readonly [true, false, false, false, false, false, true] = [true, false, false, false, false, false, true] as const

Index of the neutral step of CHART_DIVERGING_COLORS.

import { CHART_DIVERGING_NEUTRAL_INDEX } from "@synertech/ui";
const CHART_DIVERGING_NEUTRAL_INDEX: 3
import { CHART_DOWN_COLOR } from "@synertech/ui";
const CHART_DOWN_COLOR: "var(--color-chart-down)"

Past this many colour classes, two neighbouring cells stop being tellable apart — the reader sees a texture rather than a scale. A finer grid is read as a continuous wash, which is what the scale does when steps is unset.

import { CHART_MAX_COLOR_CLASSES } from "@synertech/ui";
const CHART_MAX_COLOR_CLASSES: 7

Grey used for de-emphasised series and for the "Other" bucket.

import { CHART_MUTED_COLOR } from "@synertech/ui";
const CHART_MUTED_COLOR: "var(--color-chart-muted)"

One hue in ordered steps: ranked bands, brackets, a funnel.

import { CHART_ORDINAL_COLORS } from "@synertech/ui";
const CHART_ORDINAL_COLORS: readonly ["var(--color-chart-ord-1)", "var(--color-chart-ord-2)", "var(--color-chart-ord-3)", "var(--color-chart-ord-4)", "var(--color-chart-ord-5)"]
import { CHART_ORDINAL_DARK_STOPS } from "@synertech/ui";
const CHART_ORDINAL_DARK_STOPS: readonly [false, false, true, true, true] = [false, false, true, true, true] as const

Number of categorical slots the palette holds.

Eight is not a round number picked for looks: past it, a generated hue is indistinguishable from an existing slot for a colour-blind reader. A ninth series is folded into an "Other" bucket, faceted into several charts, or given a second channel (shape, texture) — never a ninth colour.

import { CHART_PALETTE_SIZE } from "@synertech/ui";
const CHART_PALETTE_SIZE: 8

The textures, in the order they are handed out.

One per palette slot, and assigned the same way: by the series' position in series, never by its rank. Hiding a series repaints nothing, and the texture a reader learnt in the legend is still the one on the plot.

Every hatch runs at 45° or its mirror at 135°, never horizontal and never vertical: those two align with the gridlines and with the edges of the marks, where they read as part of the chrome rather than as a fill. The first slot is left solid — an untextured mark is itself a texture, and the easiest of all to tell apart.

import { CHART_PATTERNS } from "@synertech/ui";
const CHART_PATTERNS: readonly ["solid", "diagonal", "diagonal-reverse", "cross", "dots", "diagonal-wide", "diagonal-reverse-wide", "dots-wide"] = [ "solid", "diagonal", "diagonal-reverse", "cross", "dots", "diagonal-wide", "diagonal-reverse-wide", "dots-wide", ] as const

How many points per series the kit draws before it starts warning.

The figure is a measurement, not a taste: past roughly this many points a d attribute stops being a path and becomes a string the browser reparses on every re-render, and two neighbouring points land on the same pixel column anyway — the reader gains nothing for the cost.

Nothing is dropped on its own when a series crosses it. A chart that quietly drew a different shape than the one it was handed would be worse than a slow one; the warning says what to pass instead.

import { CHART_POINT_BUDGET } from "@synertech/ui";
const CHART_POINT_BUDGET: 2000

One hue, light to dark: a continuous magnitude (a heat map).

import { CHART_SEQUENTIAL_COLORS } from "@synertech/ui";
const CHART_SEQUENTIAL_COLORS: readonly ["var(--color-chart-seq-1)", "var(--color-chart-seq-2)", "var(--color-chart-seq-3)", "var(--color-chart-seq-4)", "var(--color-chart-seq-5)", "var(--color-chart-seq-6)"]
import { CHART_SEQUENTIAL_DARK_STOPS } from "@synertech/ui";
const CHART_SEQUENTIAL_DARK_STOPS: readonly [false, false, false, false, true, true] = [false, false, false, false, true, true] as const

The eight slots, in the order they are assigned.

The order is the safety mechanism — it was picked among the orderings that keep every neighbouring pair distinguishable under simulated protanopia and deuteranopia, in both themes. The values live in src/styles/index.css, so an application can rebrand the kit without forking a component.

import { CHART_SERIES_COLORS } from "@synertech/ui";
const CHART_SERIES_COLORS: readonly ["var(--color-chart-1)", "var(--color-chart-2)", "var(--color-chart-3)", "var(--color-chart-4)", "var(--color-chart-5)", "var(--color-chart-6)", "var(--color-chart-7)", "var(--color-chart-8)"]

The colour of the surface a chart sits on: what a texture is cut through, the gap between two bands and the ring around a marker.

Declared in src/styles/index.css under both theme scopes, so a stripe is white on a white panel and gray-800 on a dark one without a component ever asking which theme is on — and an application whose panels are another colour redefines it once.

import { CHART_SURFACE_COLOR } from "@synertech/ui";
const CHART_SURFACE_COLOR: "var(--color-chart-surface)"
import { CHART_UP_COLOR } from "@synertech/ui";
const CHART_UP_COLOR: "var(--color-chart-up)"

Width a chart draws at before its container has been measured.

There is always a first paint with no measurement: on the server, and on the client before the effect runs. Rendering at zero there would mean an empty SVG on every server render and in every jsdom test — where ResizeObserver is mocked and never fires. A plausible width keeps the first frame usable.

import { DEFAULT_CHART_WIDTH } from "@synertech/ui";
const DEFAULT_CHART_WIDTH: 640

Types

BoxStats

Interface

The five-number summary, plus what falls outside the whiskers.

interface BoxStats
FieldTypeDefaultDescription
count• number —

Number of observations the summary was computed from.

iqr• number —

q3 - q1: the width of the box, and the unit the whiskers are measured in.

lower• number —

End of the lower whisker: the smallest observation still within reach.

max• number —

Largest observation, outliers included.

median• number —
min• number —

Smallest observation, outliers included.

outliers• number[] —

Observations beyond the whiskers, in ascending order.

q1• number —
q3• number —
upper• number —

End of the upper whisker.

Props shared by every cartesian chart of the kit. Each chart adds its own geometry on top — curve for lines, stack for areas and bars, and so on.

FieldTypeDefaultDescription
data• ChartDatum[] —
series• ChartSeries[] —
x• ChartXAxisConfig —
actions ReactNode —

Slot on the right of the caption: an export button, a range picker.

A filter that frames several panels belongs in a ChartFilterBar above all of them; this is for what belongs to this panel alone.

className string —
description ReactNode —
emphasis string —

Paints one series in its colour and greys out every other one.

emptyState ReactNode —

Replaces the "no data" state: usually an EmptyState saying why, and what to do.

error boolean —

The data could not be loaded.

Never the same thing as having none: a panel that says "no data" after a failed request states something false, and offers no way out.

errorState ReactNode —

Replaces the whole built-in error state, message and button included.

grid ChartGridLines —
height number —

Height of the plot area in pixels. Width always follows the container.

legend boolean | ChartLegendPosition —
loading boolean —

Dims the plot while fresh data loads; a first load shows a spinner.

onPointClick (event: ChartPointEvent) => void —

Called with the mark that was clicked.

Enter and Space on the focused chart do the same for the mark the keyboard is on.

onRetry () => void —

Draws the retry button in the error state, and is called when pressed.

overlay ChartOverlay —

Draws inside the plot, with the chart's own resolved geometry.

size ChartSize —
tableView boolean | "toggle" —

Renders the accessible data table: always (true) or behind a button.

title ReactNode —
tooltip boolean | ((payload: ChartTooltipPayload) => ReactNode) —

false disables the hover layer; a function replaces its content.

width number —

Fixes the width instead of measuring the container.

y ChartYAxisConfig —
FieldTypeDefaultDescription
bandwidth• number —

Width of a band — 0 under a point placement.

categoryCenters• number[] —

Middle of a row's slot: where a tick, a line point or a hover lands.

categoryLength• number —

Length of the category axis in pixels.

categoryPositions• number[] —

Where each row starts along the category axis.

categoryScale• LinearScale | null —

The category axis as a continuous scale, when it is one.

null for a list of categories, where a value that is not in the data has no position at all. It is what lets an overlay place a date the rows never carry — an annotation on the 14th of a weekly series.

categoryTicks• ChartTick[] —
domain• [number, number] —

Rounded bounds of the value axis.

innerHeight• number —
innerWidth• number —
margin• ChartMargin —
orientation• CartesianOrientation —
toCategoryNumber• (value: ChartXValue) => number —

Reads an x value as the number categoryScale places: a timestamp on a time axis, ISO strings included, and the value itself on a linear one. NaN when the value cannot be placed.

valueScale• LinearScale —

Maps a value to a pixel along the value axis.

valueTicks• ChartTick[] —
xValues• ChartXValue[] —

The x value of each row, in row order.

FieldTypeDefaultDescription
bounds• [number, number] | null —

Bounds the value axis has to cover, before rounding.

The caller computes them, because they are not always the extent of the raw values: a stacked chart measures its totals, not its series.

data• readonly ChartDatum[] —
formatValue• (value: number) => string —
formatX• (value: ChartXValue, index: number) => string —
height• number —
width• number —

Measured width of the plot area — never the width prop, which is usually unset.

x• ChartXAxisConfig —

Describes the category axis, whichever side the orientation puts it on.

bandPaddingInner number —

Share of a band left empty between two neighbours.

defaultIncludeZero boolean —

Whether zero stays inside the domain when the axis config does not say.

A bar is read for the length of its mark, so it needs its baseline; a line is read for its slope, and forcing zero flattens the change.

extraTop number —

Extra room at the top, for a caption drawn above the plot.

locale string —

Language the ticks of a time axis write their dates in — the one the chart resolved, never the runtime's, or a server and a browser label the same tick two ways.

margin Partial<ChartMargin> —
orientation CartesianOrientation —
placement CategoryPlacement —
y ChartYAxisConfig —

Describes the value axis.

What every annotation carries.

FieldTypeDefaultDescription
color string —

Any CSS colour. Defaults to a muted grey, which is what keeps it chrome.

label string —

The comment itself. Without it an annotation marks a spot and says nothing.

A stretch of the category axis: a campaign, an outage, a closed quarter.

FieldTypeDefaultDescription
from• ChartXValue —
to• ChartXValue —
type• "band" —
color string —

Any CSS colour. Defaults to a muted grey, which is what keeps it chrome.

label string —

The comment itself. Without it an annotation marks a spot and says nothing.

A window dragged across a chart's category axis.

Both ends are inclusive, and both are given twice: as the x values a reader selected, and as the row indices they cover — filtering a dataset wants the indices, feeding a period picker wants the values.

interface ChartBrushRange
FieldTypeDefaultDescription
from• ChartXValue —
fromIndex• number —
to• ChartXValue —
toIndex• number —
end ChartXValue —

Where the interval of the last row ends: the x value of the row after to, or past the last row, to moved on by the step the rows were taking. A row of a monthly series stands for the whole month, so a window from January to March covers March to its end — which brushToPeriod reads here. Absent when the window cannot say, on a single row or on values that are not dates or numbers.

A colour ramp, already bound to the values it has to paint.

interface ChartColorScale
FieldTypeDefaultDescription
colors• readonly string[] —

The stops, in ramp order — what a legend draws its gradient from.

domain• readonly [number, number] —
onDark• (value: number) => boolean —

true when the colour under value is dark enough that text written on it has to be light. Always false for a ramp brought by the caller, which the kit knows nothing about.

position• (value: number) => number —

Where a value falls along the ramp, from 0 to 1.

steps• number | null —

Number of classes the ramp was cut into, or null when it is continuous.

Geometry handed to a chart once its container has been measured.

interface ChartDimensions
FieldTypeDefaultDescription
height• number —

Total height, including the axis gutters.

innerHeight• number —

Height of the drawing area.

innerWidth• number —

Width of the drawing area.

margin• ChartMargin —
width• number —

Total width, including the axis gutters.

An entry of the legend.

interface ChartLegendItem
FieldTypeDefaultDescription
color• string —
key• string —
label• string —
hidden boolean —
marker "line" | "rect" | "dot" —

Overrides the legend's shared swatch shape for this entry alone.

What a combined chart needs: the swatch has to mirror the mark, so the series drawn as a line cannot wear the same block as the bars beside it.

pattern number —

Texture slot the entry wears, when the chart draws its marks with them.

The swatch has to carry both channels the plot carries, or the texture is a pattern the reader cannot map onto anything.

A moment: a release, a price change, the day the tracking broke.

FieldTypeDefaultDescription
type• "line" —
x• ChartXValue —
color string —

Any CSS colour. Defaults to a muted grey, which is what keeps it chrome.

dashed boolean —

Solid instead of dashed — for a boundary rather than an event.

label string —

The comment itself. Without it an annotation marks a spot and says nothing.

ChartMargin

Interface

Space between the drawing area and the edges of the chart.

interface ChartMargin
FieldTypeDefaultDescription
bottom• number —
left• number —
right• number —
top• number —

One texture to declare: the slot it belongs to, and the colour it paints.

FieldTypeDefaultDescription
color• string —
slot• number —

Palette slot of the mark — what patternFill is called with.

The resolved geometry of a plot, handed to whatever an application draws inside it.

Coordinates are relative to the drawing area, not to the SVG: 0, 0 is the top-left corner of the plot, inside the axis gutters, which is the frame the chart's own marks are placed in.

FieldTypeDefaultDescription
bandwidth• number —

Width of a band. 0 where the rows are placed as points.

categoryCenters• number[] —

Middle of each row's slot, in row order — where a mark is centred.

data• readonly ChartDatum[] —

The rows the chart was given, untouched.

dimensions• ChartDimensions —

Size of the drawing area, and the gutters reserved around it.

domain• [number, number] —

Rounded bounds of the value axis.

formatValue• (value: number) => string —

The chart's own value formatter — a caption should read like its axis.

formatX• (value: ChartXValue, index: number) => string —

The chart's own category formatter.

orientation• ChartOrientation —

Which screen axis carries the values.

series• readonly ChartResolvedSeries[] —

The visible series, palette slots already resolved.

xAt• (value: ChartXValue) => number | null —

Where an x value lands along the category axis, in pixels.

null when the axis cannot place it — a category that is not in the data, or a date outside the window. Skip the mark rather than drawing it on the edge, which is what the chart's own overlays do.

xValues• ChartXValue[] —

The x value of each row, in row order.

yAt• (value: number) => number —

Where a value lands along the value axis, in pixels.

ChartPoint

Interface

One series' value at a given position, as shown in a tooltip row.

interface ChartPoint
FieldTypeDefaultDescription
color• string —
datum• ChartDatum —
formattedValue• string —

value run through the chart's formatter.

seriesKey• string —
seriesLabel• string —
value• number | null —

null for a gap in the series.

A single observation worth commenting, marked where it sits on the plot.

FieldTypeDefaultDescription
type• "point" —
x• ChartXValue —
y• number —

Value the marker is pinned to, read on the chart's own value axis.

color string —

Any CSS colour. Defaults to a muted grey, which is what keeps it chrome.

label string —

The comment itself. Without it an annotation marks a spot and says nothing.

Emitted when a mark is clicked.

interface ChartPointEvent extends ChartPoint
FieldTypeDefaultDescription
color• string —
datum• ChartDatum —
formattedValue• string —

value run through the chart's formatter.

index• number —
seriesKey• string —
seriesLabel• string —
value• number | null —

null for a gap in the series.

x• ChartXValue —

A threshold drawn across the plot: a target, a limit, a budget.

Dashed by default — unlike a gridline, a reference line is a threshold, so the dashing carries meaning here instead of adding noise.

FieldTypeDefaultDescription
value• number —
color string —

Any CSS colour. Defaults to a muted grey.

dashed boolean —
label string —

ChartSeries

Interface

A plotted series.

key is the field read on every datum AND the series' identity: its colour follows that identity, never its position after a filter, so hiding one series never repaints the others.

interface ChartSeries
FieldTypeDefaultDescription
key• string —

Field read on each datum, and stable identity of the series.

color string —

Overrides the palette slot. Any CSS colour, including a custom property.

dashed boolean —

Draws the line dashed — for a projection, a target, or a modelled value.

hidden boolean —

Keeps the series out of the plot while leaving it in the legend.

label string —

Shown in the legend, the tooltip and the data table. Defaults to key.

type "bar" | "line" —

Mark this series is drawn with, where a chart can draw more than one.

Only BarChart reads it, and only to lift a series out of the bars and draw it as a line over them — a volume and its trend on one panel. Both marks keep sharing the single value axis: a second axis lets two measures of unrelated magnitudes cross wherever the scaling happens to put them, which reads as a correlation the data never claimed.

What a panel carries besides its data.

The three states are mutually exclusive and ranked: a chart that failed is not a chart that is empty, and a chart that is loading again is neither.

FieldTypeDefaultDescription
actions ReactNode —

Slot on the right of the caption: an export button, a range picker.

A filter that frames several panels belongs in a ChartFilterBar above all of them; this is for what belongs to this panel alone.

emptyState ReactNode —

Replaces the "no data" state: usually an EmptyState saying why, and what to do.

error boolean —

The data could not be loaded.

Never the same thing as having none: a panel that says "no data" after a failed request states something false, and offers no way out.

errorState ReactNode —

Replaces the whole built-in error state, message and button included.

loading boolean —

Dims the plot while fresh data loads; a first load shows a spinner.

onRetry () => void —

Draws the retry button in the error state, and is called when pressed.

ChartTick

Interface

A tick, already placed on its axis.

interface ChartTick
FieldTypeDefaultDescription
label• string —
offset• number —

Distance in pixels from the start of the axis.

value• ChartXValue —

The underlying value, kept for key and for tests.

Everything a tooltip needs about the position under the pointer.

FieldTypeDefaultDescription
index• number —
points• ChartPoint[] —

Every visible series at this position — the pointer never has to land on a mark.

x• ChartXValue —
xLabel• string —
FieldTypeDefaultDescription
key• string —

Field read on each datum.

format (value: ChartXValue, index: number) => string —

Formats a tick. Defaults to a locale-aware rendering of the value.

height number —

Height reserved below the plot for the labels.

hidden boolean —

Hides the axis line and its labels, keeping the plot area unchanged.

label string —

Axis caption.

scale ChartScaleType —

Defaults to category.

ticks number —

Preferred number of ticks. The axis may draw fewer to avoid collisions.

FieldTypeDefaultDescription
domain [number, number] | "auto" —

Fixed bounds, or auto (the default) to derive them from the data.

format (value: number) => string —

Formats a tick and the values in the tooltip.

hidden boolean —

Hides the axis line and its labels, keeping the plot area unchanged.

includeZero boolean —

Keeps zero inside an automatic domain. The default is the chart's own: true where a length or an area is read from the baseline (bars, areas, waterfall), false where a position or a slope is (lines, scatter, dumbbell, box plot, candlestick).

label string —

Axis caption.

ticks number —

Preferred number of ticks. Defaults to 5.

width number —

Width reserved left of the plot for the labels.

FieldTypeDefaultDescription
center number —

Value the two directions are measured from. Defaults to 0.

colors readonly string[] —

Replaces the stops — any CSS colours, usually custom properties.

darkStops readonly boolean[] —

One flag per stop, saying which ones need light text written on them. Only worth passing alongside colors: the built-in ramps carry their own.

steps number —

Cuts the ramp into that many classes instead of leaving it continuous.

symmetric boolean —

Stretches the shorter arm so both cover the same distance. On by default: with independent arms, a gap of +5 and a gap of −5 come out at different intensities, which reads as one of them being the bigger miss.

HistogramBin

Interface

One bucket of a histogram.

interface HistogramBin
FieldTypeDefaultDescription
count• number —
from• number —

Lower edge, included.

last• boolean —

true for the last bin: the only one that includes its upper edge.

to• number —

Upper edge, excluded — except on the last bin, which closes on it.

FieldTypeDefaultDescription
colors readonly string[] —

Replaces the stops — any CSS colours, usually custom properties.

darkStops readonly boolean[] —

One flag per stop, saying which ones need light text written on them. Only worth passing alongside colors: the built-in ramps carry their own.

steps number —

Cuts the ramp into that many classes instead of leaving it continuous.

TimeTickScale

Interface
interface TimeTickScale
FieldTypeDefaultDescription
step• number —

How many of that unit each step covers.

unit• TimeUnit —

Calendar unit the step is counted in — what a label should say.

values• number[] —

Tick timestamps, ascending.

FieldTypeDefaultDescription
active• boolean —

Whether a window is currently set.

A press that goes nowhere drops the window — otherwise a reader who has brushed once has no way back but to brush again. Without knowing there is one to drop, every ordinary click would fire a null nobody asked for.

centers• readonly number[] —

Middle of each row's slot along the category axis, in pixels.

enabled• boolean —

false leaves every handler a no-op, so a chart can wire them anyway.

offset• number —

Offset of the drawing area inside the SVG, on the axis the drag runs along.

onCommit• (range: ChartBrushRange | null) => void —

Called when a window is set, and with null when one is dropped.

orientation• ChartOrientation —
xValues• readonly ChartXValue[] —

The x value of each row, in row order.

FieldTypeDefaultDescription
consumedClick• () => boolean —

true when the press that just ended was a drag, not a click.

dragging• ChartBrushRange | null —

The window being dragged right now, or null.

onKeyDown• (event: ReactKeyboardEvent<SVGSVGElement>, focusedIndex: number | null) => boolean —

Shift + arrows to extend the window, Escape to drop it.

Never prevents the key's default itself: the chart's own handler still moves its crosshair on the same press, which is what keeps the window's head and the focused position in step. Keyboard parity is not optional here — a filter that can only be set by dragging is a filter half the readers cannot reach.

onPointerDown• (event: ReactPointerEvent<SVGSVGElement>) => void —
onPointerMove• (event: ReactPointerEvent<SVGSVGElement>) => void —
onPointerUp• (event: ReactPointerEvent<SVGSVGElement>) => void —
FieldTypeDefaultDescription
fallbackWidth number —

Width used until the container reports one.

width number —

Fixes the width. The container is then never measured.

interface UseChartSizeResult<T extends HTMLElement>
FieldTypeDefaultDescription
measured• boolean —

false while the width is still the fallback.

ref• { current: T | null } —

Attach to the element whose width the chart should follow.

width• number —

How the buckets are cut: a count, explicit edges, or true for a count derived from the sample size.

type BinSpec = number | readonly number[] | boolean

Which screen axis carries the values.

The public spelling is ChartOrientation, declared beside the other types an application can see; this alias is what the engine has always called it.

type CartesianOrientation = ChartOrientation

How a row takes its place along the category axis.

point spaces the rows evenly with the first and last on the edges, which is what a line or an area is plotted against. band gives each row a slot of its own, which is what a bar needs to have a width.

type CategoryPlacement = "point" | "band"
type ChartAnnotation = ChartPointAnnotation | ChartLineAnnotation | ChartBandAnnotation
type ChartAxisOrientation = "bottom" | "left"

Shape of the line between two points.

  • linear — straight segments.
  • monotone — cubic interpolation that never overshoots the data.
  • step — holds each value until halfway to the next point.
  • stepAfter — holds each value until the next point, then jumps.
type ChartCurve = "linear" | "monotone" | "step" | "stepAfter"

One row of data. Charts read their values through the axis and series keys, the same way DataGrid reads a row through ColumnDef.key — an application can hand the very same array to both.

type ChartDatum = Record<string, unknown>
type ChartGridLines = "none" | "x" | "y" | "both"

Shape of the swatch. It mirrors the mark: a line for lines, a block for fills.

type ChartLegendMarker = "line" | "rect" | "dot"
type ChartLegendPosition = "top" | "bottom" | "right"

Which screen axis carries the values.

vertical is the usual case — values run up the left side, categories along the bottom. horizontal swaps them, which is what a bar chart does when its category names are too long to be read rotated.

type ChartOrientation = "vertical" | "horizontal"

What an application draws inside a chart.

A bare function is drawn over the marks, which is what an extra label, a bracket or a custom threshold wants. The object form also reaches under them, for a region the data should sit on top of.

type ChartOverlay = | ChartOverlayRenderer
  | { under?: ChartOverlayRenderer; over?: ChartOverlayRenderer }

Draws inside a chart's plot area, with the chart's own geometry.

type ChartOverlayRenderer = (context: ChartPlotContext) => ReactNode
type ChartPattern = (typeof CHART_PATTERNS)[number]

A series whose palette slot has been resolved to a colour.

type ChartResolvedSeries = ChartSeries & { color: string }

How the horizontal axis maps values to pixels.

type ChartScaleType = "category" | "linear" | "time"
type ChartSize = "sm" | "md" | "lg"

Value a chart can place on its horizontal axis.

type ChartXValue = string | number | Date

Ticks for an axis carrying dates.

niceTicks rounds a number to a 1 / 2 / 5 step, which is the right answer for a quantity and the wrong one for a date: time is not decimal. A step of "two hundred million milliseconds" is a perfectly round number and lands on 03:26 on a Tuesday. A reader of a schedule wants Mondays, or the first of the month — so the steps here are the ones a calendar actually has.

type TimeUnit = "second" | "minute" | "hour" | "day" | "week" | "month" | "year"