# EmKit
> Finished React chart components for teams that already have a data layer. A chart library draws the chart; EmKit, by Embeddable, ships the whole card. Every page of the documentation as one Markdown file; the index is https://emkit.embeddable.com/llms.txt.
51 pages, 408 KB.
========================================================================
Title: EmKit
Source: https://emkit.embeddable.com/
========================================================================
# EmKit
> Finished React chart components for teams that already have a data layer. A chart library draws the chart; EmKit, by Embeddable, ships the whole card.
EmKit is 32 finished React chart components: bars, lines, pies, funnels, scatter, KPIs and tables. Describe your data once (dimensions and measures) and each component handles formatting, colours, time series, loading, empty and error states, export and translations. Install `em-kit`; `react` and `react-dom` 19.1.1 or later are the only peer dependencies.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
## Start here
- [Quick start](/docs/quick-start.md): the first chart on screen
- [Components](/docs/components.md): every component, grouped by type
- [Why EmKit](/docs/why.md): what it adds over a chart library
- [Documentation index](/llms.txt): every page, one line each
- [All documentation in one file](/llms-full.txt)
Each page of this site has a Markdown twin at the same URL plus `.md`. A component's page is the export name in kebab-case, for example `BarChartStacked` is `/docs/components/bar-chart-stacked`.
## By Embeddable
EmKit is Embeddable’s chart components as a standalone React library: you bring the data. Inside Embeddable the same components are called Remarkable Pro. [Embeddable](https://embeddable.com) adds the data layer, multi-tenant security and self-serve dashboards for your customers.
========================================================================
Title: Quick start
Source: https://emkit.embeddable.com/docs/quick-start
========================================================================
# Quick start
From an empty React app to a chart on screen, in three steps.
The components take rows you already have, so there is nothing to fetch or configure.
## 1. Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
The only peer dependencies are `react` and `react-dom`, version 19.1.1 or later. Chart.js and the other runtime dependencies install with the package, and there is no stylesheet to import.
## 2. Add the provider
Wrap your app in `ChartsProvider` once. Charts read their theme, language and time zone from it: see [Theming](/docs/theming.md) and [Localisation](/docs/localisation.md). `RevenueChart` is the file you add in step 3.
```tsx title="App.tsx"
import { ChartsProvider } from 'em-kit';
import { RevenueChart } from './RevenueChart';
export default function App() {
return (
);
}
```
The provider loads the Inter font from Google Fonts; to serve it yourself or turn it off, see [fonts](/docs/troubleshooting.md#chart-text-is-in-a-serif-or-system-font).
### In the Next.js App Router
Next.js renders a file on the server unless it starts with `'use client'`, and the components use React context. Put the provider in a client file that pins the locale, so the server and the browser format numbers alike, and render it from the root layout.
```tsx title="app/ClientProvider.tsx"
'use client';
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
// Render this from app/layout.tsx. Files that render charts start with
// 'use client' too. The fixed locale makes the server format numbers as the
// browser will; use the reader's locale from the request if you have it.
export function ClientProvider({ children }: { children: ReactNode }) {
return {children} ;
}
```
```tsx title="app/layout.tsx"
import type { ReactNode } from 'react';
import { ClientProvider } from './ClientProvider';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
{children}
);
}
```
Start `RevenueChart.tsx` from step 3 with `'use client';` as well, and render it from a page.
```tsx title="app/page.tsx"
import { RevenueChart } from '../RevenueChart';
export default function Page() {
return ;
}
```
## 3. Render a chart
Describe each field once, then pass your rows to `results`. The chart fills its parent, so give the parent a height, and a width it can fill.
```tsx title="RevenueChart.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({ name: 'revenue', title: 'Revenue' });
// One row per bar. Each key is the `name` of a field above.
const rows = [
{ region: 'North America', revenue: 48200 },
{ region: 'Europe', revenue: 39500 },
{ region: 'Asia Pacific', revenue: 27800 },
{ region: 'Latin America', revenue: 12100 },
];
export function RevenueChart() {
return (
);
}
```
Result: a card titled “Revenue by region” with four bars, labelled 48,200, 39,500, 27,800 and 12,100.
The numbers are formatted for your browser’s locale, and the menu in the card’s corner exports CSV, Excel and PNG.
## Next steps
- [Describing your data](/docs/describing-your-data.md): dimensions, measures and field options, such as `currency: 'USD'` for $48,200
- [Time series](/docs/time-series.md): dates on the axis, the timestamp format and missing periods
- [Components](/docs/components.md): every chart, with examples and props
- [Troubleshooting](/docs/troubleshooting.md): what to check if the chart does not appear or looks wrong
========================================================================
Title: Why EmKit
Source: https://emkit.embeddable.com/docs/why
========================================================================
# Why EmKit
What a chart library leaves to you, and what these components do instead.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
A chart library such as Chart.js or Recharts draws the chart. A dashboard also needs formatting, consistent colours, gap-free time series, loading and error states, export and translations around it. That work is the same in every product.
EmKit is that work, done once, behind one API: describe your fields, pass your rows. [The same card written both ways](/docs/why.md#the-same-card-written-twice) is below.
## What you would otherwise build
| What a dashboard needs | With a chart library | With EmKit |
|---|---|---|
| Number, currency and date formatting | Write formatters for ticks, tooltips and labels, per chart and per locale | Per field: prefix, suffix, decimals, currency, compact numbers, in the reader’s locale |
| One colour per value across the dashboard | Keep your own colour map and pass it to every chart | Automatic, shared by every chart, kept across refreshes; pin any value |
| Missing time periods | Lines join straight across gaps unless you fill them yourself | Filled per granularity and time zone, including ISO weeks and quarters |
| Changing granularity | Build a picker and re-bucket the data | Picker in the card header; you re-query at the chosen granularity |
| Comparison periods | Work out the previous range and overlay a second series | Comparison lines and KPI deltas from a second result set |
| Loading, empty and error states | Design and wire three states for every chart | Designed states in every card, driven by the same results prop |
| Card, title and info tooltip | Build the card around the canvas | Every chart is a finished card |
| CSV, Excel and PNG export | Write the export code | In every card’s menu, with a maximize view |
| Translations | Thread i18n through titles, axes, legends and tooltips | Titles, field names and values translate; English, German and French built in |
| Click events | Map canvas hit-tests back to your rows | Typed payloads with the clicked value and its time range |
| Tables, pivots and heat maps | A separate table library with its own data shape and styling | Same field descriptions, same response shape, same theme |
| Charts chosen by an AI model | Design a schema, validate the model’s output, map it to charts | A tool definition and a renderer that repairs common model mistakes |
## The same card, written twice
One revenue card with loading, empty and error states, formatted values and an export, as two complete files. On a chart library it is 97 lines before the CSS, with one export format, one language and no click handler. On EmKit it is 29, and [that file is running on the home page](/index.md).
```tsx title="RevenueByRegionChartJs.tsx"
import { useMemo } from 'react';
import { Bar } from 'react-chartjs-2';
import {
BarElement,
CategoryScale,
Chart,
Legend,
LinearScale,
Tooltip,
} from 'chart.js';
Chart.register(BarElement, CategoryScale, Legend, LinearScale, Tooltip);
type Row = { region: string; revenue: number };
type Props = {
rows?: Row[];
isLoading: boolean;
error?: string;
};
const money = new Intl.NumberFormat(navigator.language, {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
});
const downloadCsv = (rows: Row[]) => {
const lines = rows.map((row) => `"${row.region}",${row.revenue}`);
const csv = ['Region,Revenue', ...lines].join('\n');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
link.download = 'revenue-by-region.csv';
link.click();
};
export function RevenueByRegion({ rows, isLoading, error }: Props) {
const data = useMemo(
() => ({
labels: (rows ?? []).map((row) => row.region),
datasets: [
{
label: 'Revenue',
data: (rows ?? []).map((row) => row.revenue),
},
],
}),
[rows],
);
let body = (
money.format(Number(item.parsed.y)),
},
},
},
scales: {
y: {
ticks: { callback: (value) => money.format(Number(value)) },
},
},
}}
/>
);
if (isLoading && !rows) {
body =
;
} else if (error) {
body = {error}
;
} else if (!rows?.length) {
body = No results
;
}
return (
Revenue by region
downloadCsv(rows ?? [])}
>
Download CSV
{body}
);
}
```
```tsx title="RevenueByRegion.tsx"
import { BarChart, dimension, measure } from 'em-kit';
import type { BarChartOptionsClickArg } from 'em-kit';
type Props = {
rows?: { region: string; revenue: number }[];
isLoading: boolean;
error?: string;
onBarClicked?: (bar: BarChartOptionsClickArg) => void;
};
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { prefix: '$' },
});
export function RevenueByRegion(props: Props) {
const { rows, isLoading, error, onBarClicked } = props;
return (
);
}
```
Across a whole app the difference in lines is smaller, because fetching, filters and layout are yours either way. What stays different is that every card is finished, and finished the same way.
## What stays yours
- **Your data layer.** EmKit never fetches. Pass rows from any API, warehouse or cache.
- **Every display option.** Each one is an optional prop that overrides a default.
- **The look.** Design tokens for colour, type and spacing, and Chart.js options per chart type. See [Theming](/docs/theming.md).
- **Custom charts.** When no component fits, build one from the same toolkit. See [Build your own chart](/docs/build-your-own-chart.md).
## What it adds to your bundle
About 256 KB of JavaScript, minified and gzipped, with React left out: Chart.js and its plugins are about 86 KB of that. Importing every component costs about 4 KB more than importing one. Spreadsheet and image export (about 167 KB) load only when a reader chooses them from a chart’s menu.
## When it pays off
The saving grows with the number of cards. One chart on one page is quick to build on a chart library, by hand or with a coding assistant. EmKit earns its place when:
- **You have many cards.** Ten charts and tables that must load, fail, format and export alike. Each new card is a few lines, and none of them needs states or formatting of its own.
- **Customers see them.** Empty and error states, keyboard access to every control, readable axes and phone layouts are done and tested. A hand-built card gets them one bug report at a time.
- **You theme or translate.** One theme restyles every card, dark mode included. One locale changes every number and date, and the built-in text comes in English, German and French.
- **You need tables and export too.** Paginated and pivot tables, heat maps and KPIs take the same fields as the charts, and every card exports CSV, Excel and PNG.
- **A coding assistant writes the code.** It writes less, and you review less: the states, formatting and export are the library’s, already tested, not new code in every pull request.
## When to use something else
- **One or two simple charts.** A chart library is lighter: EmKit adds about 256 KB however few components you use.
- **A visualisation no dashboard chart covers**, such as a custom D3 graphic or a map. Use a lower-level library; the [build toolkit](/docs/build-your-own-chart.md) can still give it the same card, formatting and colours.
- **Control of every pixel.** The components take options, tokens and Chart.js settings, not replacement parts.
- **An app that is not React.** The components need React 19.
## If you need the data layer too
EmKit is Embeddable’s chart components as a standalone React library: you bring the data. Inside Embeddable the same components are called Remarkable Pro.
[Embeddable](https://embeddable.com) adds the data layer, multi-tenant security and self-serve dashboards for your customers.
========================================================================
Title: Troubleshooting
Source: https://emkit.embeddable.com/docs/troubleshooting
========================================================================
# Troubleshooting
What to check when a chart does not appear or looks wrong, by what you see on screen.
Each heading is what you see on screen.
## An error says components must be rendered inside ChartsProvider
The full message is `EmKit components must be rendered inside .` A chart is being rendered outside the provider. Wrap the app in it, as in [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
## An error says createContext only works in Client Components
This is Next.js, which renders every file as a Server Component unless it says otherwise, and the components read React context. Render `ChartsProvider` from a client file rendered by `app/layout.tsx`, and put `'use client';` on the first line of every file that renders a chart, as in [the quick start](/docs/quick-start.md#in-the-nextjs-app-router). The package does not add the directive itself.
On the server, a chart renders as its card, with its title and an empty `` that Chart.js draws in the browser; a KPI renders its number and a paginated table its rows. Three components wait for the browser: the scrollable table shows its empty state until it hydrates, and the donut and the donut with total draw their chart after they mount.
## Next.js says hydration failed, or that text did not match
The server and the browser formatted a number differently, because their locales differ, and React threw the server’s HTML away. Pin the locale in the provider, `theme={{ formatter: { locale: 'en-US' } }}`, as in the [client file](/docs/quick-start.md#in-the-nextjs-app-router), or pass the reader’s locale from the request.
## A server-rendered heat map has black cells
A colour you passed as a name, `rgb()` or `var()`, such as `minColor="mediumpurple"`, renders black on the server, and React keeps the server’s colours. Pass hex colours, such as `'#f4f0ff'`, for `minColor`, `midColor`, `maxColor` and the theme’s chart colours; the defaults are hex already. Or render the heat map in the browser only, with `next/dynamic(() => import('./HeatMapCard'), { ssr: false })` from a client file.
## Chart text is in a serif or system font
The provider loads Inter when it mounts: a stylesheet from `fonts.googleapis.com` and the font files from `fonts.gstatic.com`. If a network or a content security policy blocks them, charts draw in the system sans-serif font. A policy needs `https://fonts.googleapis.com` in `style-src` and `https://fonts.gstatic.com` in `font-src`.
To stop the request or serve the font yourself, replace `theme.fonts`: an empty `google` list turns the request off, and `custom` adds an `@font-face` from your own file.
```tsx title="SelfHostedFont.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const theme = {
fonts: {
google: [], // no request to Google Fonts
custom: [
{
family: 'Inter',
src: '/fonts/inter-variable.woff2',
descriptors: { weight: '100 900' },
},
],
},
};
export function SelfHostedFont({ children }: { children: ReactNode }) {
return {children} ;
}
```
## The chart is squashed to about 150 pixels tall
A chart fills its parent, and the parent has no height. Give the parent one, for example `style={{ height: 360 }}`.
## The chart is squashed to about 300 pixels wide
A chart fills its parent’s width, and the parent sits in a flex item with no width of its own, for example under `display: flex; place-items: center`. Give the flex item itself a width, such as `#root { width: 100% }`, or remove the centring. A width on the chart’s own wrapper does not help: it is a share of the same shrunken item.
## The time axis shows raw timestamps
Labels such as `2026-01-01T00:00:00.000Z` mean a time value has a `Z`, an offset, or is not a full timestamp. Send `YYYY-MM-DDTHH:mm:ss.SSS` with nothing after it. See [time values](/docs/time-series.md#time-values).
## A time chart draws its axis but no bars or line
The time values are not the start of each period, so no row matches a period on the axis. For `month`, send the first day of the month at `00:00:00.000`. See [time values](/docs/time-series.md#time-values).
## A time chart shows one empty period
The rows have no key that matches the dimension’s `name`, so the chart falls back to the current period. Use the same string for the row key and for `name`.
## A chart grouped by a time field shows no bars
A time dimension used as `groupBy` is read from the key `name.granularity`, such as `month.month`. Add that key to each row. See [time as the grouping field](/docs/time-series.md#time-as-the-grouping-field).
## The skeleton never goes away
`results.isLoading` is still `true`, or `results()` was called before the rows arrived. Pass `{ isLoading: false, data: rows }` once they do. See [Loading, empty and errors](/docs/loading-empty-and-errors.md).
========================================================================
Title: Describing your data
Source: https://emkit.embeddable.com/docs/describing-your-data
========================================================================
# Describing your data
Dimensions, measures, field options and the one response shape every chart takes.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
Charts do not guess what your columns mean. You describe each one once, as a **dimension** (something you group by) or a **measure** (a number), and reuse the description in every chart.
## A dimension and a measure
This chart groups by one dimension, the plan, and plots one measure, the recurring revenue.
```tsx title="PlanChart.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';
// A dimension is something you group by.
const plan = dimension({ name: 'plan', title: 'Plan' });
// A measure is a number. Display options go on `inputs`.
const mrr = measure({
name: 'mrr',
title: 'Monthly recurring revenue',
inputs: { currency: 'EUR', abbreviateLargeNumber: true },
});
// Each row has one key per field name.
const rows = [
{ plan: 'Starter', mrr: 84200 },
{ plan: 'Growth', mrr: 213500 },
{ plan: 'Enterprise', mrr: 391000 },
];
export function PlanChart() {
return (
);
}
```
Result: three bars, labelled €84K, €214K and €391K.
## Field properties
| Property | What it is |
|---|---|
| `name` | The key the chart reads from each row. |
| `title` | The label on axes, legends, tooltips and table headers. Defaults to `name`. |
| `type` | `string`, `number`, `time` or `boolean`. Dimensions default to `string` and measures to `number`. |
| `granularity` | Time dimensions only: `second`, `minute`, `hour`, `day`, `week`, `month`, `quarter` or `year`. See below. |
| `inputs` | The field options below. |
Set `granularity` on the dimension itself, at the top level of `dimension()`. It formats the axis (`month` shows `Jan 2026`) and fills missing periods. See [Time series](/docs/time-series.md).
A chart’s own `granularity` prop formats and fills nothing. It says which granularity the rows you pass are at now, so a click handler can turn a clicked period into a time range. Left out, it follows the dimension’s.
## Field options
Field options go in a field’s `inputs` and apply wherever the field is shown: axes, value labels, tooltips, legends and table cells.
| Option | For | What it does |
|---|---|---|
| `prefix` | Any field | Text before each value. `prefix: '$'` shows `$48,200`. |
| `suffix` | Any field | Text after each value. `suffix: '%'` shows `12%`. |
| `decimalPlaces` | Numbers | A fixed number of decimal places. `1` shows `12.5`. |
| `currency` | Numbers | An ISO currency code such as `EUR`. The value is formatted as money in the reader’s locale. |
| `abbreviateLargeNumber` | Numbers | Shortens large numbers: `1,200,000` becomes `1.2M`. |
| `displayName` | Any field | A label shown in place of `title`. |
| `maxCharacters` | Text | Cuts longer text off at this length and adds `...`. |
| `displayNullAs` | Any field | Text shown when a value is missing, such as `n/a`. |
| `showGranularityDropdown` | Time dimensions | Shows a granularity picker in the card. See [Time series](/docs/time-series.md#let-readers-change-the-granularity). |
| `dateBounds` | Time dimensions | `{ from, to }`: the first and last date on the axis. The default is the range of your rows. |
| `ignoreEmptyDate` | Time dimensions | Leaves out periods with no rows instead of showing them as gaps. |
| `color`, `lineColor` | Measures | A colour for this measure’s bars or line. Bar and line charts only. |
There is no date format option: dates follow the granularity and the [provider’s locale](/docs/localisation.md). Options that only one chart reads, such as a dashed line or a pivot total, are listed on that [component’s page](/docs/components.md).
## The response shape
Every component takes its rows through one prop, `results`. `results(rows)` builds it from an array, and counts as loading until `rows` has a value.
| Key | Type | What it is |
|---|---|---|
| `isLoading` | `boolean` | Whether a request is in flight. |
| `data` | Array of objects | Your rows. |
| `error` | `string` | A message to show in place of the chart. |
| `total` | `number` | The total row count, for paginated tables. |
[Loading, empty and errors](/docs/loading-empty-and-errors.md) shows what each combination draws.
========================================================================
Title: Time series
Source: https://emkit.embeddable.com/docs/time-series
========================================================================
# Time series
Time dimensions, the timestamp format, missing periods and the granularity picker.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
Give a dimension `type: 'time'` and set `granularity` on the dimension itself. The chart then formats the dates for that granularity, puts the rows in date order and adds the periods that have no row.
## A time dimension
Four weeks of signups, with one week missing from the rows.
```tsx title="SignupsByWeek.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';
const week = dimension({ name: 'week', title: 'Week', type: 'time', granularity: 'week' });
const signups = measure({ name: 'signups', title: 'Signups' });
// Each value is the start of its week (a Monday). There is no row for the
// week of 19 January, so the chart adds that week itself and leaves it empty.
const rows = [
{ week: '2026-01-05T00:00:00.000', signups: 212 },
{ week: '2026-01-12T00:00:00.000', signups: 248 },
{ week: '2026-01-26T00:00:00.000', signups: 231 },
{ week: '2026-02-02T00:00:00.000', signups: 274 },
];
export function SignupsByWeek() {
return (
);
}
```
Result: five weeks on the axis, with no bar for the week of 19 January.
## Time values
A time value has to be:
- **A string in the form `YYYY-MM-DDTHH:mm:ss.SSS`**, with no `Z` and no offset. Anything else is shown as raw text.
- **The start of its period**: the first of the month for `month`, the Monday for `week`. A row at any other time is left off the chart.
- **Under the dimension’s `name`** in each row.
The time zone used to work out date ranges comes from the provider: see [Localisation](/docs/localisation.md).
## Missing periods
Periods with no row are added between your first and last row, so a gap in the data shows as a gap. Set `dateBounds` to extend the axis past your rows, or `ignoreEmptyDate` to leave empty periods out: both are [field options](/docs/describing-your-data.md#field-options).
## Let readers change the granularity
Turn on `showGranularityDropdown`, keep the granularity in state and pass `setGranularity`. The card shows a picker from day to year. The chart does not re-bucket your rows: you query again at the new granularity.
```tsx title="OrdersOverTime.tsx"
import { useState } from 'react';
import { LineChart, dimension, measure, results } from 'em-kit';
import type { Granularity } from 'em-kit';
const orders = measure({ name: 'orders', title: 'Orders' });
export function OrdersOverTime() {
const [granularity, setGranularity] = useState('month');
const orderedAt = dimension({
name: 'ordered_at',
title: 'Order date',
type: 'time',
granularity,
inputs: { showGranularityDropdown: true }, // shows the picker
});
return (
);
}
// Stand-in for your API: a year of daily orders, summed into the
// requested buckets. Each bucket is keyed by the start of its period.
const days = Array.from({ length: 365 }, (_, i) => ({
date: new Date(Date.UTC(2025, 0, 1 + i)),
orders: 40 + Math.round(i / 9) + ((i * 37) % 23),
}));
const startOf = (date: Date, granularity: Granularity) => {
const [y, m, d] = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()];
if (granularity === 'year') return Date.UTC(y, 0, 1);
if (granularity === 'quarter') return Date.UTC(y, m - (m % 3), 1);
if (granularity === 'month') return Date.UTC(y, m, 1);
if (granularity === 'week') return Date.UTC(y, m, d - ((date.getUTCDay() + 6) % 7));
return Date.UTC(y, m, d);
};
function ordersBy(granularity: Granularity) {
const totals = new Map();
for (const day of days) {
const start = startOf(day.date, granularity);
totals.set(start, (totals.get(start) ?? 0) + day.orders);
}
return [...totals].map(([start, total]) => ({
ordered_at: new Date(start).toISOString().slice(0, 23), // drop the "Z"
orders: total,
}));
}
```
Result: a line of monthly totals and a picker set to Month. Choosing Week redraws the line with weekly totals.
## Time as the grouping field
One case needs a second key. When a time dimension is the `groupBy` of a stacked or grouped bar chart, or the point or group field of a scatter or bubble chart, the chart reads it from the key `name.granularity`, for example `month.month`.
```tsx title="RevenueByPlanAndMonth.tsx"
import { BarChartStacked, dimension, measure, results } from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const month = dimension({ name: 'month', title: 'Month', type: 'time', granularity: 'month' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });
const january = '2026-01-01T00:00:00.000';
const february = '2026-02-01T00:00:00.000';
// The month is the grouping field, so each row also has it under "month.month".
const rows = [
{ plan: 'Starter', month: january, 'month.month': january, revenue: 18400 },
{ plan: 'Starter', month: february, 'month.month': february, revenue: 21700 },
{ plan: 'Growth', month: january, 'month.month': january, revenue: 42900 },
{ plan: 'Growth', month: february, 'month.month': february, revenue: 47300 },
];
export function RevenueByPlanAndMonth() {
return (
);
}
```
Result: one stacked bar per plan, with a segment and a legend entry for each month.
========================================================================
Title: Loading, empty and errors
Source: https://emkit.embeddable.com/docs/loading-empty-and-errors
========================================================================
# Loading, empty and errors
Four states in every card, all driven by the results prop.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
A card draws one of four states from its `results` prop. There is nothing else to wire: pass the state of your request straight through.
## The four states
```tsx title="ChartStates.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
const rows = [
{ plan: 'Starter', customers: 1840 },
{ plan: 'Growth', customers: 920 },
{ plan: 'Enterprise', customers: 140 },
];
const grid = {
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
gridAutoRows: 280,
gap: 16,
};
export function ChartStates() {
const fields = { dimension: plan, measures: [customers] };
return (
);
}
```
Result: four cards showing a skeleton, a chart with a spinner in its header, “No results.” and “Something went wrong.”
| Value of results | The card shows |
|---|---|
| `{ isLoading: true }` | A skeleton. |
| `{ isLoading: true, data: rows }` | The chart it already has, with a spinner in the header. |
| `{ isLoading: false, data: [] }` | The empty state. |
| `{ isLoading: false, error: 'message' }` | The error state, with your message. |
The empty and error headings are translated with the rest of the built-in text: see [Localisation](/docs/localisation.md).
## From a request to results
The components never fetch, so something has to turn your request into that shape. This hook does it for any function that returns a promise of rows: a skeleton first, the rows when they arrive, and the message of the error if the request fails.
```tsx title="RevenueFromApi.tsx"
import { useEffect, useState } from 'react';
import { BarChart, dimension, measure, type DataResponse } from 'em-kit';
// Turns a function that returns a promise of rows into the `results` a card
// takes. `deps` are the values the request depends on, such as filters.
type Rows = DataResponse['data'];
export function useResults(load: () => Promise, deps: unknown[]): DataResponse {
const [state, setState] = useState({ isLoading: true });
useEffect(() => {
let current = true;
// The rows already on screen stay while the next ones load.
setState((previous) => ({ isLoading: true, data: previous.data }));
load().then(
(data) => current && setState({ isLoading: false, data }),
(error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
if (current) setState({ isLoading: false, error: message });
},
);
return () => {
current = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return state;
}
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
// Your data layer: anything that resolves to rows, or rejects with an Error.
// This one stands in for a request that takes a moment.
const rows = [
{ region: 'Europe', plan: 'Starter', revenue: 18400 },
{ region: 'Europe', plan: 'Team', revenue: 42900 },
{ region: 'Americas', plan: 'Starter', revenue: 21700 },
{ region: 'Americas', plan: 'Team', revenue: 38100 },
];
const fetchRevenueByPlan = (region: string) =>
new Promise((resolve) => {
setTimeout(() => resolve(rows.filter((row) => row.region === region)), 600);
});
export function RevenueFromApi({ region = 'Europe' }: { region?: string }) {
const results = useResults(() => fetchRevenueByPlan(region), [region]);
return (
);
}
```
With a data library you already have the three values. For TanStack Query: `results={{ isLoading: query.isPending, data: query.data, error: query.error?.message }}`.
========================================================================
Title: Events
Source: https://emkit.embeddable.com/docs/events
========================================================================
# Events
Click handlers that give you the clicked value, for cross-filtering and drill-downs.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
A chart calls your handler when a bar, point, slice or row is clicked, and passes the value that was clicked. Use it to filter another chart, open a detail view or navigate.
## Filter one chart from another
Click a region on the left to filter the chart on the right.
```tsx title="RegionFilter.tsx"
import { useState } from 'react';
import { BarChart, dimension, measure, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });
const byRegion = [
{ region: 'Americas', revenue: 527900 },
{ region: 'EMEA', revenue: 391500 },
{ region: 'APAC', revenue: 276300 },
];
const byRegionAndPlan = [
{ region: 'Americas', plan: 'Starter', revenue: 96400 },
{ region: 'Americas', plan: 'Growth', revenue: 181200 },
{ region: 'Americas', plan: 'Enterprise', revenue: 250300 },
{ region: 'EMEA', plan: 'Starter', revenue: 88100 },
{ region: 'EMEA', plan: 'Growth', revenue: 142900 },
{ region: 'EMEA', plan: 'Enterprise', revenue: 160500 },
{ region: 'APAC', plan: 'Starter', revenue: 71800 },
{ region: 'APAC', plan: 'Growth', revenue: 109300 },
{ region: 'APAC', plan: 'Enterprise', revenue: 95200 },
];
const grid = {
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
gridAutoRows: 320,
gap: 16,
};
export function RegionFilter() {
const [selected, setSelected] = useState('EMEA');
return (
{
if (dimensionValue != null) setSelected(String(dimensionValue));
}}
/>
row.region === selected))}
/>
);
}
```
Result: two bar charts. Clicking a region in the first changes the title and the bars of the second.
## What the handler receives
| Key | Value |
|---|---|
| `dimensionValue` | The clicked category, such as `'EMEA'`. `undefined` when the axis is a time dimension. |
| `dimensionTimeRange` | On a time axis, the clicked period as a `TimeRange`. `undefined` on a category axis. |
| `groupingDimensionValue`, `groupingDimensionTimeRange` | The same pair for the series that was clicked. Stacked and grouped charts only. |
| `measureValues` | Each measure’s value at the click, keyed by the measure’s `name`. Passed by , though their payload types leave it out. |
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Handler names
The prop is named after what is clicked, and the names differ: some end in `Clicked`, some in `Click`. This table is generated from each component’s props.
| Handler | Components |
|---|---|
| `onRowClicked` | `TableScrollable`, `TablePaginated` |
| `onBarClicked` | `BarChart`, `BarChartHorizontal`, `BarChartGrouped`, `BarChartGroupedHorizontal`, `BarChartStacked`, `BarChartStackedHorizontal`, `BarLineChart` |
| `onLineClicked` | `BarLineChart`, `LineChart`, `LineChartGrouped`, `LineChartComparison`, `LineChartWithKpiTabs`, `LineChartComparisonWithKpiTabs` |
| `onPointClicked` | `AreaChart` |
| `onAreaClicked` | `AreaChart` |
| `onSegmentClick` | `PieChart`, `DonutChart`, `DonutLabelChart` |
| `onPointClick` | `ScatterChart`, `BubbleChart` |
| `onCellClicked` | `HeatMap` |
`AreaChart` takes `onPointClicked`; `ScatterChart` and `BubbleChart` take `onPointClick`. Each [component page](/docs/components.md) has the payload type, and its playground logs the payload as you click.
Clicks need a pointer. For keyboard users, offer the same action another way: see [Accessibility](/docs/accessibility.md).
========================================================================
Title: Tables
Source: https://emkit.embeddable.com/docs/tables
========================================================================
# Tables
A paginated table you control: it asks for a page and you fetch it.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
`TablePaginated` holds no data of its own. It reports the page, the [page size](/docs/tables.md#page-size) and the sort. You fetch that slice and pass it back, so one page is in memory at a time.
## A paginated table
Here a local array stands in for the server. Sort a column or change page, and the table asks for the new slice.
```tsx title="CustomersTable.tsx"
import { useState } from 'react';
import { TablePaginated, dimension, measure, results } from 'em-kit';
import type { TablePaginatedProps } from 'em-kit';
type TableState = NonNullable;
type Customer = { customer: string; orders: number; revenue: number };
const customer = dimension({ name: 'customer', title: 'Customer' });
const orders = measure({ name: 'orders', title: 'Orders' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
export function CustomersTable() {
const [state, setState] = useState({ page: 0, isLoadingDownloadData: false });
// The table reports the page, the page size that fits its height, and the sort.
const { rows, total } = fetchCustomers(state);
return (
);
}
// Stand-in for your API: sort, then return one page and the total row count.
const names = [
'Alder & Finch', 'Brightwater', 'Cobalt Freight', 'Dunmore Labs', 'Eastgate Foods',
'Fernhill', 'Granite Works', 'Harbour Lane', 'Ironbridge', 'Juniper Health',
'Kestrel Air', 'Larkspur Media', 'Marlow & Reed', 'Northgate', 'Oakfield Dairy',
'Pinecrest', 'Quayside Books', 'Redwater', 'Saltmarsh', 'Thornbury',
'Umber Clay', 'Vale Cycles', 'Westbrook', 'Yarrow Tea',
];
const customers: Customer[] = names.map((customer, i) => ({
customer,
orders: 12 + ((i * i * 29) % 61),
revenue: 1800 + ((i * i * 7919) % 42000),
}));
function fetchCustomers({ page, pageSize = 10, sort }: TableState) {
const sorted = [...customers];
if (sort) {
const key = sort.id as keyof Customer;
const sign = sort.direction === 'desc' ? -1 : 1;
sorted.sort((a, b) => (a[key] > b[key] ? sign : a[key] < b[key] ? -sign : 0));
}
return {
rows: sorted.slice(page * pageSize, (page + 1) * pageSize),
total: customers.length,
};
}
```
Result: a table of five rows with sortable column headers and “Page 1 of 5” under it.
## What you pass
| Prop | What it is |
|---|---|
| `state`, `setState` | The table’s state, kept by you: `page`, `pageSize`, `sort` and `isLoadingDownloadData`. |
| `results` | The rows of the current page. |
| `totalResults` | `{ isLoading, total }`: the total row count, which sets the number of pages. |
| `allResults` | Every row, for the CSV and Excel export. `state.isLoadingDownloadData` turns `true` when a reader asks for one, so you can fetch them only then. |
## Page size
Left alone, the table shows as many rows as fit its height, so it fills a card of any size and follows it when the card is resized. For a fixed number, pass `pageSize`, for example `pageSize={5}`. Either way the table reports it in `state.pageSize`, so slice your rows by that.
Give a card with a `pageSize` room for its rows: about 40 pixels each, on top of the header row, the pager and the card’s title. Rows that do not fit scroll inside the card.
`setState` can be any function that stores the new state, not only the setter from `useState`.
## Other tables
The [scrollable table](/docs/components/table-scrollable.md) loads more rows as the reader scrolls. The [pivot table](/docs/components/pivot-table.md) and the [heat map](/docs/components/heat-map.md) take the same fields and the same `results`.
========================================================================
Title: Theming
Source: https://emkit.embeddable.com/docs/theming
========================================================================
# Theming
Design tokens, dark mode, pinned colours and Chart.js options.
Styling runs on CSS variables that start with `--em-`, and you can override any of them in the provider’s `theme.styles`. The default look is an orange and blue palette on a white card with a hairline border. Semantic tokens, such as the background, the text and the ten chart colours, restyle every component, and component tokens adjust one.
```tsx title="BrandCharts.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const theme = {
styles: {
'--em-sem-chart-color--1': '#0b6e99', // first series colour
'--em-sem-chart-color--2': '#23a6d5', // second series colour
'--em-sem-background': '#ffffff', // card background
'--em-card-border-radius': '0.5rem', // one component's token
},
};
export function BrandCharts({ children }: { children: ReactNode }) {
return {children} ;
}
```
> The tokens are set on the page root, so one theme is active per page. To see every chart restyle together, use the theme switcher (Default, Cool, Mono or Uluru) above the preview on any [component page](/docs/components.md).
## Dark mode
A dark theme is a handful of semantic overrides.
```tsx title="DarkModeCharts.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const dark = {
styles: {
'--em-sem-background': '#18181b',
'--em-sem-background--light': '#27272a',
'--em-sem-text': '#fafafa',
'--em-sem-text--muted': '#a1a1aa',
'--em-sem-text--subtle': '#52525b',
},
};
const light = {}; // no overrides: the default theme
export function DarkModeCharts({ isDark, children }: { isDark: boolean; children: ReactNode }) {
return {children} ;
}
```
## Pinned colours
Charts give each value a colour and keep it the same in every chart. To choose the colour yourself, map it in `theme.charts.backgroundColorMap`: the key is `dimensionName.value` for a dimension value, or the measure’s name.
```tsx title="PinnedColours.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const theme = {
charts: {
backgroundColorMap: {
// dimensionName.value
dimensionValue: {
'plan.Starter': '#fbbf24',
'plan.Growth': '#d97706',
'plan.Enterprise': '#92400e',
},
// measure name
measure: { revenue: '#0b6e99' },
},
},
};
export function PinnedColours({ children }: { children: ReactNode }) {
return {children} ;
}
```
## Chart.js options
Each chart type takes Chart.js options under `theme.charts`, merged over the defaults. The keys are `pieChartPro`, `donutChartPro`, `donutLabelChartPro`, `barChartDefaultPro`, `barChartDefaultHorizontalPro`, `barChartGroupedPro`, `barChartGroupedHorizontalPro`, `barChartStackedPro`, `barChartStackedHorizontalPro`, `lineChartDefaultPro`, `lineChartGroupedPro`, `lineChartComparisonDefaultPro`, `barLineChartPro`, `areaChartPro`, `scatterChartPro`, `bubbleChartPro` and `funnelChartPro`. This example turns animation off for readers who ask for reduced motion.
```tsx title="StillCharts.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
// Chart.js options for one chart type, merged over the defaults.
const noAnimation = { options: { animation: false as const } };
const still = {
charts: {
barChartDefaultPro: noAnimation,
lineChartDefaultPro: noAnimation,
pieChartPro: noAnimation,
},
};
const animated = {}; // no overrides: the default theme
export function StillCharts({ children }: { children: ReactNode }) {
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
return {children} ;
}
```
========================================================================
Title: Localisation
Source: https://emkit.embeddable.com/docs/localisation
========================================================================
# Localisation
Language, number and date formats, time zone and your own translations.
Three settings, each set on its own: the language of the built-in text, the locale for numbers and dates, and the time zone for date ranges. German labels with Swiss number formats is `language: 'de'` with `locale: 'de-CH'`.
```tsx title="GermanCharts.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const theme = {
i18n: { language: 'de' }, // built-in text: 'en', 'de' or 'fr'
formatter: { locale: 'de-DE' }, // numbers, currencies and dates
};
export function GermanCharts({ children }: { children: ReactNode }) {
return (
{children}
);
}
```
Without `formatter.locale`, numbers and dates follow the browser’s language. To see every chart switch language, use the EN, DE and FR buttons above the preview on any [component page](/docs/components.md).
## Translate your own titles and values
Write a title or description as `key|fallback`. Field titles are looked up at `measure.` and `dimension.`, and dimension values at `dimension..`.
```tsx title="TranslatedChart.tsx"
import { BarChart, ChartsProvider, dimension, measure, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { currency: 'EUR' } });
const rows = [
{ region: 'North America', revenue: 527900 },
{ region: 'Europe', revenue: 391500 },
];
const theme = {
i18n: {
language: 'de',
translations: {
de: {
translation: {
dashboard: { revenue: 'Umsatz nach Region' }, // your own key, used by the title
measure: { revenue: 'Umsatz' }, // field titles
dimension: {
region: 'Region',
'region.North America': 'Nordamerika', // dimension values
'region.Europe': 'Europa',
},
},
},
},
},
formatter: { locale: 'de-DE' },
};
export function TranslatedChart() {
return (
);
}
```
## Add a language
Add a bundle under a new language code. Any key you leave out falls back to English, so you can translate in stages. The built-in keys are in `defaultTheme.i18n.translations.en`.
```tsx title="SpanishCharts.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider } from 'em-kit';
const theme = {
i18n: {
language: 'es',
translations: {
es: {
translation: {
charts: {
emptyTitle: 'Sin resultados.',
emptyMessage: 'No hay datos para mostrar.',
errorTitle: 'Algo ha fallado.',
'menuOptions.downloadCSV': 'Descargar CSV',
},
},
},
},
},
formatter: { locale: 'es-ES' },
};
export function SpanishCharts({ children }: { children: ReactNode }) {
return {children} ;
}
```
========================================================================
Title: Card menu
Source: https://emkit.embeddable.com/docs/card-menu
========================================================================
# Card menu
Choose the entries in a card’s menu, add your own, and change what the downloads do.
A chart’s card has a menu behind the ⋮ button in its header: download the data as CSV or XLSX, download the chart as a PNG, or maximize the card. You choose the entries per chart, and you can add your own or change what a built-in one does.
## Choose the entries for a chart
`menuOptions` lists the entries a chart offers, by `value`. The built-in values are `csv`, `xlsx`, `png` and `maximize`, and each [component page](/docs/components.md) gives its default: all four for most.
Pass `[]` for no menu at all. `hideMenu` goes further and leaves out the card’s whole header: title, description and menu.
## Add your own entry
Entries are defined in the theme, at `defaults.chartMenuOptions`. Add yours to the built-in list, then name its `value` in the `menuOptions` of each chart that should offer it.
```tsx title="CopyJsonMenu.tsx"
import { BarChart, ChartsProvider, defaultTheme, dimension, measure, results } from 'em-kit';
import type { ChartCardMenuOption } from 'em-kit';
const copyJson: ChartCardMenuOption = {
value: 'json',
labelKey: 'Copy as JSON',
onClick: ({ data }) => navigator.clipboard.writeText(JSON.stringify(data, null, 2)),
};
const theme = {
defaults: { chartMenuOptions: [...defaultTheme.defaults.chartMenuOptions, copyJson] },
};
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });
const rows = [
{ region: 'Americas', revenue: 527900 },
{ region: 'EMEA', revenue: 391500 },
{ region: 'APAC', revenue: 276300 },
];
export function CopyJsonMenu() {
return (
);
}
```
An override replaces the list, which is why the example starts from `defaultTheme.defaults.chartMenuOptions`. The menu button shows a spinner until `onClick` returns or, when it returns a promise, until that settles.
## What an entry receives
| Key | Value |
|---|---|
| `title` | The card’s title, translated. |
| `data` | The chart’s rows. On a table, every row from `allResults`, not the page on screen. |
| `dimensionsAndMeasures` | The fields the chart draws. |
| `containerRef`, `cardRef` | DOM refs to the chart’s body and to the whole card. |
| `theme` | The active theme, with its formatter and translations. |
| `options` | The entry’s own `options`. |
On a table, an entry waits for `allResults`, as the built-in downloads do: see [Tables](/docs/tables.md#what-you-pass).
## Change a built-in entry
Map over the built-in list and return a changed copy of the entry. To keep the download and add a step, call the original `onClick` from yours.
```tsx title="CustomDownloads.tsx"
import type { ReactNode } from 'react';
import { ChartsProvider, defaultTheme } from 'em-kit';
import type { ChartCardMenuOption } from 'em-kit';
const options = defaultTheme.defaults.chartMenuOptions.map((option): ChartCardMenuOption => {
// PNG: a white background, and the whole card rather than the chart alone.
if (option.value === 'png') {
return { ...option, options: { pngBackgroundColor: '#ffffff', captureFullCard: true } };
}
// CSV: note the download, then run the built-in one.
if (option.value === 'csv') {
return {
...option,
onClick: (args) => {
console.info(`CSV downloaded: ${args.title}`);
return option.onClick(args);
},
};
}
return option;
});
const theme = { defaults: { chartMenuOptions: options } };
export function CustomDownloads({ children }: { children: ReactNode }) {
return {children} ;
}
```
The PNG entry reads two settings from its `options`. `pngBackgroundColor` is any CSS colour, and the image is transparent without it; `captureFullCard` includes the card’s title and description.
## Labels, icons and order
- **Labels.** `labelKey` is a translation key, and text with no translation is shown as written, so a plain label works. For a translated label, add the key to your [translations](/docs/localisation.md#add-a-language) before the first chart renders.
- **Icons.** `iconSrc` is an SVG as a data URL: `data:image/svg+xml,` followed by the URL-encoded markup.
- **Order.** Entries appear in the order of the theme’s list, whatever the order of `menuOptions`.
- **No spinner.** `isInstantAction: true` runs an entry at once, without the spinner.
- **Errors.** An error thrown by `onClick` is not caught. Handle a failure inside it, for example to tell the reader.
========================================================================
Title: Accessibility
Source: https://emkit.embeddable.com/docs/accessibility
========================================================================
# Accessibility
What keyboard and screen-reader users get from each component today, and what is left to you.
KPIs and tables are HTML, so assistive technology can read them as they are. Charts are drawn on a canvas, which holds no data a screen reader can reach, so each chart needs a text alternative from you. This page lists what the components do today, gaps included.
## Charts
- **The title and description are text.** The card’s `title` is a heading and its `description` is a paragraph. Both are read aloud.
- **The plot is named, not described.** It is a `` named after the card’s title and description. A screen reader hears that name, not the values.
- **The plot needs a pointer.** Tooltips and click handlers work with a mouse or touch. Nothing inside the plot takes keyboard focus.
- **Series differ by colour only.** On line charts, the `dashedLine` field option adds a second cue.
- **Charts animate when they draw**, whatever the reader’s reduced-motion setting. [Chart.js options](/docs/theming.md#chartjs-options) shows how to turn that off.
## KPIs
The title, the number and the change are all text. The change carries a plus or minus sign as well as a colour and an arrow, so it does not depend on colour.
## Tables
- Tables are a real `` with column headers. The pivot table and the heat map add row headers.
- A sortable column header is a button with a spoken label, and its column carries `aria-sort`.
- The pagination buttons are labelled “First page”, “Previous page”, “Next page” and “Last page”.
- An expandable pivot row is a button with `aria-expanded`. Every heat map cell is a button that takes focus, whether or not you pass `onCellClicked`.
Three gaps:
- The sort and pagination labels are in English, whatever language the provider is set to.
- `onRowClicked` needs a pointer. Rows do not take focus.
- Each body cell holds a copy button, shown on hover and whenever focus is in its cell: a table of many cells is many keyboard stops.
## The card: menu, picker and states
- **Export menu.** It works from the keyboard, with the keys below. Its button is named after the chart (“Chart menu: Revenue by region”) in the provider’s language. Its entries are yours to change: see [Card menu](/docs/card-menu.md).
- **Maximised view.** It opens as a modal dialog named after the chart’s title, with a “Minimize” button. Focus is not put back on the card when it closes.
- **Granularity picker.** A menu button that shows the current value, with the same keys as the export menu.
- **States.** The empty and error states are text. The loading skeleton has none, and a change of state is not announced: the card has no live region.
- **Focus.** Buttons keep the browser’s default focus ring.
## Keyboard
| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Anywhere | Moves between the controls of a card: export menu, granularity picker, column headers, cell copy buttons and pagination. |
| `Enter` or `Space` | Export menu button, granularity picker | Opens the menu and moves focus to its first item. |
| `↓`, `↑` | Open menu | Moves to the next or previous item, wrapping at the ends. |
| `Home`, `End` | Open menu | Moves to the first or last item. |
| `Enter` | Menu item | Chooses it. |
| `Esc` | Open menu | Closes it and returns focus to its button. |
| `Esc` | Maximised view | Closes it. |
| `Enter` or `Space` | Column header | Sorts ascending, then descending, then clears the sort. |
| `Enter` or `Space` | Expandable pivot row | Opens or closes the row. |
| `Enter` or `Space` | Heat map cell | Calls `onCellClicked`, if you passed one. |
## What to do in your app
1. Give every chart a `title`, and state its main finding in `description`. “Revenue rose 37% from January to June” is read aloud; the bars are not.
2. Offer the numbers as a table near each chart. The same fields and rows work in a [table component](/docs/tables.md).
3. Never make a click handler the only way to reach something. Add a link, button or filter outside the chart that does the same.
4. Check the contrast of your [theme](/docs/theming.md): text tokens against their background, and neighbouring chart colours against each other.
5. Turn animation off for readers who ask for reduced motion, as in [Chart.js options](/docs/theming.md#chartjs-options).
========================================================================
Title: Use with AI
Source: https://emkit.embeddable.com/docs/ai
========================================================================
# Use with AI
Point Claude Code, Cursor or ChatGPT at these docs, so the code they write for EmKit is correct.
These docs are published as Markdown as well as HTML, so a coding assistant can read them without a browser.
| URL | What it holds |
|---|---|
| `https://emkit.embeddable.com/llms.txt` | Every page with a one-line description and a link to its Markdown. |
| `https://emkit.embeddable.com/llms-full.txt` | Every page in one file. Its header, and its line in `llms.txt`, give its size. |
| A docs page’s URL plus `.md` | That page as Markdown, for example `https://emkit.embeddable.com/docs/components/bar-chart.md`. The home page is `https://emkit.embeddable.com/index.md`; playgrounds have none. |
## Claude Code
Add this to `CLAUDE.md` at the root of your repository.
```text title="CLAUDE.md"
For charts, KPIs and data tables, use the em-kit package (EmKit). Read https://emkit.embeddable.com/llms.txt first, then the .md page of each component you use. Fetch them with curl, not WebFetch, which returns a summary: the code and the props table must come through word for word.
```
## Cursor
In Cursor’s settings, under Indexing & Docs, add `https://emkit.embeddable.com/llms-full.txt` as a doc, every page in one file, and mention it with `@Docs`. For a standing rule, add this to `AGENTS.md` at the root of your project, or to a rule file under `.cursor/rules/`.
```md title="AGENTS.md"
## Charts
Use the em-kit package (EmKit) for charts, KPIs and data tables.
- Index of the docs: https://emkit.embeddable.com/llms.txt
- One component: https://emkit.embeddable.com/docs/components/.md, where is the export name in kebab-case: BarChartStacked is bar-chart-stacked.md
```
## ChatGPT
Start your message with the index and the page of the component you need, as below. If your plan cannot open links, paste that page into the chat.
```text
Read https://emkit.embeddable.com/llms.txt and https://emkit.embeddable.com/docs/components/line-chart.md. Using only the em-kit components documented there, write a React component that shows monthly revenue as a line chart. Include the imports, sample rows and the provider.
```
## One component at a time
Every [component page](/docs/components.md) has a **Copy page as Markdown** button. It copies the page as text an assistant can read: purpose, install, a complete example and the props table.
To let a model in your own product answer with a chart, see [Charts from a model](/docs/charts-from-a-model.md).
========================================================================
Title: Charts from a model
Source: https://emkit.embeddable.com/docs/charts-from-a-model
========================================================================
# Charts from a model
Let a model choose the chart: it returns JSON, and one component renders it.
`ChartFromSpec` renders a chart from a `ChartSpec`: plain JSON that names the chart kind, the fields and the rows. A model writes that JSON through a tool call, so an assistant in your product can answer with a chart.
## 1. Ask the model for a spec
`renderChartTool` is the tool definition. `chartGuidance` is a system prompt that tells the model which chart to pick and how to shape the rows. Neither imports React, so both can run in a server route.
The sample uses the Anthropic SDK. Install it in the project that runs your server route.
```bash
npm install @anthropic-ai/sdk
```
```ts title="chartFor.ts"
import Anthropic from '@anthropic-ai/sdk';
import type { ChartSpec } from 'em-kit';
import { chartGuidance, renderChartTool } from 'em-kit/ai';
const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY
// Ask a question about some rows. Returns the spec of the chart that answers
// it, or null when the model replied in text instead.
export async function chartFor(question: string, rows: object[]): Promise {
const response = await anthropic.messages.create({
model: 'claude-opus-5-5',
max_tokens: 16000,
system: chartGuidance, // which chart to pick and how to shape the rows
tools: [renderChartTool], // the JSON Schema of every chart spec
messages: [{ role: 'user', content: `${question}\n\n${JSON.stringify(rows)}` }],
});
for (const block of response.content) {
if (block.type === 'tool_use' && block.name === renderChartTool.name) {
return block.input as ChartSpec;
}
}
return null;
}
```
With OpenAI, pass `renderChartToolOpenAI` as the tool and parse `tool_calls[0].function.arguments`.
## 2. Render the spec
Pass the spec to `ChartFromSpec`. Each click comes back as a serialisable `ChartIntent`, and `intentToPrompt()` turns it into a sentence you can send as the next message.
```tsx title="AnswerChart.tsx"
import { useState } from 'react';
import { ChartFromSpec, intentToPrompt } from 'em-kit';
import type { ChartSpec } from 'em-kit';
// What the model's render_chart call contains: plain JSON.
const spec: ChartSpec = {
chart: 'bar',
title: 'Signups by channel',
dimension: { name: 'channel', title: 'Channel' },
measures: [{ name: 'signups', title: 'Signups' }],
rows: [
{ channel: 'Organic search', signups: 1840 },
{ channel: 'Paid search', signups: 1210 },
{ channel: 'Referral', signups: 760 },
{ channel: 'Partner', signups: 430 },
],
};
export function AnswerChart() {
const [followUp, setFollowUp] = useState('Click a bar to see the follow-up it produces.');
return (
setFollowUp(intentToPrompt(intent))}
/>
{followUp}
);
}
```
Result: a bar chart of the four channels. Clicking the “Paid search” bar shows the sentence `The user clicked channel "Paid search" on the "Signups by channel" chart. Drill into it.`
`chrome` sets how much of the card is drawn: `card`, `plain` (no export menu) or `bare` (no header or background, for a chat bubble).
## What happens to a bad spec
The renderer does not trust its input. Dates and numbers sent as text are converted, an unknown chart kind falls back to a table of the rows, and an invalid spec shows the error card instead of throwing.
## What the model sees
The tool is named `render_chart`. Its schema is generated from the `ChartSpec` type, so it cannot drift from the renderer. To validate a spec on your server, import `chartSpecSchema` from `em-kit/ai`.
The full JSON Schema is `renderChartTool.input_schema` (18.8 KB). Its `chart` field takes one of: `bar`, `barHorizontal`, `barGrouped`, `barGroupedHorizontal`, `barStacked`, `barStackedHorizontal`, `line`, `lineGrouped`, `lineWithKpiTabs`, `lineComparison`, `lineComparisonWithKpiTabs`, `area`, `barLine`, `pie`, `donut`, `donutLabel`, `scatter`, `bubble`, `kpi`, `kpiComparison`, `table`, `heatmap`, `pivot`.
The guidance is plain text, about 4 KB:
```text
Charts: call render_chart to show data. One call per chart; pick the kind from the shape of the data.
Choosing `chart`:
- bar: one measure (or a few) compared across categories.
- barHorizontal: the same, when labels are long or there are more than ~8 categories.
- barGrouped, barGroupedHorizontal: a measure split by a second category (`groupBy`), parts side by side.
- barStacked, barStackedHorizontal: the same split stacked, to show how the parts add up to a total.
- line: a trend over time or another ordered x axis; one line per entry in `measures`.
- lineGrouped: one measure drawn as a line per value of `groupBy`.
- lineWithKpiTabs: a trend with one KPI tab per measure (the tab shows the measure's total);
good for dashboards-in-one-chart like "revenue / orders / signups over time".
- lineComparison: this period against a previous one (`rows` vs `comparisonRows`, aligned by
position); set `comparisonLabel`, e.g. "Previous period".
- lineComparisonWithKpiTabs: the comparison plus KPI tabs; headline numbers are derived from the
rows unless `kpiRows`/`kpiComparisonRows` are given.
- area: volume over time; add `groupBy` to stack the parts.
- barLine: bars (`barMeasures`) plus lines (`lineMeasures`) on a second axis, e.g. volume and a rate.
- pie, donut: only shares of a whole: at most 8 slices, non-negative values. Otherwise use a bar chart.
- donutLabel: a donut with a headline number in the center (`innerLabel`: { text, value } — the
value defaults to the sum of the rows).
- scatter: the relationship between two measures, one point per `pointDimension`.
- bubble: scatter plus a third measure as point size (`bubbleSizeMeasure`).
- kpi: one headline number.
- kpiComparison: a number against another period (`value`, `comparisonValue`); set
`options.reversePositiveNegativeColors` when lower is better.
- table: row-level detail or exact values; mixed text and number `columns`.
- heatmap: one measure across two categories as colour intensity (weekday by hour).
- pivot: the same two-way layout with numbers in the cells, several measures and optional sub-rows.
Data rules:
- `rows` is an array of flat objects in long format: one row per category and group combination.
Never spread groups across columns; name the group field in `groupBy` instead.
- Use only values from the data you were given. Omit `rows` while data is loading (set `loading: true`),
or set `error` to show a message instead.
- A field is a row key as a bare string ("revenue"), or { name, title?, type?, role?, format? } when it
needs a display title or formatting. `type` ('string' | 'number' | 'time' | 'boolean') is inferred from rows.
- Time values are zone-less ISO strings: "2025-03-01T00:00:00.000" ("2025-03-01" is also accepted).
Never add a Z or a UTC offset.
- When the category axis (`dimension` or `xAxis`) is a time field, set `granularity` on the chart,
never on the field: second, minute, hour, day, week, month, quarter or year.
The rows must already be bucketed at that granularity.
- Format numbers with the field's `format`: { prefix: "$", suffix: "%", decimalPlaces: 1 }.
Also available: displayName, displayNullAs, maxCharacters.
- Options are always written in vertical orientation, including for horizontal variants:
`options.xAxisLabel` labels the category axis; `options.yAxisLabel`, `options.yAxisRangeMin`
and `options.yAxisRangeMax` the value axis. The renderer swaps them.
- `kpi` and `kpiComparison` accept `value` (and `comparisonValue`) instead of `rows`.
- In `table`, set a column's `role` ('dimension' | 'measure') only when it is ambiguous.
- Give every chart a short `title` that says what it shows.
```
[Try your own specs in the AI chat example](/examples/ai-chat.md).
========================================================================
Title: Build your own chart
Source: https://emkit.embeddable.com/docs/build-your-own-chart
========================================================================
# Build your own chart
The toolkit the built-in charts are made from, for the charts you add yourself.
The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).
When no component fits, build one from the toolkit the built-in charts use, imported from `em-kit/build`. Your chart then formats values, picks colours, fills time gaps and draws the same states as the rest.
| For | Use |
|---|---|
| Theme and translations | `useChartsTheme`, `i18nSetup`, `resolveI18nProps` |
| Formatting every value | `getThemeFormatter(theme).data(field, value)` |
| Time series | `useFillGaps`, `getDimensionWithGranularity`, `getTimeRangeFromDimensionValue` |
| Comparison periods | `defaultComparisonPeriodOptions`, `getComparisonPeriodDateRange` |
| Series colours | `getChartColors`, `getDimensionMeasureColor` |
| Theme tokens | `getStyle`, `getStyleNumber` |
| Card, states and menu | `ChartCard`, `EditorCard` |
| Chart.js primitives | `BarChart`, `LineChart`, `PieChart`, `DonutChart`, `KpiChart` |
| Data and option builders | `getBarChartProData`, `getBarChartProOptions`, `getLineChartProData`, `getLineChartProOptions`, `getPieChartProData`, `getPieChartProOptions` |
## Example: a line with a target
The built-in line chart plus a dashed target line. Everything except the target dataset comes from the toolkit, which is why it matches the other charts.
```tsx title="TargetLineChart.tsx"
import type { DataResponse, Dimension, Measure } from 'em-kit';
import {
ChartCard,
LineChart,
getLineChartProData,
getLineChartProOptions,
getStyle,
getStyleNumber,
i18nSetup,
resolveI18nProps,
useChartsTheme,
useFillGaps,
} from 'em-kit/build';
type TargetLineChartProps = {
xAxis: Dimension;
measure: Measure;
results: DataResponse;
target: number;
title?: string;
description?: string;
};
// A line chart with a flat target line: the built-in line chart plus one
// extra dataset, assembled from the same toolkit the built-in charts use.
export const TargetLineChart = (props: TargetLineChartProps) => {
const { xAxis, measure, target } = props;
const theme = useChartsTheme();
i18nSetup(theme);
const { title, description } = resolveI18nProps(props);
// Missing months become empty buckets instead of a line jumping across them.
const results = useFillGaps({ results: props.results, dimension: xAxis });
// Labels, values, colours and dashing exactly as does them.
const data = getLineChartProData(
{ data: results.data, dimension: xAxis, measures: [measure], hasMinMaxYAxisRange: false },
theme,
);
// The new part. A chrome colour (not a series colour) from a theme token,
// so it follows the theme and dark mode.
const targetColor = getStyle('--em-sem-text--muted', '#71717a');
const dash = getStyleNumber('--em-linechart-line-dash', '0.25rem') ?? 4;
data.datasets.push({
label: 'Target',
data: (data.labels ?? []).map(() => target),
borderColor: targetColor,
backgroundColor: targetColor,
borderDash: [dash * 2, dash],
pointRadius: 0,
pointHoverRadius: 0,
});
// The value-formatting overlay. It formats each dataset with the measure at
// the same index, so the target is listed twice to share its formatting.
// merges this onto its own themed base options.
const options = getLineChartProOptions(
{ data, dimension: xAxis, measures: [measure, measure] },
theme,
);
return (
);
};
```
Use it like any built-in chart:
```tsx title="RevenueTarget.tsx"
import { dimension, measure, results } from 'em-kit';
import { TargetLineChart } from './TargetLineChart';
const month = dimension({ name: 'month', title: 'Month', type: 'time', granularity: 'month' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });
const rows = [
{ month: '2026-01-01T00:00:00.000', revenue: 48200 },
{ month: '2026-02-01T00:00:00.000', revenue: 51900 },
{ month: '2026-03-01T00:00:00.000', revenue: 55400 },
{ month: '2026-04-01T00:00:00.000', revenue: 61300 },
{ month: '2026-05-01T00:00:00.000', revenue: 58700 },
{ month: '2026-06-01T00:00:00.000', revenue: 66100 },
];
export function RevenueTarget() {
return (
);
}
```
Result: the revenue line with a dashed line at $55,000 and “Target” in the legend.
## Rules that keep it consistent
- Format every value with `getThemeFormatter(theme).data(field, value)`, so the field’s options and the locale apply.
- A `Pro` options builder only formats values. Pass it as `options` to a primitive, which merges it onto its themed base.
- Take data colours from `getChartColors()` and `getDimensionMeasureColor()`, so a value keeps its colour across charts. Read everything else from a theme token with `getStyle()` during render, so it follows theme changes.
- Wrap the chart in `ChartCard` and pass it the filled `results`. It draws the skeleton, the empty and error states and the export menu.
========================================================================
Title: Components
Source: https://emkit.embeddable.com/docs/components
========================================================================
# Components
32 components in 9 groups. Each links to its own page: purpose, install, usage, examples and props. Live previews: https://emkit.embeddable.com/docs/components
## KPIs (2)
- [KPI number](/docs/components/kpi-number.md) (` `): A single headline figure, formatted with the measure’s currency, prefix, suffix and locale.
- [KPI with comparison](/docs/components/kpi-number-comparison.md) (` `): A headline figure with its change against a comparison period, coloured by direction.
## Bars (5)
- [Bar chart](/docs/components/bar-chart.md) (` `): Compare one or more measures across the values of a dimension.
- [Horizontal bar chart](/docs/components/bar-chart-horizontal.md) (` `): Bars laid out horizontally, for long category labels or ranked lists.
- [Grouped bar chart](/docs/components/bar-chart-grouped.md) (` `): Side-by-side bars for each value of a second dimension.
- [Grouped horizontal bar chart](/docs/components/bar-chart-grouped-horizontal.md) (` `): Side-by-side bars for each value of a second dimension, laid out horizontally.
- [Bar and line combo](/docs/components/bar-line-chart.md) (` `): Bars and a line on independent axes, for volume against a rate or count.
## Stacked (3)
- [Stacked bar chart](/docs/components/bar-chart-stacked.md) (` `): Show the composition of each bar by a second dimension.
- [Stacked horizontal bar chart](/docs/components/bar-chart-stacked-horizontal.md) (` `): The composition of each bar by a second dimension, laid out horizontally for long labels.
- [Stacked area chart](/docs/components/area-chart.md) (` `): Stacked areas showing how segments contribute to a total over time.
## Lines (5)
- [Line chart](/docs/components/line-chart.md) (` `): A time series with gap filling and a built-in granularity switcher.
- [Multi-series line chart](/docs/components/line-chart-grouped.md) (` `): One line per value of a dimension, over time.
- [Line chart with comparison](/docs/components/line-chart-comparison.md) (` `): The current period against an earlier one, each on its own date axis.
- [Line chart with KPI tabs](/docs/components/line-chart-with-kpi-tabs.md) (` `): A tab per measure showing its total; selecting a tab switches the plotted line.
- [Line chart with comparison and KPI tabs](/docs/components/line-chart-comparison-with-kpi-tabs.md) (` `): KPI tabs showing each measure’s change against the previous period, over a line chart that overlays both.
## Pies (3)
- [Pie chart](/docs/components/pie-chart.md) (` `): Share of a total across a small number of categories.
- [Donut chart](/docs/components/donut-chart.md) (` `): A pie with the centre cut out, for a lighter visual weight.
- [Donut with total](/docs/components/donut-label-chart.md) (` `): A donut with a headline figure in the centre.
## Funnels (1)
- [Funnel chart](/docs/components/funnel-chart.md) (` `): How much of a total survives each step of a process, in order.
## Scatter (2)
- [Scatter chart](/docs/components/scatter-chart.md) (` `): Plot two measures against each other, one point per dimension value.
- [Bubble chart](/docs/components/bubble-chart.md) (` `): A scatter chart with a third measure encoded as bubble size.
## Tables (4)
- [Paginated table](/docs/components/table-paginated.md) (` `): A controlled table: you own paging and sorting and pass in the current page of rows.
- [Scrollable table](/docs/components/table-scrollable.md) (` `): An infinite-scroll table: you serve pages of 50 rows and it appends each as the reader scrolls.
- [Pivot table](/docs/components/pivot-table.md) (` `): Measures cross-tabulated by a row and a column dimension, with totals.
- [Heat map](/docs/components/heat-map.md) (` `): A grid of cells coloured by value, for spotting hot and cold combinations.
## Controls (7)
- [Date range picker](/docs/components/date-range-picker.md) (` `): Preset ranges such as “Last 30 days”, with a calendar for any other range.
- [Custom date range picker](/docs/components/date-range-picker-custom.md) (` `): A calendar for picking any start and end date, with no presets.
- [Granularity select](/docs/components/granularity-select.md) (` `): Day, week, month, quarter or year: the period a time series is grouped by.
- [Comparison period select](/docs/components/comparison-period-select.md) (` `): Previous period, previous year and the like: what the current figures are compared with.
- [Single select](/docs/components/single-select.md) (` `): A searchable dropdown of a field’s values, one of which can be chosen.
- [Multi select](/docs/components/multi-select.md) (` `): A searchable dropdown of a field’s values, any number of which can be chosen.
- [Text field](/docs/components/text-field.md) (` `): A free-text input, reported once the reader pauses typing.
========================================================================
Title: KPI number
Source: https://emkit.embeddable.com/docs/components/kpi-number
========================================================================
# KPI number
A single headline figure, formatted with the measure’s currency, prefix, suffix and locale.
- Component: ` `, imported from `em-kit`
- Required props: `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/kpi-number
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/kpi-number/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. The card fills its parent, so the parent needs a height; the number scales to fit. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, KpiNumber, measure, results } from 'em-kit';
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const totalRows = [{ customers: 476 }];
```
## States
The card draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Compact
A large figure shortened to “1.2M”, still in the reader’s locale. `abbreviateLargeNumber` is a field option on the measure; the currency stays.
```tsx
import { ChartsProvider, KpiNumber, measure, results } from 'em-kit';
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const totalRows = [{ revenue: 837479 }];
```
### Fixed font size
A set font size instead of auto-fitting the card, for a row of KPIs that should match. Without `fontSize` the number grows and shrinks to fill the card.
```tsx
import { ChartsProvider, KpiNumber, measure, results } from 'em-kit';
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const totalRows = [{ customers: 476 }];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `measure` | `Measure` | yes | | The number to show. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `fontSize` | `number` | no | | Font size of the headline number in pixels. By default it grows and shrinks to fit the card. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: KPI with comparison
Source: https://emkit.embeddable.com/docs/components/kpi-number-comparison
========================================================================
# KPI with comparison
A headline figure with its change against a comparison period, coloured by direction.
- Component: ` `, imported from `em-kit`
- Required props: `measure`, `primaryDateRange`, `results`, `resultsComparison` and `comparisonDateRange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/kpi-number-comparison
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/kpi-number-comparison/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. The card fills its parent, so the parent needs a height; the number scales to fit. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-06-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2026-05-02'),
to: new Date('2026-05-31'),
};
const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```
## States
The card draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Change as a percentage
The change as a percentage of the earlier figure, instead of an amount in the measure’s own format. `displayChangeAsPercentage` switches to a percentage, to one decimal place.
```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-06-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2026-05-02'),
to: new Date('2026-05-31'),
};
const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```
### Lower is better
For costs, churn or response times: a rise shows red and a fall shows green. `reversePositiveNegativeColors` swaps the colours. `reverseTrendDirection={false}` keeps the arrow pointing the way the number moved; without it the arrow flips with the colours.
```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';
const churnRate = measure({
name: 'churn_rate',
title: 'Churn rate',
inputs: { suffix: '%', decimalPlaces: 1 },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-06-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2026-05-02'),
to: new Date('2026-05-31'),
};
const currentRows = [{ churn_rate: 2.5 }];
const previousRows = [{ churn_rate: 2.7 }];
```
### Two decimals
A percentage change to two decimal places, for metrics that move by fractions of a percent. `percentageDecimalPlaces` only applies with `displayChangeAsPercentage`.
```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-06-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2026-05-02'),
to: new Date('2026-05-31'),
};
const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `measure` | `Measure` | yes | | The number to show and compare. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `primaryDateRange` | `TimeRange` | yes | | The dates `results` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. Only read to work out the comparison dates for `setComparisonDateRange`. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsComparison` | `DataResponse` | yes | | Rows for the comparison period, with the same keys as `results`. |
| `comparisonDateRange` | `TimeRange` | yes | | The dates `resultsComparison` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. Without it the change is not shown. |
| `changeFontSize` | `number` | no | | Font size of the change line in pixels. |
| `comparisonPeriod` | `string` | no | | Names the comparison under the number (“vs previous period”, translated). One of `"Previous period"`, `"Previous week"`, `"Previous month"`, `"Previous quarter"`, `"Previous year"`, `"Same period last week"`, `"Same period last month"`, `"Same period last quarter"`, `"Same period last year"`; any other string leaves the name empty. |
| `displayChangeAsPercentage` | `boolean` | no | `false` | Show the change as a percentage instead of a difference. |
| `fontSize` | `number` | no | | Font size of the headline number in pixels. By default it grows and shrinks to fit the card. |
| `reversePositiveNegativeColors` | `boolean` | no | `false` | Colour an increase as bad and a decrease as good, for costs or churn. |
| `reverseTrendDirection` | `boolean` | no | | Point the trend arrow the other way. When unset, the arrow follows `reversePositiveNegativeColors`. |
| `percentageDecimalPlaces` | `number` | no | `1` | Decimal places on the percentage change. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `setComparisonDateRange` | `(dateRange: TimeRange) => void` | no | | If set, the card works out the comparison dates from `primaryDateRange` and `comparisonPeriod` and calls this with them, so you can query them. When it cannot work them out, it calls this with no range. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TimeRange } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart
========================================================================
# Bar chart
Compare one or more measures across the values of a dimension.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart/playground
`BarChart` takes `dimension` + `measures`. Its siblings name their fields differently: `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', customers: 448 },
{ industry: 'Media', customers: 677 },
{ industry: 'Retail', customers: 741 },
{ industry: 'Tech', customers: 707 },
];
```
- Each row in `results` is one bar: the dimension's value plus each measure.
- Format values through the measure's `inputs`: here `abbreviateLargeNumber` shortens thousands to K.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Monthly columns
Six months as columns, each labelled with its abbreviated value. A time dimension with `granularity: 'month'` labels the axis and fills months with no row.
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-01-01T00:00:00.000', revenue: 131229 },
{ startDate: '2026-02-01T00:00:00.000', revenue: 116685 },
{ startDate: '2026-03-01T00:00:00.000', revenue: 141619 },
{ startDate: '2026-04-01T00:00:00.000', revenue: 138438 },
{ startDate: '2026-05-01T00:00:00.000', revenue: 148882 },
{ startDate: '2026-06-01T00:00:00.000', revenue: 160625 },
];
```
### Growth, up and down
Month-on-month change as a percentage, with bars below zero for the months that fell. Compute `growth` in your query and describe it with its own `measure()`, formatted by `suffix` and `decimalPlaces`.
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const growth = measure({
name: 'growth',
title: 'Revenue growth',
inputs: { suffix: '%', decimalPlaces: 1 },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-01-01T00:00:00.000', growth: 0.6 },
{ startDate: '2026-02-01T00:00:00.000', growth: -11.1 },
{ startDate: '2026-03-01T00:00:00.000', growth: 21.4 },
{ startDate: '2026-04-01T00:00:00.000', growth: -2.2 },
{ startDate: '2026-05-01T00:00:00.000', growth: 7.5 },
{ startDate: '2026-06-01T00:00:00.000', growth: 7.9 },
];
```
### Axis titles
A caption on each axis, for a chart that has to stand on its own in a report.
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', customers: 448 },
{ industry: 'Media', customers: 677 },
{ industry: 'Retail', customers: 741 },
{ industry: 'Tech', customers: 707 },
];
```
### Fixed value range
A pinned value axis, so charts side by side share one scale. `yAxisRangeMin` and `yAxisRangeMax` pin the axis; values above the maximum are clipped.
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', customers: 448 },
{ industry: 'Media', customers: 677 },
{ industry: 'Retail', customers: 741 },
{ industry: 'Tech', customers: 707 },
];
```
### Long tail as “Other”
Rows sorted largest first: the top five as bars, and the rest added up into one “Other” bar. `xAxisMaxItems: 6` keeps the first five rows in your order and adds up the rest, so sort the query largest first.
```tsx
import { ChartsProvider, BarChart, dimension, measure, results } from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ account: 'Juniper', revenue: 176000 },
{ account: 'Kite', revenue: 152000 },
{ account: 'Harbor', revenue: 131000 },
{ account: 'Isle', revenue: 114000 },
{ account: 'Fjord', revenue: 96000 },
{ account: 'Grove', revenue: 84000 },
{ account: 'Dune', revenue: 78000 },
{ account: 'Ember', revenue: 64000 },
{ account: 'Birch', revenue: 60000 },
{ account: 'Cedar', revenue: 49000 },
{ account: 'Alder', revenue: 44000 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `xAxisMaxItems` | `number` | no | | Show at most this many x values. The rest are added up into one “Other” value. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
```ts
type BarChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `dimension` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `BarChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `color` | `string` | `measures` | | A colour for this measure’s bars, in place of the theme’s. |
| `showValueAsPercentage` | `boolean` | `measures` | `false` | Label each value with its share of the total. The tooltip shows both. |
========================================================================
Title: Horizontal bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart-horizontal
========================================================================
# Horizontal bar chart
Bars laid out horizontally, for long category labels or ranked lists.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart-horizontal
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart-horizontal/playground
`BarChartHorizontal` takes `dimension` + `measures`. Its siblings name their fields differently: `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarChartHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', customers: 985 },
{ region: 'Europe', customers: 709 },
{ region: 'Asia Pacific', customers: 451 },
{ region: 'Latin America', customers: 240 },
{ region: 'Middle East', customers: 188 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Truncated labels
Long category names cut to eight characters on the axis; the tooltip shows them in full. `maxCharacters` is a field option on the dimension.
```tsx
import {
ChartsProvider,
BarChartHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({
name: 'region',
title: 'Region',
inputs: { maxCharacters: 8 },
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', customers: 985 },
{ region: 'Europe', customers: 709 },
{ region: 'Asia Pacific', customers: 451 },
{ region: 'Latin America', customers: 240 },
{ region: 'Middle East', customers: 188 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseYAxis` | `boolean` | no | `false` | Reverse the order of the y-axis. |
| `xAxisRangeMax` | `number` | no | | Fix the highest value on the x-axis. When unset, it fits the data. |
| `xAxisRangeMin` | `number` | no | | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisMaxItems` | `number` | no | | Show at most this many y values. The rest are added up into one “Other” value. |
```ts
type BarChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `dimension` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `BarChartHorizontal` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `color` | `string` | `measures` | | A colour for this measure’s bars, in place of the theme’s. |
| `showValueAsPercentage` | `boolean` | `measures` | `false` | Label each value with its share of the total. The tooltip shows both. |
========================================================================
Title: Stacked bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart-stacked
========================================================================
# Stacked bar chart
Show the composition of each bar by a second dimension.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart-stacked
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart-stacked/playground
`BarChartStacked` takes `xAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `BarChart`, `BarChartHorizontal` and `BarLineChart` take `dimension` + `measures`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarChartStacked,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', revenue: 23494 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', revenue: 62545 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', revenue: 55581 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', revenue: 21223 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', revenue: 57533 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', revenue: 59682 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', revenue: 22081 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', revenue: 61318 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', revenue: 65483 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', revenue: 21648 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', revenue: 66775 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', revenue: 72202 },
];
```
- Rows are long format: one per bar and segment, with the `groupBy` value on each.
- The `xAxis` values are drawn A to Z, whatever the order of your rows, unless you pass `axisOrder`.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Totals
Each stack’s total printed above it, in compact numbers. `showTotalLabels` adds the totals; the segments keep their own tooltips.
```tsx
import {
ChartsProvider,
BarChartStacked,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', revenue: 23494 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', revenue: 62545 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', revenue: 55581 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', revenue: 21223 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', revenue: 57533 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', revenue: 59682 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', revenue: 22081 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', revenue: 61318 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', revenue: 65483 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', revenue: 21648 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', revenue: 66775 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', revenue: 72202 },
];
```
### Segment values
Every segment labelled, for reading the mix as well as the total.
```tsx
import {
ChartsProvider,
BarChartStacked,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', revenue: 23494 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', revenue: 62545 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', revenue: 55581 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', revenue: 21223 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', revenue: 57533 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', revenue: 59682 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', revenue: 22081 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', revenue: 61318 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', revenue: 65483 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', revenue: 21648 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', revenue: 66775 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', revenue: 72202 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `maxLegendItems`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsAxisOrder` | `DataResponse` | no | | A separate result listing the axis values in the order to draw them, for example largest first. Reported back through `setAxisOrderAndCacheKey`. |
| `axisOrder` | `string[]` | no | | The axis values in the order to draw them. Values missing from the list are left out. |
| `axisOrderCacheKey` | `string` | no | | Any string identifying the `resultsAxisOrder` query. Passed back as the second argument of `setAxisOrderAndCacheKey`, which is only called when this is set. |
| `setAxisOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsAxisOrder` and `axisOrderCacheKey` once that result has loaded. Store the values and pass them as `axisOrder`. |
| `resultsGroupOrder` | `DataResponse` | no | | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no | | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no | | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showTotalLabels` | `boolean` | no | `false` | Print the total at the end of each stack. |
| `showValueLabels` | `boolean` | no | `false` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartStackedOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
```ts
type BarChartStackedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; groupingDimensionValue: string | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartStackedOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Stacked horizontal bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart-stacked-horizontal
========================================================================
# Stacked horizontal bar chart
The composition of each bar by a second dimension, laid out horizontally for long labels.
- Component: ` `, imported from `em-kit`
- Required props: `yAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart-stacked-horizontal
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart-stacked-horizontal/playground
`BarChartStackedHorizontal` takes `yAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `BarChart`, `BarChartHorizontal` and `BarLineChart` take `dimension` + `measures`; `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarChartStackedHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', customers: 500 },
{ region: 'North America', plan: 'Growth', customers: 401 },
{ region: 'North America', plan: 'Enterprise', customers: 84 },
{ region: 'Europe', plan: 'Starter', customers: 377 },
{ region: 'Europe', plan: 'Growth', customers: 278 },
{ region: 'Europe', plan: 'Enterprise', customers: 54 },
{ region: 'Asia Pacific', plan: 'Starter', customers: 204 },
{ region: 'Asia Pacific', plan: 'Growth', customers: 215 },
{ region: 'Asia Pacific', plan: 'Enterprise', customers: 32 },
{ region: 'Latin America', plan: 'Starter', customers: 110 },
{ region: 'Latin America', plan: 'Growth', customers: 108 },
{ region: 'Latin America', plan: 'Enterprise', customers: 22 },
{ region: 'Middle East', plan: 'Starter', customers: 91 },
{ region: 'Middle East', plan: 'Growth', customers: 83 },
{ region: 'Middle East', plan: 'Enterprise', customers: 14 },
];
```
- The `yAxis` values are drawn A to Z, whatever the order of your rows, unless you pass `axisOrder`.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Totals
Each stack’s total printed at its end, in compact numbers.
```tsx
import {
ChartsProvider,
BarChartStackedHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', customers: 500 },
{ region: 'North America', plan: 'Growth', customers: 401 },
{ region: 'North America', plan: 'Enterprise', customers: 84 },
{ region: 'Europe', plan: 'Starter', customers: 377 },
{ region: 'Europe', plan: 'Growth', customers: 278 },
{ region: 'Europe', plan: 'Enterprise', customers: 54 },
{ region: 'Asia Pacific', plan: 'Starter', customers: 204 },
{ region: 'Asia Pacific', plan: 'Growth', customers: 215 },
{ region: 'Asia Pacific', plan: 'Enterprise', customers: 32 },
{ region: 'Latin America', plan: 'Starter', customers: 110 },
{ region: 'Latin America', plan: 'Growth', customers: 108 },
{ region: 'Latin America', plan: 'Enterprise', customers: 22 },
{ region: 'Middle East', plan: 'Starter', customers: 91 },
{ region: 'Middle East', plan: 'Growth', customers: 83 },
{ region: 'Middle East', plan: 'Enterprise', customers: 14 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `yAxis` | `Dimension` | yes | | The dimension down the y-axis of a horizontal chart. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsAxisOrder` | `DataResponse` | no | | A separate result listing the axis values in the order to draw them, for example largest first. Reported back through `setAxisOrderAndCacheKey`. |
| `axisOrder` | `string[]` | no | | The axis values in the order to draw them. Values missing from the list are left out. |
| `axisOrderCacheKey` | `string` | no | | Any string identifying the `resultsAxisOrder` query. Passed back as the second argument of `setAxisOrderAndCacheKey`, which is only called when this is set. |
| `setAxisOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsAxisOrder` and `axisOrderCacheKey` once that result has loaded. Store the values and pass them as `axisOrder`. |
| `resultsGroupOrder` | `DataResponse` | no | | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no | | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no | | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showTotalLabels` | `boolean` | no | `false` | Print the total at the end of each stack. |
| `showValueLabels` | `boolean` | no | `false` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartStackedOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseYAxis` | `boolean` | no | `false` | Reverse the order of the y-axis. |
| `xAxisRangeMax` | `number` | no | | Fix the highest value on the x-axis. When unset, it fits the data. |
| `xAxisRangeMin` | `number` | no | | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
```ts
type BarChartStackedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; groupingDimensionValue: string | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartStackedOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `yAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Grouped bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart-grouped
========================================================================
# Grouped bar chart
Side-by-side bars for each value of a second dimension.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart-grouped
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart-grouped/playground
`BarChartGrouped` takes `xAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `BarChart`, `BarChartHorizontal` and `BarLineChart` take `dimension` + `measures`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarChartGrouped,
dimension,
measure,
results,
} from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', billing: 'Monthly', revenue: 62141 },
{ industry: 'Health', billing: 'Annual', revenue: 176864 },
{ industry: 'Media', billing: 'Monthly', revenue: 99606 },
{ industry: 'Media', billing: 'Annual', revenue: 51312 },
{ industry: 'Retail', billing: 'Monthly', revenue: 104861 },
{ industry: 'Retail', billing: 'Annual', revenue: 75934 },
{ industry: 'Tech', billing: 'Monthly', revenue: 114706 },
{ industry: 'Tech', billing: 'Annual', revenue: 152053 },
];
```
- The `xAxis` values are drawn A to Z, whatever the order of your rows, unless you pass `axisOrder`.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Value labels
Every bar labelled with its compact value.
```tsx
import {
ChartsProvider,
BarChartGrouped,
dimension,
measure,
results,
} from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', billing: 'Monthly', revenue: 62141 },
{ industry: 'Health', billing: 'Annual', revenue: 176864 },
{ industry: 'Media', billing: 'Monthly', revenue: 99606 },
{ industry: 'Media', billing: 'Annual', revenue: 51312 },
{ industry: 'Retail', billing: 'Monthly', revenue: 104861 },
{ industry: 'Retail', billing: 'Annual', revenue: 75934 },
{ industry: 'Tech', billing: 'Monthly', revenue: 114706 },
{ industry: 'Tech', billing: 'Annual', revenue: 152053 },
];
```
### Axis titles
A caption on each axis.
```tsx
import {
ChartsProvider,
BarChartGrouped,
dimension,
measure,
results,
} from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', billing: 'Monthly', revenue: 62141 },
{ industry: 'Health', billing: 'Annual', revenue: 176864 },
{ industry: 'Media', billing: 'Monthly', revenue: 99606 },
{ industry: 'Media', billing: 'Annual', revenue: 51312 },
{ industry: 'Retail', billing: 'Monthly', revenue: 104861 },
{ industry: 'Retail', billing: 'Annual', revenue: 75934 },
{ industry: 'Tech', billing: 'Monthly', revenue: 114706 },
{ industry: 'Tech', billing: 'Annual', revenue: 152053 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsAxisOrder` | `DataResponse` | no | | A separate result listing the axis values in the order to draw them, for example largest first. Reported back through `setAxisOrderAndCacheKey`. |
| `axisOrder` | `string[]` | no | | The axis values in the order to draw them. Values missing from the list are left out. |
| `axisOrderCacheKey` | `string` | no | | Any string identifying the `resultsAxisOrder` query. Passed back as the second argument of `setAxisOrderAndCacheKey`, which is only called when this is set. |
| `setAxisOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsAxisOrder` and `axisOrderCacheKey` once that result has loaded. Store the values and pass them as `axisOrder`. |
| `resultsGroupOrder` | `DataResponse` | no | | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no | | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no | | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showTotalLabels` | `boolean` | no | `false` | Print the total at the end of each stack. |
| `showValueLabels` | `boolean` | no | `false` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartStackedOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
```ts
type BarChartStackedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; groupingDimensionValue: string | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartStackedOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Grouped horizontal bar chart
Source: https://emkit.embeddable.com/docs/components/bar-chart-grouped-horizontal
========================================================================
# Grouped horizontal bar chart
Side-by-side bars for each value of a second dimension, laid out horizontally.
- Component: ` `, imported from `em-kit`
- Required props: `yAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-chart-grouped-horizontal
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-chart-grouped-horizontal/playground
`BarChartGroupedHorizontal` takes `yAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `BarChart`, `BarChartHorizontal` and `BarLineChart` take `dimension` + `measures`; `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarChartGroupedHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ plan: 'Starter', billing: 'Monthly', customers: 1052 },
{ plan: 'Starter', billing: 'Annual', customers: 231 },
{ plan: 'Growth', billing: 'Monthly', customers: 586 },
{ plan: 'Growth', billing: 'Annual', customers: 499 },
{ plan: 'Enterprise', billing: 'Monthly', customers: 25 },
{ plan: 'Enterprise', billing: 'Annual', customers: 182 },
];
```
- The `yAxis` values are drawn A to Z, whatever the order of your rows, unless you pass `axisOrder`.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Value labels
Every bar labelled with its value.
```tsx
import {
ChartsProvider,
BarChartGroupedHorizontal,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ plan: 'Starter', billing: 'Monthly', customers: 1052 },
{ plan: 'Starter', billing: 'Annual', customers: 231 },
{ plan: 'Growth', billing: 'Monthly', customers: 586 },
{ plan: 'Growth', billing: 'Annual', customers: 499 },
{ plan: 'Enterprise', billing: 'Monthly', customers: 25 },
{ plan: 'Enterprise', billing: 'Annual', customers: 182 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `yAxis` | `Dimension` | yes | | The dimension down the y-axis of a horizontal chart. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsAxisOrder` | `DataResponse` | no | | A separate result listing the axis values in the order to draw them, for example largest first. Reported back through `setAxisOrderAndCacheKey`. |
| `axisOrder` | `string[]` | no | | The axis values in the order to draw them. Values missing from the list are left out. |
| `axisOrderCacheKey` | `string` | no | | Any string identifying the `resultsAxisOrder` query. Passed back as the second argument of `setAxisOrderAndCacheKey`, which is only called when this is set. |
| `setAxisOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsAxisOrder` and `axisOrderCacheKey` once that result has loaded. Store the values and pass them as `axisOrder`. |
| `resultsGroupOrder` | `DataResponse` | no | | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no | | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no | | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showTotalLabels` | `boolean` | no | `false` | Print the total at the end of each stack. |
| `showValueLabels` | `boolean` | no | `false` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartStackedOptionsClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseYAxis` | `boolean` | no | `false` | Reverse the order of the y-axis. |
| `xAxisRangeMax` | `number` | no | | Fix the highest value on the x-axis. When unset, it fits the data. |
| `xAxisRangeMin` | `number` | no | | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
```ts
type BarChartStackedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record | undefined; groupingDimensionValue: string | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarChartStackedOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `yAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Bar and line combo
Source: https://emkit.embeddable.com/docs/components/bar-line-chart
========================================================================
# Bar and line combo
Bars and a line on independent axes, for volume against a rate or count.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bar-line-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bar-line-chart/playground
`BarLineChart` takes `dimension` + `measures`. Its siblings name their fields differently: `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BarLineChart,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
const churnRate = measure({
name: 'churn_rate',
title: 'Churn rate',
inputs: { suffix: '%', decimalPlaces: 1, useSecondaryAxis: true },
});
export const Example = () => (
);
const rows = [
{ plan: 'Starter', customers: 1283, churn_rate: 4.8 },
{ plan: 'Growth', customers: 1085, churn_rate: 2.7 },
{ plan: 'Enterprise', customers: 207, churn_rate: 1.1 },
];
```
- `useSecondaryAxis` on a line measure gives the line its own scale, on the right.
- `showValueLabels` labels the bars and `showValueLabelsLine` the line, both on by default. Here the bars are plain, so the line never runs through a bar’s label.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Axis titles
A caption on each value axis, so it’s clear which scale belongs to which series.
```tsx
import {
ChartsProvider,
BarLineChart,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
const churnRate = measure({
name: 'churn_rate',
title: 'Churn rate',
inputs: { suffix: '%', decimalPlaces: 1, useSecondaryAxis: true },
});
export const Example = () => (
);
const rows = [
{ plan: 'Starter', customers: 1283, churn_rate: 4.8 },
{ plan: 'Growth', customers: 1085, churn_rate: 2.7 },
{ plan: 'Enterprise', customers: 207, churn_rate: 1.1 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `lineMeasures` | `Measure[]` | no | | Measures drawn as lines over the bars. Set `useSecondaryAxis` on a measure to give it the right-hand axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `showValueLabelsLine` | `boolean` | no | `true` | Print the line’s values too. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `xAxisMaxItems` | `number` | no | | Show at most this many x values. The rest are added up into one “Other” value. |
| `yAxisSecondaryLabel` | `string` | no | | A title beside the right-hand axis. |
| `yAxisSecondaryMin` | `number` | no | | Fix the lowest value on the right-hand axis. |
| `yAxisSecondaryMax` | `number` | no | | Fix the highest value on the right-hand axis. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarLineChartClickArg) => void` | no | | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `onLineClicked` | `(args: BarLineChartClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type BarLineChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BarLineChartClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `dimension` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `BarLineChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `color` | `string` | `measures` | | A colour for this measure’s bars, in place of the theme’s. |
| `showValueAsPercentage` | `boolean` | `measures` | `false` | Label each value with its share of the total. The tooltip shows both. |
| `lineColor` | `string` | `lineMeasures` | | A colour for this measure’s line, in place of the theme’s. |
| `dashedLine` | `boolean` | `lineMeasures` | `false` | Draw the line dashed. |
| `connectGaps` | `boolean` | `lineMeasures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
| `fillUnderLine` | `boolean` | `lineMeasures` | | Shade the area under the line. |
| `useSecondaryAxis` | `boolean` | `lineMeasures` | | Plot this measure against the right-hand axis, with its own scale. |
========================================================================
Title: Line chart
Source: https://emkit.embeddable.com/docs/components/line-chart
========================================================================
# Line chart
A time series with gap filling and a built-in granularity switcher.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `measures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/line-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/line-chart/playground
`LineChart` takes `xAxis` + `measures`. Its siblings name their fields differently: `LineChartGrouped` and `AreaChart` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, LineChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', signups: 2634 },
];
```
- The time field’s `granularity` labels the axis and fills periods with no row. For a picker in the card, set `showGranularityDropdown` on the field and pass `setGranularity` (both optional), then refetch at the granularity it reports.
- Rows are long format, one per time bucket, with zone-less ISO time strings.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Filled
A shaded area under the line, for a sense of volume over time. `fillUnderLine` is a field option on the measure, so each measure in `measures` can choose its own.
```tsx
import { ChartsProvider, LineChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: { abbreviateLargeNumber: true, fillUnderLine: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', signups: 2634 },
];
```
### Dashed
A dashed line, for a forecast or a target, with compact numbers on the axis. `dashedLine` and `abbreviateLargeNumber` are field options on the measure, not chart props.
```tsx
import { ChartsProvider, LineChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: { dashedLine: true, abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', signups: 2634 },
];
```
### Fitted value axis
The value axis starts just below the lowest point instead of at zero, to bring out small changes. The axis starts at zero by default; `yAxisRangeMin` moves it, and `yAxisLabel` captions it.
```tsx
import { ChartsProvider, LineChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', signups: 2634 },
];
```
### Granularity picker
A picker in the card switches between weeks, months and quarters. `showGranularityDropdown` shows it; `setGranularity` gets the choice, which you keep in state and query again at.
```tsx
import { useState } from 'react';
import { ChartsProvider, LineChart, dimension, measure, results } from 'em-kit';
import type { Granularity } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
inputs: {
showGranularityDropdown: true,
// The picker offers the granularities with 1 to 100 periods in this range.
dateBounds: {
from: new Date('2026-01-05'),
to: new Date('2026-06-28'),
},
},
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => {
const [granularity, setGranularity] = useState('month');
return (
);
};
// Signups per day from Monday 5 January 2026, as your database holds them.
const daily = [
90, 84, 76, 93, 87, 61, 52, 93, 93, 96, 70, 83, 57, 49, 96, 83, 85, 76, 86,
53, 65, 75, 94, 94, 96, 84, 50, 55, 89, 88, 85, 76, 79, 63, 56, 102, 85, 98,
98, 89, 54, 50, 81, 74, 73, 82, 80, 57, 58, 99, 90, 84, 100, 87, 60, 57, 70,
87, 71, 74, 89, 53, 60, 72, 74, 93, 72, 83, 52, 58, 69, 68, 81, 93, 80, 59,
54, 83, 69, 70, 89, 97, 46, 57, 92, 93, 85, 77, 104, 58, 69, 83, 98, 82, 88,
93, 51, 70, 90, 87, 98, 95, 87, 50, 51, 100, 104, 101, 110, 80, 65, 53, 87,
84, 94, 81, 102, 71, 62, 96, 108, 105, 110, 106, 70, 74, 116, 104, 97, 106,
107, 67, 68, 121, 100, 96, 122, 106, 71, 79, 97, 112, 111, 102, 117, 75, 67,
104, 93, 97, 108, 89, 64, 67, 88, 92, 102, 99, 92, 69, 60, 88, 93, 102, 109,
98, 64, 59, 98, 98, 113, 93, 100, 61, 63,
];
// The first day of the week, month or quarter that a day falls in.
const periodOf = (day: Date, granularity: Granularity) => {
const y = day.getUTCFullYear();
const m = day.getUTCMonth();
let start = Date.UTC(y, m, 1);
if (granularity === 'quarter') start = Date.UTC(y, m - (m % 3), 1);
if (granularity === 'week') {
start = Date.UTC(y, m, day.getUTCDate() - ((day.getUTCDay() + 6) % 7));
}
return new Date(start).toISOString().slice(0, 23); // drop the "Z"
};
// Stand-in for your API: the days summed into the periods the reader picks,
// each keyed by its first day.
const rowsBy = (granularity: Granularity) => {
const sums = new Map();
daily.forEach((value, i) => {
const key = periodOf(new Date(Date.UTC(2026, 0, 5 + i)), granularity);
sums.set(key, (sums.get(key) ?? 0) + value);
});
return [...sums].map(([key, signups]) => ({
'startDate': key,
signups,
}));
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `xAxisMaxItems` | `number` | no | | Show at most this many x values. The rest are added up into one “Other” value. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onLineClicked` | `(arg: LineChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type LineChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValue?: number | undefined; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { LineChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `LineChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `fillUnderLine` | `boolean` | `measures` | | Shade the area under the line. |
| `lineColor` | `string` | `measures` | | A colour for this measure’s line, in place of the theme’s. |
| `connectGaps` | `boolean` | `measures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
| `dashedLine` | `boolean` | `measures` | `false` | Draw the line dashed. |
========================================================================
Title: Multi-series line chart
Source: https://emkit.embeddable.com/docs/components/line-chart-grouped
========================================================================
# Multi-series line chart
One line per value of a dimension, over time.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/line-chart-grouped
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/line-chart-grouped/playground
`LineChartGrouped` takes `xAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `LineChart`, `LineChartComparison`, `LineChartWithKpiTabs` and `LineChartComparisonWithKpiTabs` take `xAxis` + `measures`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
LineChartGrouped,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', revenue: 23494 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', revenue: 62545 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', revenue: 55581 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', revenue: 21223 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', revenue: 57533 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', revenue: 59682 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', revenue: 22081 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', revenue: 61318 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', revenue: 65483 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', revenue: 21648 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', revenue: 66775 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', revenue: 72202 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Filled
Every segment shaded under its line, so the biggest reads at a glance. `fillUnderLine` on the measure shades under every line the chart draws for it.
```tsx
import {
ChartsProvider,
LineChartGrouped,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true, fillUnderLine: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', revenue: 23494 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', revenue: 62545 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', revenue: 55581 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', revenue: 21223 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', revenue: 57533 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', revenue: 59682 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', revenue: 22081 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', revenue: 61318 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', revenue: 65483 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', revenue: 21648 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', revenue: 66775 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', revenue: 72202 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsGroupOrder` | `DataResponse` | no | | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no | | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no | | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no | | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `xAxisMaxItems` | `number` | no | | Show at most this many x values. The rest are added up into one “Other” value. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onLineClicked` | `(arg: LineChartGroupedOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type LineChartGroupedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; groupingDimensionValue: string | boolean | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { LineChartGroupedOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `LineChartGrouped` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `fillUnderLine` | `boolean` | `measure` | | Shade the area under the line. |
| `connectGaps` | `boolean` | `measure` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
========================================================================
Title: Line chart with comparison
Source: https://emkit.embeddable.com/docs/components/line-chart-comparison
========================================================================
# Line chart with comparison
The current period against an earlier one, each on its own date axis.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `measures`, `results`, `resultsComparison`, `comparisonDateRange` and `primaryDateRange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/line-chart-comparison
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/line-chart-comparison/playground
`LineChartComparison` takes `xAxis` + `measures`. Its siblings name their fields differently: `LineChartGrouped` and `AreaChart` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
LineChartComparison,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: {
abbreviateLargeNumber: true,
previousLineDashed: true,
previousLineColor: '#a1a1aa',
},
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-03-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2025-11-01'),
to: new Date('2026-02-28'),
};
const rows = [
{ startDate: '2026-03-01T00:00:00.000', customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', customers: 476 },
];
const comparisonRows = [
{ startDate: '2025-11-01T00:00:00.000', customers: 478 },
{ startDate: '2025-12-01T00:00:00.000', customers: 498 },
{ startDate: '2026-01-01T00:00:00.000', customers: 406 },
{ startDate: '2026-02-01T00:00:00.000', customers: 385 },
];
```
- Both lines are solid and take the measure’s colour unless the measure says otherwise: here `previousLineDashed` and `previousLineColor` set the earlier line apart.
- `comparisonPeriod` is needed: without it the earlier line is not drawn.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### One date axis
Both lines against the current period’s dates, without the second x-axis. `showComparisonAxis={false}` drops the axis that carries the comparison period’s own dates.
```tsx
import {
ChartsProvider,
LineChartComparison,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: {
abbreviateLargeNumber: true,
previousLineDashed: true,
previousLineColor: '#a1a1aa',
},
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-03-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2025-11-01'),
to: new Date('2026-02-28'),
};
const rows = [
{ startDate: '2026-03-01T00:00:00.000', customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', customers: 476 },
];
const comparisonRows = [
{ startDate: '2025-11-01T00:00:00.000', customers: 478 },
{ startDate: '2025-12-01T00:00:00.000', customers: 498 },
{ startDate: '2026-01-01T00:00:00.000', customers: 406 },
{ startDate: '2026-02-01T00:00:00.000', customers: 385 },
];
```
### Styled lines
Each period in a colour of your choice, both drawn solid. `lineColor` and `previousLineColor` are field options on the measure. Either line is solid unless `lineDashed` or `previousLineDashed` is set.
```tsx
import {
ChartsProvider,
LineChartComparison,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: {
abbreviateLargeNumber: true,
lineColor: '#0ea5e9',
previousLineColor: '#f59e0b',
},
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-03-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2025-11-01'),
to: new Date('2026-02-28'),
};
const rows = [
{ startDate: '2026-03-01T00:00:00.000', customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', customers: 476 },
];
const comparisonRows = [
{ startDate: '2025-11-01T00:00:00.000', customers: 478 },
{ startDate: '2025-12-01T00:00:00.000', customers: 498 },
{ startDate: '2026-01-01T00:00:00.000', customers: 406 },
{ startDate: '2026-02-01T00:00:00.000', customers: 385 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsComparison` | `DataResponse` | yes | | Rows for the comparison period, with the same keys as `results`. |
| `comparisonDateRange` | `TimeRange` | yes | | The dates `resultsComparison` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. The comparison’s axis runs from `from` to `to`. |
| `primaryDateRange` | `TimeRange` | yes | | The dates `results` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. The x-axis runs from `from` to `to`. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `comparisonPeriod` | `string` | no | | Which period `resultsComparison` holds. One of `"Previous period"`, `"Previous week"`, `"Previous month"`, `"Previous quarter"`, `"Previous year"`, `"Same period last week"`, `"Same period last month"`, `"Same period last quarter"`, `"Same period last year"`. Without it the comparison is not drawn. With `setComparisonDateRange` the comparison dates are worked out from it, and any other string gives no range. |
| `showComparisonAxis` | `boolean` | no | `true` | Show a second x-axis with the comparison period’s dates. Set it to `false` to draw both lines against the current dates. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `setComparisonDateRange` | `(dateRange: TimeRange) => void` | no | | If set, the chart works out the comparison dates from `primaryDateRange` and `comparisonPeriod` and calls this with them, so you can query them. When it cannot work them out, it calls this with no range. |
| `onLineClicked` | `(arg: LineChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type LineChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValue?: number | undefined; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { LineChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `LineChartComparison` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `fillUnderLine` | `boolean` | `measures` | | Shade the area under the line. |
| `lineColor` | `string` | `measures` | | A colour for this measure’s line, in place of the theme’s. |
| `previousLineColor` | `string` | `measures` | | A colour for the comparison period’s line. |
| `lineDashed` | `boolean` | `measures` | `false` | Draw the current period’s line dashed. |
| `previousLineDashed` | `boolean` | `measures` | `false` | Draw the comparison period’s line dashed. When off, it is solid like the current line. |
| `connectGaps` | `boolean` | `measures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
========================================================================
Title: Line chart with KPI tabs
Source: https://emkit.embeddable.com/docs/components/line-chart-with-kpi-tabs
========================================================================
# Line chart with KPI tabs
A tab per measure showing its total; selecting a tab switches the plotted line.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `measures`, `results` and `resultsKpis`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/line-chart-with-kpi-tabs
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/line-chart-with-kpi-tabs/playground
`LineChartWithKpiTabs` takes `xAxis` + `measures`. Its siblings name their fields differently: `LineChartGrouped` and `AreaChart` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
LineChartWithKpiTabs,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', revenue: 141619, customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', revenue: 138438, customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', revenue: 148882, customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', revenue: 160625, customers: 476 },
];
const kpiRows = [{ revenue: 589564, customers: 1783 }];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Filled
Each measure shaded under its line when its tab is selected.
```tsx
import {
ChartsProvider,
LineChartWithKpiTabs,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true, fillUnderLine: true },
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { fillUnderLine: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', revenue: 141619, customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', revenue: 138438, customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', revenue: 148882, customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', revenue: 160625, customers: 476 },
];
const kpiRows = [{ revenue: 589564, customers: 1783 }];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsKpis` | `DataResponse` | yes | | One row holding each measure’s total, shown as tabs above the chart. Clicking a tab plots that measure. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `xAxisMaxItems` | `number` | no | | Show at most this many x values. The rest are added up into one “Other” value. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onLineClicked` | `(arg: LineChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type LineChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValue?: number | undefined; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { LineChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `LineChartWithKpiTabs` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `fillUnderLine` | `boolean` | `measures` | | Shade the area under the line. |
| `lineColor` | `string` | `measures` | | A colour for this measure’s line, in place of the theme’s. |
| `connectGaps` | `boolean` | `measures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
| `dashedLine` | `boolean` | `measures` | `false` | Draw the line dashed. |
========================================================================
Title: Line chart with comparison and KPI tabs
Source: https://emkit.embeddable.com/docs/components/line-chart-comparison-with-kpi-tabs
========================================================================
# Line chart with comparison and KPI tabs
KPI tabs showing each measure’s change against the previous period, over a line chart that overlays both.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `measures`, `results`, `resultsComparison`, `comparisonDateRange`, `primaryDateRange` and `resultsKpis`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/line-chart-comparison-with-kpi-tabs
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/line-chart-comparison-with-kpi-tabs/playground
`LineChartComparisonWithKpiTabs` takes `xAxis` + `measures`. Its siblings name their fields differently: `LineChartGrouped` and `AreaChart` take `xAxis` + `groupBy` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
LineChartComparisonWithKpiTabs,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: {
abbreviateLargeNumber: true,
previousLineDashed: true,
previousLineColor: '#a1a1aa',
},
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { previousLineDashed: true, previousLineColor: '#a1a1aa' },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-03-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2025-11-01'),
to: new Date('2026-02-28'),
};
const rows = [
{ startDate: '2026-03-01T00:00:00.000', customers: 469, signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', customers: 410, signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', customers: 428, signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', customers: 476, signups: 2634 },
];
const comparisonRows = [
{ startDate: '2025-11-01T00:00:00.000', customers: 478, signups: 1543 },
{ startDate: '2025-12-01T00:00:00.000', customers: 498, signups: 2282 },
{ startDate: '2026-01-01T00:00:00.000', customers: 406, signups: 2385 },
{ startDate: '2026-02-01T00:00:00.000', customers: 385, signups: 2191 },
];
const kpiRows = [{ signups: 10319, customers: 1783 }];
const kpiComparisonRows = [{ signups: 8401, customers: 1767 }];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### One date axis
Both lines against the current period’s dates, without the second x-axis. `showComparisonAxis={false}` drops the axis that carries the comparison period’s own dates.
```tsx
import {
ChartsProvider,
LineChartComparisonWithKpiTabs,
dimension,
measure,
results,
} from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const signups = measure({
name: 'signups',
title: 'Signups',
inputs: {
abbreviateLargeNumber: true,
previousLineDashed: true,
previousLineColor: '#a1a1aa',
},
});
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { previousLineDashed: true, previousLineColor: '#a1a1aa' },
});
export const Example = () => (
);
const currentRange = {
from: new Date('2026-03-01'),
to: new Date('2026-06-30'),
};
const previousRange = {
from: new Date('2025-11-01'),
to: new Date('2026-02-28'),
};
const rows = [
{ startDate: '2026-03-01T00:00:00.000', customers: 469, signups: 2266 },
{ startDate: '2026-04-01T00:00:00.000', customers: 410, signups: 2474 },
{ startDate: '2026-05-01T00:00:00.000', customers: 428, signups: 2945 },
{ startDate: '2026-06-01T00:00:00.000', customers: 476, signups: 2634 },
];
const comparisonRows = [
{ startDate: '2025-11-01T00:00:00.000', customers: 478, signups: 1543 },
{ startDate: '2025-12-01T00:00:00.000', customers: 498, signups: 2282 },
{ startDate: '2026-01-01T00:00:00.000', customers: 406, signups: 2385 },
{ startDate: '2026-02-01T00:00:00.000', customers: 385, signups: 2191 },
];
const kpiRows = [{ signups: 10319, customers: 1783 }];
const kpiComparisonRows = [{ signups: 8401, customers: 1767 }];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `granularity`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `measures` | `Measure[]` | yes | | The numeric fields to plot, one series each. Their `inputs` set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsComparison` | `DataResponse` | yes | | Rows for the comparison period, with the same keys as `results`. |
| `comparisonDateRange` | `TimeRange` | yes | | The dates `resultsComparison` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. The comparison’s axis runs from `from` to `to`. |
| `primaryDateRange` | `TimeRange` | yes | | The dates `results` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. The x-axis runs from `from` to `to`. |
| `resultsKpis` | `DataResponse` | yes | | One row holding each measure’s total, shown as tabs above the chart. Clicking a tab plots that measure. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `comparisonPeriod` | `string` | no | | Which period `resultsComparison` holds. One of `"Previous period"`, `"Previous week"`, `"Previous month"`, `"Previous quarter"`, `"Previous year"`, `"Same period last week"`, `"Same period last month"`, `"Same period last quarter"`, `"Same period last year"`. Without it the comparison is not drawn. With `setComparisonDateRange` the comparison dates are worked out from it, and any other string gives no range. |
| `showComparisonAxis` | `boolean` | no | `true` | Show a second x-axis with the comparison period’s dates. Set it to `false` to draw both lines against the current dates. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `setComparisonDateRange` | `(dateRange: TimeRange) => void` | no | | If set, the chart works out the comparison dates from `primaryDateRange` and `comparisonPeriod` and calls this with them, so you can query them. When it cannot work them out, it calls this with no range. |
| `onLineClicked` | `(arg: LineChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and date range. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `resultsKpisComparison` | `DataResponse` | no | | The same one row for the comparison period, so each tab can show its change. |
```ts
type LineChartOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValue?: number | undefined; measureValues?: Record | undefined; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { LineChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `LineChartComparisonWithKpiTabs` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `fillUnderLine` | `boolean` | `measures` | | Shade the area under the line. |
| `lineColor` | `string` | `measures` | | A colour for this measure’s line, in place of the theme’s. |
| `previousLineColor` | `string` | `measures` | | A colour for the comparison period’s line. |
| `lineDashed` | `boolean` | `measures` | `false` | Draw the current period’s line dashed. |
| `previousLineDashed` | `boolean` | `measures` | `false` | Draw the comparison period’s line dashed. When off, it is solid like the current line. |
| `connectGaps` | `boolean` | `measures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
| `invertChangeColors` | `boolean` | `measures` | `false` | Colour an increase as bad and a decrease as good, for costs or churn. |
| `reverseTrendDirection` | `boolean` | `measures` | | Point the trend arrow the other way. When unset, the arrow follows `invertChangeColors`. |
| `displayChangeAsPercentage` | `boolean` | `measures` | `false` | Show the change as a percentage instead of a difference. |
| `percentageDecimalPlaces` | `number` | `measures` | `1` | Decimal places on the percentage change. Only read with `displayChangeAsPercentage`. |
========================================================================
Title: Stacked area chart
Source: https://emkit.embeddable.com/docs/components/area-chart
========================================================================
# Stacked area chart
Stacked areas showing how segments contribute to a total over time.
- Component: ` `, imported from `em-kit`
- Required props: `xAxis`, `groupBy`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/area-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/area-chart/playground
`AreaChart` takes `xAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `LineChart`, `LineChartComparison`, `LineChartWithKpiTabs` and `LineChartComparisonWithKpiTabs` take `xAxis` + `measures`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, AreaChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', customers: 236 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', customers: 202 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', customers: 31 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', customers: 211 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', customers: 168 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', customers: 32 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', customers: 212 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', customers: 177 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', customers: 39 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', customers: 205 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', customers: 220 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', customers: 52 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Axis titles
A caption on each axis.
```tsx
import { ChartsProvider, AreaChart, dimension, measure, results } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ startDate: '2026-03-01T00:00:00.000', plan: 'Starter', customers: 236 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Growth', customers: 202 },
{ startDate: '2026-03-01T00:00:00.000', plan: 'Enterprise', customers: 31 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Starter', customers: 211 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Growth', customers: 168 },
{ startDate: '2026-04-01T00:00:00.000', plan: 'Enterprise', customers: 32 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Starter', customers: 212 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Growth', customers: 177 },
{ startDate: '2026-05-01T00:00:00.000', plan: 'Enterprise', customers: 39 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Starter', customers: 205 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Growth', customers: 220 },
{ startDate: '2026-06-01T00:00:00.000', plan: 'Enterprise', customers: 52 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `resultsGroupOrder`, `resultsGroupOther`, `groupOrderCacheKey`, `setGroupOrderAndCacheKey` and `xAxisMaxItems`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `xAxis` | `Dimension` | yes | | The dimension along the x-axis. A time dimension gets gap filling and date labels. |
| `groupBy` | `Dimension` | yes | | A second dimension that splits each axis value into one series per value. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `granularity` | `Granularity` | no | | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no | | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onPointClicked` | `(arg: AreaChartPointClickArg) => void` | no | | Called with the clicked point’s dimension value, date range and measure value. |
| `onAreaClicked` | `(arg: AreaChartAreaClickArg) => void` | no | | Called with the clicked area’s `groupBy` value. |
```ts
type AreaChartPointClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValue: number | undefined; }
type AreaChartAreaClickArg = { groupingDimensionValue: string | boolean | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { AreaChartPointClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `xAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `AreaChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `connectGaps` | `boolean` | `measure` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
========================================================================
Title: Pie chart
Source: https://emkit.embeddable.com/docs/components/pie-chart
========================================================================
# Pie chart
Share of a total across a small number of categories.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/pie-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/pie-chart/playground
`PieChart` takes `dimension` + `measure`. Its siblings name their fields differently: `DonutLabelChart` takes `dimension` + `measure` + `innerLabelMeasure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', revenue: 239005 },
{ industry: 'Media', revenue: 150918 },
{ industry: 'Retail', revenue: 180795 },
{ industry: 'Tech', revenue: 266759 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Percentages
Each slice labelled with its share of the total. `showValueAsPercentage` on the measure works out the shares from your rows; no extra query. `decimalPlaces` rounds them.
```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 1, showValueAsPercentage: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Health', revenue: 239005 },
{ industry: 'Media', revenue: 150918 },
{ industry: 'Retail', revenue: 180795 },
{ industry: 'Tech', revenue: 266759 },
];
```
### Long tail as “Other”
At most three slices: the first two rows, and the rest added up into one “Other” slice. `maxLegendItems` keeps your rows’ order, so sort the query largest first.
```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ industry: 'Tech', revenue: 266759 },
{ industry: 'Health', revenue: 239005 },
{ industry: 'Retail', revenue: 180795 },
{ industry: 'Media', revenue: 150918 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `showValueLabelsAsPercentage`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `maxLegendItems` | `number` | no | `10` | Show at most this many segments. The rest are added up into one “Other” segment. |
| `showLegend` | `boolean` | no | `true` | Show the legend. Entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `onSegmentClick` | `(args: PieChartClickArg) => void` | no | | Called with the clicked segment’s dimension value. Use it as a filter. A click on the “Other” segment reports the first of the rows it adds up, so ignore that one. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type PieChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { PieChartClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `PieChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `showValueAsPercentage` | `boolean` | `measure` | `false` | Label each value with its share of the total. The tooltip shows both. |
========================================================================
Title: Donut chart
Source: https://emkit.embeddable.com/docs/components/donut-chart
========================================================================
# Donut chart
A pie with the centre cut out, for a lighter visual weight.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/donut-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/donut-chart/playground
`DonutChart` takes `dimension` + `measure`. Its siblings name their fields differently: `DonutLabelChart` takes `dimension` + `measure` + `innerLabelMeasure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
DonutChart,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', customers: 1283 },
{ plan: 'Growth', customers: 1085 },
{ plan: 'Enterprise', customers: 207 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Percentages
Each segment labelled with its share of the total. `showValueAsPercentage` is a field option on the measure.
```tsx
import {
ChartsProvider,
DonutChart,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
name: 'customers',
title: 'Customers',
inputs: { showValueAsPercentage: true, decimalPlaces: 1 },
});
export const Example = () => (
);
const rows = [
{ plan: 'Starter', customers: 1283 },
{ plan: 'Growth', customers: 1085 },
{ plan: 'Enterprise', customers: 207 },
];
```
### Minimal
No legend and no labels: shape only, with the detail in the tooltips.
```tsx
import {
ChartsProvider,
DonutChart,
dimension,
measure,
results,
} from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', customers: 1283 },
{ plan: 'Growth', customers: 1085 },
{ plan: 'Enterprise', customers: 207 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `showValueLabelsAsPercentage`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `maxLegendItems` | `number` | no | `10` | Show at most this many segments. The rest are added up into one “Other” segment. |
| `showLegend` | `boolean` | no | `true` | Show the legend. Entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `onSegmentClick` | `(args: PieChartClickArg) => void` | no | | Called with the clicked segment’s dimension value. Use it as a filter. A click on the “Other” segment reports the first of the rows it adds up, so ignore that one. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type PieChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { PieChartClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `DonutChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `showValueAsPercentage` | `boolean` | `measure` | `false` | Label each value with its share of the total. The tooltip shows both. |
========================================================================
Title: Donut with total
Source: https://emkit.embeddable.com/docs/components/donut-label-chart
========================================================================
# Donut with total
A donut with a headline figure in the centre.
- Component: ` `, imported from `em-kit`
- Required props: `dimension`, `measure`, `innerLabelMeasure`, `results` and `resultsInnerLabel`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/donut-label-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/donut-label-chart/playground
`DonutLabelChart` takes `dimension` + `measure` + `innerLabelMeasure`. Its siblings name their fields differently: `PieChart` and `DonutChart` take `dimension` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
DonutLabelChart,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', revenue: 324606 },
{ region: 'Europe', revenue: 221197 },
{ region: 'Asia Pacific', revenue: 146411 },
{ region: 'Latin America', revenue: 84145 },
{ region: 'Middle East', revenue: 61120 },
];
const totalRows = [{ revenue: 837479 }];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Percentages
The total in the centre and each segment’s share around it. `showValueAsPercentage` is a field option on the measure; the centre still shows the total.
```tsx
import {
ChartsProvider,
DonutLabelChart,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
export const Example = () => (
);
const rows = [
{ region: 'North America', revenue: 324606 },
{ region: 'Europe', revenue: 221197 },
{ region: 'Asia Pacific', revenue: 146411 },
{ region: 'Latin America', revenue: 84145 },
{ region: 'Middle East', revenue: 61120 },
];
const totalRows = [{ revenue: 837479 }];
```
### A count in full
A smaller figure written out in full in the centre: the inner label takes its own measure and rows. `innerLabelMeasure` and `resultsInnerLabel` are separate from the donut’s own measure and rows.
```tsx
import {
ChartsProvider,
DonutLabelChart,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ region: 'North America', customers: 985 },
{ region: 'Europe', customers: 709 },
{ region: 'Asia Pacific', customers: 451 },
{ region: 'Latin America', customers: 240 },
{ region: 'Middle East', customers: 188 },
];
const totalRows = [{ customers: 2573 }];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `showValueLabelsAsPercentage`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measure` | `Measure` | yes | | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `innerLabelMeasure` | `Measure` | yes | | The measure shown in the centre of the donut, read from `resultsInnerLabel`. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsInnerLabel` | `DataResponse` | yes | | A one-row result whose value is shown in the centre of the donut. |
| `maxLegendItems` | `number` | no | `10` | Show at most this many segments. The rest are added up into one “Other” segment. |
| `showLegend` | `boolean` | no | `true` | Show the legend. Entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `onSegmentClick` | `(args: PieChartClickArg) => void` | no | | Called with the clicked segment’s dimension value. Use it as a filter. A click on the “Other” segment reports the first of the rows it adds up, so ignore that one. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
| `innerLabelText` | `string` | no | | The caption under the centre value. |
```ts
type PieChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { PieChartClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `DonutLabelChart` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `showValueAsPercentage` | `boolean` | `measure` | `false` | Label each value with its share of the total. The tooltip shows both. |
========================================================================
Title: Funnel chart
Source: https://emkit.embeddable.com/docs/components/funnel-chart
========================================================================
# Funnel chart
How much of a total survives each step of a process, in order.
- Component: ` `, imported from `em-kit`
- Required props: `sectionDimension`, `countMeasure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/funnel-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/funnel-chart/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
- Steps sort largest first. When a later step can outgrow an earlier one, pass the optional `orderDimension`: a field holding each step’s position.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Step names on the funnel
Each step named on the funnel beside its value, with no legend: for a wide card. `showSectionLabels` writes “Step: value” on each step, so a legend would repeat the names.
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
### Share of all steps
Each step as a share of all steps added together, not a conversion rate. `displayPercentages` divides by the total of every step.
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
### Proportional bars
No taper: plain bars whose widths are exactly proportional, at the cost of the funnel look. `shrinkAnchor="none"` turns the taper off.
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
### Custom colour ramp
A ramp between two colours of your choice, from the first step to the last. Set `startColor` and `endColor`; with one of them, the other is generated.
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
### In a small card
A card 320px wide, with the steps in the legend and the counts in the tooltips. `showValueLabels={false}` keeps the narrow last steps clean.
```tsx
import {
ChartsProvider,
FunnelChart,
dimension,
measure,
results,
} from 'em-kit';
const dealStage = dimension({ name: 'deal_stage', title: 'Stage' });
const deals = measure({ name: 'deals', title: 'Deals' });
export const Example = () => (
);
const rows = [
{ deal_stage: 'Lead', deals: 4820 },
{ deal_stage: 'Qualified', deals: 2796 },
{ deal_stage: 'Proposal', deals: 1901 },
{ deal_stage: 'Negotiation', deals: 1369 },
{ deal_stage: 'Won', deals: 903 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `sectionDimension` | `Dimension` | yes | | The dimension whose values are the funnel’s steps. Rows with the same step are added up. |
| `countMeasure` | `Measure` | yes | | The measure that sizes each step. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `orderDimension` | `Dimension` | no | | A numeric field giving each step’s position, lowest first. Without it, steps run largest to smallest. |
| `startColor` | `string` | no | | Colour of the first step. The steps between blend towards `endColor`. |
| `endColor` | `string` | no | | Colour of the last step. With only one of the two set, the other is generated. |
| `showLegend` | `boolean` | no | `true` | Show the legend. Entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `showSectionLabels` | `boolean` | no | `false` | Print each step’s name on its bar. With `showValueLabels`, the value follows the name. |
| `displayPercentages` | `boolean` | no | `false` | Label each step with its share of all steps’ total instead of its value. |
| `shrinkAnchor` | `"top" \| "middle" \| "bottom" \| "none"` | no | `"middle"` | Where each step narrows towards the next. `"none"` draws straight-sided bars. |
| `shrinkFraction` | `number` | no | `1` | How much of each step narrows, from 0 (none of it) to 1 (all of it). |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Scatter chart
Source: https://emkit.embeddable.com/docs/components/scatter-chart
========================================================================
# Scatter chart
Plot two measures against each other, one point per dimension value.
- Component: ` `, imported from `em-kit`
- Required props: `pointDimension`, `xMeasure`, `yMeasure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/scatter-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/scatter-chart/playground
`ScatterChart` takes `pointDimension` + `xMeasure` + `yMeasure`. Its siblings name their fields differently: `BubbleChart` takes `pointDimension` + `xMeasure` + `yMeasure` + `bubbleSizeMeasure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
ScatterChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ account: 'Alder', plan: 'Starter', seats: 40, revenue: 44000 },
{ account: 'Birch', plan: 'Starter', seats: 66, revenue: 60000 },
{ account: 'Cedar', plan: 'Starter', seats: 92, revenue: 49000 },
{ account: 'Dune', plan: 'Growth', seats: 118, revenue: 78000 },
{ account: 'Ember', plan: 'Growth', seats: 144, revenue: 64000 },
{ account: 'Fjord', plan: 'Growth', seats: 170, revenue: 96000 },
{ account: 'Grove', plan: 'Growth', seats: 196, revenue: 84000 },
{ account: 'Harbor', plan: 'Enterprise', seats: 226, revenue: 131000 },
{ account: 'Isle', plan: 'Enterprise', seats: 258, revenue: 114000 },
{ account: 'Juniper', plan: 'Enterprise', seats: 296, revenue: 176000 },
{ account: 'Kite', plan: 'Enterprise', seats: 334, revenue: 152000 },
];
```
- Each row is one point. `groupByDimension` colours the points and adds the legend.
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Point labels
Each point labelled with its dimension value, so outliers name themselves. A label sits under its point, so both axes start at zero here to keep the labels clear of them.
```tsx
import {
ChartsProvider,
ScatterChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ account: 'Alder', plan: 'Starter', seats: 40, revenue: 44000 },
{ account: 'Birch', plan: 'Starter', seats: 66, revenue: 60000 },
{ account: 'Cedar', plan: 'Starter', seats: 92, revenue: 49000 },
{ account: 'Dune', plan: 'Growth', seats: 118, revenue: 78000 },
{ account: 'Ember', plan: 'Growth', seats: 144, revenue: 64000 },
{ account: 'Fjord', plan: 'Growth', seats: 170, revenue: 96000 },
{ account: 'Grove', plan: 'Growth', seats: 196, revenue: 84000 },
{ account: 'Harbor', plan: 'Enterprise', seats: 226, revenue: 131000 },
{ account: 'Isle', plan: 'Enterprise', seats: 258, revenue: 114000 },
{ account: 'Juniper', plan: 'Enterprise', seats: 296, revenue: 176000 },
{ account: 'Kite', plan: 'Enterprise', seats: 334, revenue: 152000 },
];
```
### One colour
Every point in one colour with no grouping, for a plain correlation plot.
```tsx
import {
ChartsProvider,
ScatterChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
export const Example = () => (
);
const rows = [
{ account: 'Alder', seats: 40, revenue: 44000 },
{ account: 'Birch', seats: 66, revenue: 60000 },
{ account: 'Cedar', seats: 92, revenue: 49000 },
{ account: 'Dune', seats: 118, revenue: 78000 },
{ account: 'Ember', seats: 144, revenue: 64000 },
{ account: 'Fjord', seats: 170, revenue: 96000 },
{ account: 'Grove', seats: 196, revenue: 84000 },
{ account: 'Harbor', seats: 226, revenue: 131000 },
{ account: 'Isle', seats: 258, revenue: 114000 },
{ account: 'Juniper', seats: 296, revenue: 176000 },
{ account: 'Kite', seats: 334, revenue: 152000 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `pointDimension` | `Dimension` | yes | | The dimension that names each point, used in the tooltip and the point label. |
| `xMeasure` | `Measure` | yes | | The measure plotted along the x-axis. |
| `yMeasure` | `Measure` | yes | | The measure plotted along the y-axis. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `groupByDimension` | `Dimension` | no | | An optional dimension that colours the points by group. |
| `pointColor` | `string` | no | | One colour for every point, in place of the theme’s. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showPointLabels` | `boolean` | no | `false` | Label each point with its `pointDimension` value. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `xAxisRangeMin` | `number` | no | | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `xAxisRangeMax` | `number` | no | | Fix the highest value on the x-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `onPointClick` | `(payload: ScatterChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and its x and y values. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type ScatterChartOptionsClickArg = { xMeasureValue: string; yMeasureValue: string; pointDimensionValue: string | undefined; groupByDimensionValue: string | null | undefined; pointDimensionTimeRange: TimeRange; groupByDimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { ScatterChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Bubble chart
Source: https://emkit.embeddable.com/docs/components/bubble-chart
========================================================================
# Bubble chart
A scatter chart with a third measure encoded as bubble size.
- Component: ` `, imported from `em-kit`
- Required props: `pointDimension`, `xMeasure`, `yMeasure`, `bubbleSizeMeasure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/bubble-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/bubble-chart/playground
`BubbleChart` takes `pointDimension` + `xMeasure` + `yMeasure` + `bubbleSizeMeasure`. Its siblings name their fields differently: `ScatterChart` takes `pointDimension` + `xMeasure` + `yMeasure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
BubbleChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const tickets = measure({ name: 'tickets', title: 'Tickets' });
export const Example = () => (
);
const rows = [
{ account: 'Alder', plan: 'Starter', seats: 40, revenue: 44000, tickets: 6 },
{ account: 'Birch', plan: 'Starter', seats: 66, revenue: 60000, tickets: 14 },
{ account: 'Cedar', plan: 'Starter', seats: 92, revenue: 49000, tickets: 9 },
{ account: 'Dune', plan: 'Growth', seats: 118, revenue: 78000, tickets: 22 },
{ account: 'Ember', plan: 'Growth', seats: 144, revenue: 64000, tickets: 12 },
{ account: 'Fjord', plan: 'Growth', seats: 170, revenue: 96000, tickets: 31 },
{ account: 'Grove', plan: 'Growth', seats: 196, revenue: 84000, tickets: 17 },
{ account: 'Harbor', plan: 'Enterprise', seats: 226, revenue: 131000, tickets: 26 },
{ account: 'Isle', plan: 'Enterprise', seats: 258, revenue: 114000, tickets: 48 },
{ account: 'Juniper', plan: 'Enterprise', seats: 296, revenue: 176000, tickets: 35 },
{ account: 'Kite', plan: 'Enterprise', seats: 334, revenue: 152000, tickets: 58 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Labels
Each bubble labelled with its dimension value.
```tsx
import {
ChartsProvider,
BubbleChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const tickets = measure({ name: 'tickets', title: 'Tickets' });
export const Example = () => (
);
const rows = [
{ account: 'Alder', plan: 'Starter', seats: 40, revenue: 44000, tickets: 6 },
{ account: 'Birch', plan: 'Starter', seats: 66, revenue: 60000, tickets: 14 },
{ account: 'Cedar', plan: 'Starter', seats: 92, revenue: 49000, tickets: 9 },
{ account: 'Dune', plan: 'Growth', seats: 118, revenue: 78000, tickets: 22 },
{ account: 'Ember', plan: 'Growth', seats: 144, revenue: 64000, tickets: 12 },
{ account: 'Fjord', plan: 'Growth', seats: 170, revenue: 96000, tickets: 31 },
{ account: 'Grove', plan: 'Growth', seats: 196, revenue: 84000, tickets: 17 },
{ account: 'Harbor', plan: 'Enterprise', seats: 226, revenue: 131000, tickets: 26 },
{ account: 'Isle', plan: 'Enterprise', seats: 258, revenue: 114000, tickets: 48 },
{ account: 'Juniper', plan: 'Enterprise', seats: 296, revenue: 176000, tickets: 35 },
{ account: 'Kite', plan: 'Enterprise', seats: 334, revenue: 152000, tickets: 58 },
];
```
### Wider size range
A wider spread between the smallest and largest bubble, to make the third measure stand out. Both radii are in pixels.
```tsx
import {
ChartsProvider,
BubbleChart,
dimension,
measure,
results,
} from 'em-kit';
const account = dimension({ name: 'account', title: 'Account' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const seats = measure({ name: 'seats', title: 'Seats' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const tickets = measure({ name: 'tickets', title: 'Tickets' });
export const Example = () => (
);
const rows = [
{ account: 'Alder', plan: 'Starter', seats: 40, revenue: 44000, tickets: 6 },
{ account: 'Birch', plan: 'Starter', seats: 66, revenue: 60000, tickets: 14 },
{ account: 'Cedar', plan: 'Starter', seats: 92, revenue: 49000, tickets: 9 },
{ account: 'Dune', plan: 'Growth', seats: 118, revenue: 78000, tickets: 22 },
{ account: 'Ember', plan: 'Growth', seats: 144, revenue: 64000, tickets: 12 },
{ account: 'Fjord', plan: 'Growth', seats: 170, revenue: 96000, tickets: 31 },
{ account: 'Grove', plan: 'Growth', seats: 196, revenue: 84000, tickets: 17 },
{ account: 'Harbor', plan: 'Enterprise', seats: 226, revenue: 131000, tickets: 26 },
{ account: 'Isle', plan: 'Enterprise', seats: 258, revenue: 114000, tickets: 48 },
{ account: 'Juniper', plan: 'Enterprise', seats: 296, revenue: 176000, tickets: 35 },
{ account: 'Kite', plan: 'Enterprise', seats: 334, revenue: 152000, tickets: 58 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `pointDimension` | `Dimension` | yes | | The dimension that names each point, used in the tooltip and the point label. |
| `xMeasure` | `Measure` | yes | | The measure plotted along the x-axis. |
| `yMeasure` | `Measure` | yes | | The measure plotted along the y-axis. |
| `bubbleSizeMeasure` | `Measure` | yes | | A third measure, drawn as the size of each bubble. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `groupByDimension` | `Dimension` | no | | An optional dimension that colours the points by group. |
| `pointColor` | `string` | no | | One colour for every bubble, in place of the theme’s. Only read when `groupByDimension` is not set. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showPointLabels` | `boolean` | no | `false` | Label each point with its `pointDimension` value. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `xAxisLabel` | `string` | no | | A title under the x-axis. |
| `yAxisLabel` | `string` | no | | A title beside the y-axis. |
| `xAxisRangeMin` | `number` | no | | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `xAxisRangeMax` | `number` | no | | Fix the highest value on the x-axis. When unset, it fits the data. |
| `yAxisRangeMin` | `number` | no | | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisRangeMax` | `number` | no | | Fix the highest value on the y-axis. When unset, it fits the data. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `bubbleRadiusMin` | `number` | no | `3` | Radius in pixels of the smallest bubble. |
| `bubbleRadiusMax` | `number` | no | `20` | Radius in pixels of the largest bubble. |
| `onPointClick` | `(payload: BubbleChartOptionsClickArg) => void` | no | | Called with the clicked point’s dimension value and its x and y values. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type BubbleChartOptionsClickArg = { xMeasureValue: string; yMeasureValue: string; pointDimensionValue: string | undefined; groupByDimensionValue: string | null | undefined; pointDimensionTimeRange: TimeRange; groupByDimensionTimeRange: TimeRange; sizeMeasureValue: string; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { BubbleChartOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Paginated table
Source: https://emkit.embeddable.com/docs/components/table-paginated
========================================================================
# Paginated table
A controlled table: you own paging and sorting and pass in the current page of rows.
- Component: ` `, imported from `em-kit`
- Required props: `dimensionsAndMeasures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/table-paginated
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/table-paginated/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. The table fills its parent, so the parent needs a height: a page holds as many rows as fit it, reported as `state.pageSize`. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import {
ChartsProvider,
TablePaginated,
dimension,
measure,
results,
} from 'em-kit';
import type { TablePaginatedState } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => {
const [state, setState] = useState({
page: 0,
isLoadingDownloadData: false,
});
// Stand-in for your API: the page the table asks for, in its sort order.
const { page, pageSize = 10, sort } = state;
const sorted = sortRows(rows, sort);
const pageRows = sorted.slice(page * pageSize, (page + 1) * pageSize);
return (
);
};
const rows: Record[] = [
{ region: 'North America', revenue: 324606, customers: 985 },
{ region: 'Europe', revenue: 221197, customers: 709 },
{ region: 'Asia Pacific', revenue: 146411, customers: 451 },
{ region: 'Latin America', revenue: 84145, customers: 240 },
{ region: 'Middle East', revenue: 61120, customers: 188 },
];
// The rows in the order the table asks for: a column, ascending or descending.
const sortRows = (data: typeof rows, sort: TablePaginatedState['sort']) => {
if (!sort) return data;
const sign = sort.direction === 'desc' ? -1 : 1;
return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```
## States
The table draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Formatted columns
Formatting set per column: the names in bold, and the first measure in compact numbers, with thousands as K. `tableCellStyle` and `abbreviateLargeNumber` are field options on each column’s dimension or measure.
```tsx
import { useState } from 'react';
import {
ChartsProvider,
TablePaginated,
dimension,
measure,
results,
} from 'em-kit';
import type { TablePaginatedState } from 'em-kit';
const region = dimension({
name: 'region',
title: 'Region',
inputs: { tableCellStyle: 'Bold' },
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => {
const [state, setState] = useState({
page: 0,
isLoadingDownloadData: false,
});
// Stand-in for your API: the page the table asks for, in its sort order.
const { page, pageSize = 10, sort } = state;
const sorted = sortRows(rows, sort);
const pageRows = sorted.slice(page * pageSize, (page + 1) * pageSize);
return (
);
};
const rows: Record[] = [
{ region: 'North America', revenue: 324606, customers: 985 },
{ region: 'Europe', revenue: 221197, customers: 709 },
{ region: 'Asia Pacific', revenue: 146411, customers: 451 },
{ region: 'Latin America', revenue: 84145, customers: 240 },
{ region: 'Middle East', revenue: 61120, customers: 188 },
];
// The rows in the order the table asks for: a column, ascending or descending.
const sortRows = (data: typeof rows, sort: TablePaginatedState['sort']) => {
if (!sort) return data;
const sign = sort.direction === 'desc' ? -1 : 1;
return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimensionsAndMeasures` | `DimensionOrMeasure[]` | yes | | The table columns, in order. Dimensions show as text, measures as formatted numbers. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `allResults` | `DataResponse` | no | | Every row, unpaged, for the downloads in the card menu. A download waits until this is set and not loading, so without it the menu spins for good. `state.isLoadingDownloadData` turns `true` when a reader asks, if you would rather fetch only then. |
| `clickDimension` | `Dimension` | no | | The dimension whose value `onRowClicked` receives. Rows are only clickable when it is set. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `pageSize` | `number` | no | | Rows on a page. Left out, the table shows as many rows as fit its height. Either way it reports the number in `state.pageSize`. Give the card room for the rows, about 40 pixels each, or they scroll inside it. |
| `showIndex` | `boolean` | no | `true` | Number the rows. |
| `state` | `TablePaginatedState` | no | | Paging and sorting, controlled: keep it in `useState` and build your query from it. Without `state` and `setState` the table cannot page or sort; downloads need only `allResults`. |
| `totalResults` | `DataResponse` | no | | A result carrying only `total`, the number of rows across all pages. The page count is worked out from it. |
| `onRowClicked` | `(rowDimensionValue: TablePaginatedOnRowClickArg) => void` | no | | Called with the clicked row’s `clickDimension` value. |
| `setState` | `(value: SetStateAction) => void` | no | | A function that stores the new state, such as the setter from `useState`. Called when the reader pages, sorts or downloads, and when the page size is first known or changes. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type TablePaginatedState = { page: number; pageSize?: number | undefined; sort?: { id: string; direction: "asc" | "desc"; } | undefined; isLoadingDownloadData: boolean; }
type TablePaginatedOnRowClickArg = { dimensionValue: string | null | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TablePaginatedState } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `TablePaginated` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `width` | `number` | `dimensionsAndMeasures` | | The column’s width in pixels. |
| `align` | `'left' \| 'center' \| 'right'` | `dimensionsAndMeasures` | | Align the column’s cells left, centre or right. |
| `tableCellStyle` | `'Bold' \| 'Italic' \| 'Positive vs Negative'` | `dimensionsAndMeasures` | | Style the column’s cells. `Positive vs Negative` colours values above zero as good and the rest as bad. |
## Keyboard
| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Table | Moves between the column headers, each cell’s copy button and the page buttons. |
| `Enter` or `Space` | Column header | Sorts ascending, then descending, then clears the sort. |
| `Enter` or `Space` | Page button | Goes to the first, previous, next or last page. |
| `Enter` or `Space` | Copy button in a cell | Copies the cell’s value. The button shows on hover and while focus is in its cell. |
The card menu’s keys, and what is still missing, are in [Accessibility](/docs/accessibility.md#keyboard).
========================================================================
Title: Scrollable table
Source: https://emkit.embeddable.com/docs/components/table-scrollable
========================================================================
# Scrollable table
An infinite-scroll table: you serve pages of 50 rows and it appends each as the reader scrolls.
- Component: ` `, imported from `em-kit`
- Required props: `dimensionsAndMeasures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/table-scrollable
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/table-scrollable/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. The table fills its parent and scrolls inside it, so the parent needs a height, unless `heightMode="auto"` lets the card grow to fit its rows. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useMemo, useState } from 'react';
import {
ChartsProvider,
TableScrollable,
dimension,
measure,
results,
} from 'em-kit';
import type { TableScrollableState } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'day',
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
const customers = measure({ name: 'customers', title: 'Customers' });
// Identifies the query: when it changes, the table starts again from page 0
const filters = { search: '' };
export const Example = () => {
const [state, setState] = useState({
page: 0,
isLoadingDownloadData: false,
});
// Stand-in for your API. Memoised: the table appends every new array.
const sorted = useMemo(() => sortRows(rows, state.sort), [state.sort]);
return (
);
};
const rows: Record[] = [
{ startDate: '2026-01-01T00:00:00.000', revenue: 4709, customers: 15 },
{ startDate: '2026-01-02T00:00:00.000', revenue: 4722, customers: 16 },
{ startDate: '2026-01-03T00:00:00.000', revenue: 3246, customers: 10 },
{ startDate: '2026-01-04T00:00:00.000', revenue: 2890, customers: 9 },
{ startDate: '2026-01-05T00:00:00.000', revenue: 4631, customers: 14 },
{ startDate: '2026-01-06T00:00:00.000', revenue: 4762, customers: 14 },
{ startDate: '2026-01-07T00:00:00.000', revenue: 4563, customers: 14 },
{ startDate: '2026-01-08T00:00:00.000', revenue: 5046, customers: 17 },
{ startDate: '2026-01-09T00:00:00.000', revenue: 4492, customers: 14 },
{ startDate: '2026-01-10T00:00:00.000', revenue: 2989, customers: 11 },
{ startDate: '2026-01-11T00:00:00.000', revenue: 3247, customers: 10 },
{ startDate: '2026-01-12T00:00:00.000', revenue: 4395, customers: 15 },
{ startDate: '2026-01-13T00:00:00.000', revenue: 4204, customers: 14 },
{ startDate: '2026-01-14T00:00:00.000', revenue: 4949, customers: 13 },
{ startDate: '2026-01-15T00:00:00.000', revenue: 4675, customers: 15 },
];
// The rows in the order the table asks for. With more rows, serve 50 a page by
// state.page; a shorter page ends the scroll.
const sortRows = (data: typeof rows, sort: TableScrollableState['sort']) => {
if (!sort) return data;
const sign = sort.direction === 'desc' ? -1 : 1;
return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```
- Sorting, or a new `resetKey`, starts again from page 0.
## States
The table draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Auto height
The card grows to fit every row instead of scrolling: for printable reports and embedded summaries. `heightMode="auto"`: pass all the rows at once (up to your own cap) with `results.total`, and the table says when rows were left out.
```tsx
import { useMemo, useState } from 'react';
import {
ChartsProvider,
TableScrollable,
dimension,
measure,
results,
} from 'em-kit';
import type { TableScrollableState } from 'em-kit';
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity: 'month',
});
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
const customers = measure({ name: 'customers', title: 'Customers' });
// Identifies the query: when it changes, the table starts again from page 0
const filters = { search: '' };
export const Example = () => {
const [state, setState] = useState({
page: 0,
isLoadingDownloadData: false,
});
// Stand-in for your API. Memoised: the table appends every new array.
const sorted = useMemo(() => sortRows(rows, state.sort), [state.sort]);
return (
);
};
const rows: Record[] = [
{ startDate: '2026-01-01T00:00:00.000', revenue: 131229, customers: 406 },
{ startDate: '2026-02-01T00:00:00.000', revenue: 116685, customers: 385 },
{ startDate: '2026-03-01T00:00:00.000', revenue: 141619, customers: 469 },
{ startDate: '2026-04-01T00:00:00.000', revenue: 138438, customers: 410 },
{ startDate: '2026-05-01T00:00:00.000', revenue: 148882, customers: 428 },
{ startDate: '2026-06-01T00:00:00.000', revenue: 160625, customers: 476 },
];
// The rows in the order the table asks for. With more rows, serve 50 a page by
// state.page; a shorter page ends the scroll.
const sortRows = (data: typeof rows, sort: TableScrollableState['sort']) => {
if (!sort) return data;
const sign = sort.direction === 'desc' ? -1 : 1;
return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimensionsAndMeasures` | `DimensionOrMeasure[]` | yes | | The table columns, in order. Dimensions show as text, measures as formatted numbers. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `allResults` | `DataResponse` | no | | Every row, unpaged, for the downloads in the card menu. A download waits until this is set and not loading, so without it the menu spins for good. `state.isLoadingDownloadData` turns `true` when a reader asks, if you would rather fetch only then. |
| `clickDimension` | `Dimension` | no | | The dimension whose value `onRowClicked` receives. Rows are only clickable when it is set. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `showIndex` | `boolean` | no | `true` | Number the rows. |
| `state` | `TableScrollableState` | no | | Paging and sorting, controlled: keep it in `useState` and build your query from it. Without `state` and `setState` the table cannot page or sort; downloads need only `allResults`. |
| `onRowClicked` | `(rowDimensionValue: TableScrollableOnRowClickArg) => void` | no | | Called with the clicked row’s `clickDimension` value. |
| `setState` | `(value: SetStateAction) => void` | no | | A function that stores the new state, such as the setter from `useState`. Called when the reader pages, sorts or downloads, and when the page size is first known or changes. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx"]` | Which entries the card menu offers. Pass `[]` for none. |
| `resetKey` | `unknown` | no | | Any value that identifies the current query, such as your filters. When it changes (compared by value), the table goes back to the top and starts again from page 0. |
| `heightMode` | `"fixed" \| "auto"` | no | `"fixed"` | `"fixed"` scrolls inside the card and loads pages as the reader scrolls. `"auto"` grows the card to fit every row you pass. |
```ts
type TableScrollableState = { page: number; pageSize?: number | undefined; sort?: { id: string; direction: "asc" | "desc"; } | undefined; isLoadingDownloadData: boolean; heightMode?: "fixed" | "auto" | undefined; }
type TableScrollableOnRowClickArg = { dimensionValue: string | null | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TableScrollableState } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `TableScrollable` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `width` | `number` | `dimensionsAndMeasures` | | The column’s width in pixels. |
| `align` | `'left' \| 'center' \| 'right'` | `dimensionsAndMeasures` | | Align the column’s cells left, centre or right. |
| `displayFormat` | `'Markdown' \| 'Json'` | `dimensionsAndMeasures` | | Render the cell’s text as Markdown, or as indented JSON. |
| `tableCellStyle` | `'Bold' \| 'Italic' \| 'Positive vs Negative'` | `dimensionsAndMeasures` | | Style the column’s cells. `Positive vs Negative` colours values above zero as good and the rest as bad. |
## Keyboard
| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Table | Moves between the column headers and each cell’s copy button, scrolling the table to keep the focus in view. |
| `Enter` or `Space` | Column header | Sorts ascending, then descending, then clears the sort. |
| `Enter` or `Space` | Copy button in a cell | Copies the cell’s value. The button shows on hover and while focus is in its cell. |
The card menu’s keys, and what is still missing, are in [Accessibility](/docs/accessibility.md#keyboard).
========================================================================
Title: Pivot table
Source: https://emkit.embeddable.com/docs/components/pivot-table
========================================================================
# Pivot table
Measures cross-tabulated by a row and a column dimension, with totals.
- Component: ` `, imported from `em-kit`
- Required props: `rowDimension`, `columnDimension`, `measures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/pivot-table
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/pivot-table/playground
`PivotTable` takes `rowDimension` + `columnDimension` + `measures`. Its siblings name their fields differently: `HeatMap` takes `rowDimension` + `columnDimension` + `measure`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. The table fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import {
ChartsProvider,
PivotTable,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: {
currency: 'USD',
abbreviateLargeNumber: true,
columnAggregation: ['sum'],
rowAggregation: ['sum'],
},
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', revenue: 51855 },
{ region: 'North America', plan: 'Growth', revenue: 133461 },
{ region: 'North America', plan: 'Enterprise', revenue: 139290 },
{ region: 'Europe', plan: 'Starter', revenue: 39151 },
{ region: 'Europe', plan: 'Growth', revenue: 92491 },
{ region: 'Europe', plan: 'Enterprise', revenue: 89555 },
{ region: 'Asia Pacific', plan: 'Starter', revenue: 21212 },
{ region: 'Asia Pacific', plan: 'Growth', revenue: 71767 },
{ region: 'Asia Pacific', plan: 'Enterprise', revenue: 53432 },
{ region: 'Latin America', plan: 'Starter', revenue: 11394 },
{ region: 'Latin America', plan: 'Growth', revenue: 36004 },
{ region: 'Latin America', plan: 'Enterprise', revenue: 36747 },
{ region: 'Middle East', plan: 'Starter', revenue: 9475 },
{ region: 'Middle East', plan: 'Growth', revenue: 27647 },
{ region: 'Middle East', plan: 'Enterprise', revenue: 23998 },
];
```
- Totals are per measure: `columnAggregation` and `rowAggregation` in the measure's `inputs`.
## States
The table draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Average, min and max
One measure with row statistics instead of plain totals. `rowAggregation` adds a column per statistic and `columnAggregation` a row, always in the order sum, min, max, average. Both take any of `'sum'`, `'min'`, `'max'`, `'average'`.
```tsx
import {
ChartsProvider,
PivotTable,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: {
currency: 'USD',
abbreviateLargeNumber: true,
columnAggregation: ['average'],
rowAggregation: ['average', 'min', 'max'],
},
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', revenue: 51855 },
{ region: 'North America', plan: 'Growth', revenue: 133461 },
{ region: 'North America', plan: 'Enterprise', revenue: 139290 },
{ region: 'Europe', plan: 'Starter', revenue: 39151 },
{ region: 'Europe', plan: 'Growth', revenue: 92491 },
{ region: 'Europe', plan: 'Enterprise', revenue: 89555 },
{ region: 'Asia Pacific', plan: 'Starter', revenue: 21212 },
{ region: 'Asia Pacific', plan: 'Growth', revenue: 71767 },
{ region: 'Asia Pacific', plan: 'Enterprise', revenue: 53432 },
{ region: 'Latin America', plan: 'Starter', revenue: 11394 },
{ region: 'Latin America', plan: 'Growth', revenue: 36004 },
{ region: 'Latin America', plan: 'Enterprise', revenue: 36747 },
{ region: 'Middle East', plan: 'Starter', revenue: 9475 },
{ region: 'Middle East', plan: 'Growth', revenue: 27647 },
{ region: 'Middle East', plan: 'Enterprise', revenue: 23998 },
];
```
### Share of total
Each cell as a percentage, with column totals. `showAsPercentage` shows each cell as its share; other measures may be ignored when it's on. `columnAggregation: ['sum']` adds the totals row.
```tsx
import {
ChartsProvider,
PivotTable,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: {
currency: 'USD',
decimalPlaces: 1,
showAsPercentage: true,
columnAggregation: ['sum'],
},
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', revenue: 51855 },
{ region: 'North America', plan: 'Growth', revenue: 133461 },
{ region: 'North America', plan: 'Enterprise', revenue: 139290 },
{ region: 'Europe', plan: 'Starter', revenue: 39151 },
{ region: 'Europe', plan: 'Growth', revenue: 92491 },
{ region: 'Europe', plan: 'Enterprise', revenue: 89555 },
{ region: 'Asia Pacific', plan: 'Starter', revenue: 21212 },
{ region: 'Asia Pacific', plan: 'Growth', revenue: 71767 },
{ region: 'Asia Pacific', plan: 'Enterprise', revenue: 53432 },
{ region: 'Latin America', plan: 'Starter', revenue: 11394 },
{ region: 'Latin America', plan: 'Growth', revenue: 36004 },
{ region: 'Latin America', plan: 'Enterprise', revenue: 36747 },
{ region: 'Middle East', plan: 'Starter', revenue: 9475 },
{ region: 'Middle East', plan: 'Growth', revenue: 27647 },
{ region: 'Middle East', plan: 'Enterprise', revenue: 23998 },
];
```
### Full numbers
Every cell and total written out in full, in wider columns. `columnWidth` and `firstColumnWidth` are in pixels; the table scrolls sideways when the columns outgrow the card.
```tsx
import {
ChartsProvider,
PivotTable,
dimension,
measure,
results,
} from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: {
currency: 'USD',
decimalPlaces: 0,
columnAggregation: ['sum'],
rowAggregation: ['sum'],
},
});
export const Example = () => (
);
const rows = [
{ region: 'North America', plan: 'Starter', revenue: 51855 },
{ region: 'North America', plan: 'Growth', revenue: 133461 },
{ region: 'North America', plan: 'Enterprise', revenue: 139290 },
{ region: 'Europe', plan: 'Starter', revenue: 39151 },
{ region: 'Europe', plan: 'Growth', revenue: 92491 },
{ region: 'Europe', plan: 'Enterprise', revenue: 89555 },
{ region: 'Asia Pacific', plan: 'Starter', revenue: 21212 },
{ region: 'Asia Pacific', plan: 'Growth', revenue: 71767 },
{ region: 'Asia Pacific', plan: 'Enterprise', revenue: 53432 },
{ region: 'Latin America', plan: 'Starter', revenue: 11394 },
{ region: 'Latin America', plan: 'Growth', revenue: 36004 },
{ region: 'Latin America', plan: 'Enterprise', revenue: 36747 },
{ region: 'Middle East', plan: 'Starter', revenue: 9475 },
{ region: 'Middle East', plan: 'Growth', revenue: 27647 },
{ region: 'Middle East', plan: 'Enterprise', revenue: 23998 },
];
```
### Sub-rows on demand
Each region opens to its countries, loaded the first time it is opened. `setExpandedRowKey` is called with a row’s `rowDimension` value the first time it is opened: add it to `expandedRowKeys` and load `resultsSubRows`, whose rows carry the `rowDimension`, `subRowDimension` and `columnDimension` values and the measures.
```tsx title="PivotSubRows.tsx"
import { useState } from 'react';
import { ChartsProvider, PivotTable, dimension, measure, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const country = dimension({ name: 'country', title: 'Country' });
const quarter = dimension({ name: 'quarter', title: 'Quarter' });
const revenue = measure({
name: 'revenue',
title: 'Revenue',
inputs: { currency: 'USD', decimalPlaces: 0 },
});
// The table's rows: one per region and quarter.
const rows = [
{ region: 'Americas', quarter: 'Q1', revenue: 182000 },
{ region: 'Americas', quarter: 'Q2', revenue: 197000 },
{ region: 'EMEA', quarter: 'Q1', revenue: 143000 },
{ region: 'EMEA', quarter: 'Q2', revenue: 151000 },
];
// The sub-rows: one per region, country and quarter. Each carries its
// region, so the table can put it under the right row.
const byCountry = [
{ region: 'Americas', country: 'United States', quarter: 'Q1', revenue: 141000 },
{ region: 'Americas', country: 'United States', quarter: 'Q2', revenue: 150000 },
{ region: 'Americas', country: 'Canada', quarter: 'Q1', revenue: 41000 },
{ region: 'Americas', country: 'Canada', quarter: 'Q2', revenue: 47000 },
{ region: 'EMEA', country: 'Germany', quarter: 'Q1', revenue: 79000 },
{ region: 'EMEA', country: 'Germany', quarter: 'Q2', revenue: 83000 },
{ region: 'EMEA', country: 'France', quarter: 'Q1', revenue: 64000 },
{ region: 'EMEA', country: 'France', quarter: 'Q2', revenue: 68000 },
];
export function RevenueByRegion() {
// The regions opened so far. The table calls setExpandedRowKey with a
// region the first time a reader opens it; closing it is the table's own.
const [opened, setOpened] = useState([]);
const open = (key: string) =>
setOpened((keys) => (keys.includes(key) ? keys : [...keys, key]));
// Stand-in for your API: the countries of the opened regions only.
const subRows = byCountry.filter((row) => opened.includes(row.region));
return (
);
}
// In your app, the provider goes once around the part with charts.
export const Example = () => (
);
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `rowDimension` | `Dimension` | yes | | The dimension down the side of the grid. |
| `columnDimension` | `Dimension` | yes | | The dimension across the top of the grid. |
| `measures` | `Measure[]` | yes | | The numbers shown in the cells. Their `inputs` set the formatting and the row and column totals. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsSubRows` | `DataResponse` | no | | Rows for the second level, loaded when a row is expanded. |
| `subRowDimension` | `Dimension` | no | | A second row dimension, shown when a row is expanded. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `columnWidth` | `number` | no | | A fixed width for the value columns, in pixels. |
| `firstColumnWidth` | `number` | no | | A fixed width for the row-label column, in pixels. |
| `expandedRowKeys` | `string[]` | no | | The rows whose sub-rows you load, by `rowDimension` value: each key `setExpandedRowKey` has given you. Only needed with `subRowDimension`. |
| `setExpandedRowKey` | `(expandedRowKeys: string) => void` | no | | Called with a row’s `rowDimension` value, as a string, the first time a reader opens the row. Add it to `expandedRowKeys` and load `resultsSubRows` for it; closing the row is the table’s own. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `columnDimension` or `rowDimension` also takes `granularity`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them. `PivotTable` also reads:
| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `columnAggregation` | `('sum' \| 'min' \| 'max' \| 'average')[]` | `measures` | | Add a row under the table for each calculation you list, worked out down each column. |
| `rowAggregation` | `('sum' \| 'min' \| 'max' \| 'average')[]` | `measures` | | Add a column at the end of the table for each calculation you list, worked out along each row. |
| `showAsPercentage` | `boolean` | `measures` | `false` | Show each cell as a share of the total instead of its value. Other measures may be left out. |
## Keyboard
| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Table | With `subRowDimension`, moves between the row headers. Without it, nothing in the table takes focus. |
| `Enter` or `Space` | Row header, with `subRowDimension` | Opens or closes its sub-rows. |
The card menu’s keys, and what is still missing, are in [Accessibility](/docs/accessibility.md#keyboard).
========================================================================
Title: Heat map
Source: https://emkit.embeddable.com/docs/components/heat-map
========================================================================
# Heat map
A grid of cells coloured by value, for spotting hot and cold combinations.
- Component: ` `, imported from `em-kit`
- Required props: `rowDimension`, `columnDimension`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/heat-map
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/heat-map/playground
`HeatMap` takes `rowDimension` + `columnDimension` + `measure`. Its siblings name their fields differently: `PivotTable` takes `rowDimension` + `columnDimension` + `measures`.
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. On a server-rendered page, pass the heat map’s colours (`minColor`, `midColor`, `maxColor` or a theme chart colour) as hex, such as `'#f4f0ff'`: a named, `rgb()` or `var()` colour renders black on the server, and React keeps it. The default colours are hex and match. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { ChartsProvider, HeatMap, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', industry: 'Health', customers: 133 },
{ plan: 'Growth', industry: 'Health', customers: 224 },
{ plan: 'Enterprise', industry: 'Health', customers: 91 },
{ plan: 'Starter', industry: 'Media', customers: 438 },
{ plan: 'Growth', industry: 'Media', customers: 220 },
{ plan: 'Enterprise', industry: 'Media', customers: 19 },
{ plan: 'Starter', industry: 'Retail', customers: 465 },
{ plan: 'Growth', industry: 'Retail', customers: 245 },
{ plan: 'Enterprise', industry: 'Retail', customers: 31 },
{ plan: 'Starter', industry: 'Tech', customers: 246 },
{ plan: 'Growth', industry: 'Tech', customers: 395 },
{ plan: 'Enterprise', industry: 'Tech', customers: 66 },
];
```
## States
The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.
## Examples
### Custom colour scale
Your own cold, middle and hot colours. `minColor`, `midColor` and `maxColor`; the cell text switches between dark and light for contrast.
```tsx
import { ChartsProvider, HeatMap, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', industry: 'Health', customers: 133 },
{ plan: 'Growth', industry: 'Health', customers: 224 },
{ plan: 'Enterprise', industry: 'Health', customers: 91 },
{ plan: 'Starter', industry: 'Media', customers: 438 },
{ plan: 'Growth', industry: 'Media', customers: 220 },
{ plan: 'Enterprise', industry: 'Media', customers: 19 },
{ plan: 'Starter', industry: 'Retail', customers: 465 },
{ plan: 'Growth', industry: 'Retail', customers: 245 },
{ plan: 'Enterprise', industry: 'Retail', customers: 31 },
{ plan: 'Starter', industry: 'Tech', customers: 246 },
{ plan: 'Growth', industry: 'Tech', customers: 395 },
{ plan: 'Enterprise', industry: 'Tech', customers: 66 },
];
```
### Thresholds
Everything in the bottom fifth of the range fully cold and the top fifth fully hot, so outliers don’t wash out the rest. Thresholds take a raw value or a percentage of the range: `minThreshold: '20%'`, `maxThreshold: '80%'`.
```tsx
import { ChartsProvider, HeatMap, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', industry: 'Health', customers: 133 },
{ plan: 'Growth', industry: 'Health', customers: 224 },
{ plan: 'Enterprise', industry: 'Health', customers: 91 },
{ plan: 'Starter', industry: 'Media', customers: 438 },
{ plan: 'Growth', industry: 'Media', customers: 220 },
{ plan: 'Enterprise', industry: 'Media', customers: 19 },
{ plan: 'Starter', industry: 'Retail', customers: 465 },
{ plan: 'Growth', industry: 'Retail', customers: 245 },
{ plan: 'Enterprise', industry: 'Retail', customers: 31 },
{ plan: 'Starter', industry: 'Tech', customers: 246 },
{ plan: 'Growth', industry: 'Tech', customers: 395 },
{ plan: 'Enterprise', industry: 'Tech', customers: 66 },
];
```
### Colours only
No numbers in the cells, for a compact pattern view; the values stay in the exports.
```tsx
import { ChartsProvider, HeatMap, dimension, measure, results } from 'em-kit';
const industry = dimension({ name: 'industry', title: 'Industry' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });
export const Example = () => (
);
const rows = [
{ plan: 'Starter', industry: 'Health', customers: 133 },
{ plan: 'Growth', industry: 'Health', customers: 224 },
{ plan: 'Enterprise', industry: 'Health', customers: 91 },
{ plan: 'Starter', industry: 'Media', customers: 438 },
{ plan: 'Growth', industry: 'Media', customers: 220 },
{ plan: 'Enterprise', industry: 'Media', customers: 19 },
{ plan: 'Starter', industry: 'Retail', customers: 465 },
{ plan: 'Growth', industry: 'Retail', customers: 245 },
{ plan: 'Enterprise', industry: 'Retail', customers: 31 },
{ plan: 'Starter', industry: 'Tech', customers: 246 },
{ plan: 'Growth', industry: 'Tech', customers: 395 },
{ plan: 'Enterprise', industry: 'Tech', customers: 66 },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `rowDimension` | `Dimension` | yes | | The dimension down the side of the grid. |
| `columnDimension` | `Dimension` | yes | | The dimension across the top of the grid. |
| `measure` | `Measure` | yes | | The number behind each cell’s colour and label. |
| `results` | `DataResponse` | yes | | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `columnWidth` | `number` | no | | A fixed width for the value columns, in pixels. |
| `displayNullAs` | `string` | no | | Text shown where a value is null, for example `"–"`. |
| `firstColumnWidth` | `number` | no | | A fixed width for the row-label column, in pixels. |
| `maxColor` | `string` | no | | Colour of the highest values. |
| `maxThreshold` | `string` | no | | Values at this get `maxColor`; values above it darken further. A number as a string, or a percentage of the range such as `"80%"`. |
| `midColor` | `string` | no | | Colour of the values in the middle of the range. |
| `minColor` | `string` | no | | Colour of the lowest values. |
| `minThreshold` | `string` | no | | Values at this get `minColor`; values below it fade further towards white. A number as a string (`"100"`), or a percentage of the range such as `"20%"`. |
| `showValues` | `boolean` | no | `true` | Print the value in each cell. |
| `onCellClicked` | `(args: HeatMapOptionsClickArg) => void` | no | | Called with the clicked cell’s row and column values. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |
```ts
type HeatMapOptionsClickArg = { rowDimensionValue: string | undefined; rowDimensionTimeRange: TimeRange; columnDimensionValue: string | undefined; columnDimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { HeatMapOptionsClickArg } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. A time dimension in `rowDimension` or `columnDimension` also takes `granularity`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
## Keyboard
| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Grid | Moves from cell to cell: every cell takes focus. |
| `Enter` or `Space` | Cell | Calls `onCellClicked` with the cell’s row and column values, if you passed it. |
The card menu’s keys, and what is still missing, are in [Accessibility](/docs/accessibility.md#keyboard).
========================================================================
Title: Date range picker
Source: https://emkit.embeddable.com/docs/components/date-range-picker
========================================================================
# Date range picker
Preset ranges such as “Last 30 days”, with a calendar for any other range.
- Component: ` `, imported from `em-kit`
- Required props: `onChange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/date-range-picker
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/date-range-picker/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, DateRangePicker, dateRangePreset } from 'em-kit';
import type { TimeRange } from 'em-kit';
export const Example = () => {
const [range, setRange] = useState(
dateRangePreset('Last 30 days'),
);
return (
);
};
```
- A preset is named by `relativeTimeString`; the picker fills in its `from` and `to` and reports them through `onChange`, in the provider’s time zone.
## Examples
### Two months
The calendar shows two months side by side, for ranges that cross a month.
```tsx
import { useState } from 'react';
import { ChartsProvider, DateRangePicker, dateRangePreset } from 'em-kit';
import type { TimeRange } from 'em-kit';
export const Example = () => {
const [range, setRange] = useState(
dateRangePreset('Last 30 days'),
);
return (
);
};
```
### Calendar only
No preset list: the picker opens straight on the calendar.
```tsx
import { useState } from 'react';
import { ChartsProvider, DateRangePicker } from 'em-kit';
import type { TimeRange } from 'em-kit';
export const Example = () => {
const [range, setRange] = useState();
return (
);
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `onChange` | `(newDateRange: TimeRange) => void` | yes | | Called with the range the reader picks: a preset comes with its name and its dates, worked out in the provider’s time zone. A preset passed without dates is reported back with them at once. Called with `undefined` when the reader clears it. |
| `placeholder` | `string` | no | `"Select a date-range"` | Text shown while nothing is chosen. Translates like `title`. |
| `selectedValue` | `TimeRange` | no | | The chosen range: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. `dateRangePreset('Last 30 days')` starts from a preset. |
| `clearable` | `boolean` | no | `true` | Let the reader clear the value. |
| `showCustomRangeOptions` | `boolean` | no | `true` | List the presets, with the calendar behind a “Custom” entry. When `false`, the picker opens straight on the calendar. The presets are the provider’s `theme.defaults.dateRangesOptions`. |
| `showTwoMonths` | `boolean` | no | `false` | Show two months side by side in the calendar. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
```ts
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TimeRange } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Custom date range picker
Source: https://emkit.embeddable.com/docs/components/date-range-picker-custom
========================================================================
# Custom date range picker
A calendar for picking any start and end date, with no presets.
- Component: ` `, imported from `em-kit`
- Required props: `onChange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/date-range-picker-custom
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/date-range-picker-custom/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, DateRangePickerCustom } from 'em-kit';
import type { TimeRange } from 'em-kit';
export const Example = () => {
const [range, setRange] = useState();
return (
);
};
```
## Examples
### Two months
The calendar shows two months side by side, for ranges that cross a month.
```tsx
import { useState } from 'react';
import { ChartsProvider, DateRangePickerCustom } from 'em-kit';
import type { TimeRange } from 'em-kit';
export const Example = () => {
const [range, setRange] = useState();
return (
);
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `onChange` | `(newDateRange: TimeRange) => void` | yes | | Called with the range the reader picks, from the start of its first day to the end of its last in the provider’s time zone, or with `undefined` when the reader clears it. |
| `placeholder` | `string` | no | `"Select a date-range"` | Text shown while nothing is chosen. Translates like `title`. |
| `selectedValue` | `TimeRange` | no | | The chosen range: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. |
| `clearable` | `boolean` | no | `true` | Let the reader clear the value. |
| `showTwoMonths` | `boolean` | no | `false` | Show two months side by side in the calendar. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
```ts
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TimeRange } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Granularity select
Source: https://emkit.embeddable.com/docs/components/granularity-select
========================================================================
# Granularity select
Day, week, month, quarter or year: the period a time series is grouped by.
- Component: ` `, imported from `em-kit`
- Required props: `onChange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/granularity-select
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/granularity-select/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, GranularitySelect } from 'em-kit';
import type { Granularity } from 'em-kit';
export const Example = () => {
const [granularity, setGranularity] = useState('month');
return (
);
};
```
- Pass the value to your time dimension as `granularity`, and query rows at that granularity.
## Examples
### Fewer options
Only the granularities your data supports.
```tsx
import { useState } from 'react';
import { ChartsProvider, GranularitySelect } from 'em-kit';
import type { Granularity } from 'em-kit';
export const Example = () => {
const [granularity, setGranularity] = useState('month');
return (
);
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `onChange` | `(newGranularity: Granularity) => void` | yes | | Called with the granularity the reader picks. |
| `placeholder` | `string` | no | `"Select a granularity"` | Text shown while nothing is chosen. Translates like `title`. |
| `primaryTimeRange` | `TimeRange` | no | | The dates being charted: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. With it, only the granularities that suit the range are offered, and a choice that no longer suits is replaced through `onChange`. |
| `granularity` | `Granularity` | no | | The chosen granularity. |
| `granularities` | `Granularity[]` | no | `["hour", "day", "week", "month", "quarter", "year"]` | Which granularities to offer. |
| `clearable` | `boolean` | no | `false` | Let the reader clear the value. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
```ts
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { Granularity } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Comparison period select
Source: https://emkit.embeddable.com/docs/components/comparison-period-select
========================================================================
# Comparison period select
Previous period, previous year and the like: what the current figures are compared with.
- Component: ` `, imported from `em-kit`
- Required props: `onChange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/comparison-period-select
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/comparison-period-select/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, ComparisonPeriodSelect } from 'em-kit';
export const Example = () => {
const [period, setPeriod] = useState('Previous period');
return (
);
};
```
- The value is the option’s name, such as “Previous period”.
## Examples
### With dates
Each option shows the dates it covers, worked out from the range being compared. `primaryDateRange` is the range your date picker holds: pass its state here.
```tsx
import { useState } from 'react';
import {
ChartsProvider,
ComparisonPeriodSelect,
dateRangePreset,
} from 'em-kit';
export const Example = () => {
const [period, setPeriod] = useState('Previous period');
return (
);
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `onChange` | `(newComparisonPeriod: string) => void` | yes | | Called with the name of the comparison the reader picks, or with `undefined` when the reader clears it. |
| `placeholder` | `string` | no | `"Select a date-comparison"` | Text shown while nothing is chosen. Translates like `title`. |
| `primaryDateRange` | `TimeRange` | no | | The range being compared: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. With it, each option shows the dates it covers. |
| `comparisonPeriod` | `string` | no | | The chosen comparison, by name: one of `"Previous period"`, `"Previous week"`, `"Previous month"`, `"Previous quarter"`, `"Previous year"`, `"Same period last week"`, `"Same period last month"`, `"Same period last quarter"`, `"Same period last year"`. The list, and how each works out its dates, is the provider’s `theme.defaults.comparisonPeriodsOptions`. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
```ts
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```
Each is exported from `em-kit` as a type, for example `import type { TimeRange } from 'em-kit'`.
A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Single select
Source: https://emkit.embeddable.com/docs/components/single-select
========================================================================
# Single select
A searchable dropdown of a field’s values, one of which can be chosen.
- Component: ` `, imported from `em-kit`
- Required props: `dimension` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/single-select
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/single-select/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, SingleSelect, dimension, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
export const Example = () => {
const [selected, setSelected] = useState();
return (
);
};
const options = [
{ region: 'North America' },
{ region: 'Europe' },
{ region: 'Asia Pacific' },
{ region: 'Latin America' },
{ region: 'Middle East' },
];
```
- `results` holds one row per option. Labels are formatted like the field anywhere else, so translated values match the charts.
## States
The select draws its own states from `results`: a spinner while `isLoading` is true, and “No options found” when `data` is `[]` or `error` is set. Pass your query’s state straight through.
## Examples
### Always a value
Not clearable: with nothing chosen, the first option is selected.
```tsx
import { useState } from 'react';
import { ChartsProvider, SingleSelect, dimension, results } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
export const Example = () => {
const [selected, setSelected] = useState();
return (
);
};
const options = [
{ region: 'North America' },
{ region: 'Europe' },
{ region: 'Asia Pacific' },
{ region: 'Latin America' },
{ region: 'Middle East' },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `maxOptions`, which the type accepts and the component does not read.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values are the options. Its formatting and translations label them. |
| `results` | `DataResponse` | yes | | One row per option, holding the `dimension` value. `results(rows)` builds it from an array. |
| `optionalSecondDimension` | `Dimension` | no | | A second field in the same rows. When set, its value is what is chosen and reported, while `dimension` labels the option: show a name, report an id. |
| `placeholder` | `string` | no | `"Select value..."` | Text shown while nothing is chosen. Translates like `title`. |
| `selectedValue` | `string` | no | | The chosen value. |
| `clearable` | `boolean` | no | `true` | Let the reader clear the choice. When `false` and nothing is chosen, the first option is selected. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `setSearchValue` | `(search: string) => void` | no | | Called with what the reader types in the search box, after a pause, so that you can query the matching options. When unset, the options are filtered by label as the reader types. |
| `onChange` | `(selectedValue: string) => void` | no | | Called with the value the reader picks, or with `undefined` when the reader clears it. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Multi select
Source: https://emkit.embeddable.com/docs/components/multi-select
========================================================================
# Multi select
A searchable dropdown of a field’s values, any number of which can be chosen.
- Component: ` `, imported from `em-kit`
- Required props: `dimension` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/multi-select
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/multi-select/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, MultiSelect, dimension, results } from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
export const Example = () => {
const [selected, setSelected] = useState([]);
return (
);
};
const options = [
{ plan: 'Starter' },
{ plan: 'Growth' },
{ plan: 'Enterprise' },
];
```
- `results` holds one row per option. The choice is reported when the reader presses Apply.
## States
The select draws its own states from `results`: a spinner while `isLoading` is true, and “No options found” when `data` is `[]` or `error` is set. Pass your query’s state straight through.
## Examples
### Select all
A “select all” row, and each tick applied as it is made. “Select all” shows only when every value is loaded: fewer rows than the 200-option limit.
```tsx
import { useState } from 'react';
import { ChartsProvider, MultiSelect, dimension, results } from 'em-kit';
const plan = dimension({ name: 'plan', title: 'Plan' });
export const Example = () => {
const [selected, setSelected] = useState([]);
return (
);
};
const options = [
{ plan: 'Starter' },
{ plan: 'Growth' },
{ plan: 'Enterprise' },
];
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes | | The field whose values are the options. Its formatting and translations label them. |
| `results` | `DataResponse` | yes | | One row per option, holding the `dimension` value. `results(rows)` builds it from an array. |
| `optionalSecondDimension` | `Dimension` | no | | A second field in the same rows. When set, its values are what is chosen and reported, while `dimension` labels the options: show a name, report an id. |
| `placeholder` | `string` | no | `"Select values..."` | Text shown while nothing is chosen. Translates like `title`. |
| `selectedValues` | `string[]` | no | | The chosen values. |
| `maxOptions` | `number` | no | `200` | The most options your query loads. “Select all” is offered only when `results` holds fewer rows than this: a full page may not be every value. |
| `showSelectAll` | `boolean` | no | `false` | Offer “select all” and “deselect all”, when `results` holds fewer rows than `maxOptions`. |
| `autoApply` | `boolean` | no | `false` | Report each tick as it is made, with no Apply button. |
| `clearable` | `boolean` | no | `true` | Let the reader clear the choice. When `false` and nothing is chosen, the first option is selected. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `setSearchValue` | `(search: string) => void` | no | | Called with what the reader types in the search box, after a pause, so that you can query the matching options. When unset, the options are filtered by label as the reader types. |
| `onChange` | `(newValues: string[]) => void` | no | | Called with the chosen values when the reader presses Apply, or at each tick with `autoApply`. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Text field
Source: https://emkit.embeddable.com/docs/components/text-field
========================================================================
# Text field
A free-text input, reported once the reader pauses typing.
- Component: ` `, imported from `em-kit`
- Required props:
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/text-field
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/text-field/playground
## Install
```bash
npm install em-kit
pnpm add em-kit # or, with pnpm
yarn add em-kit # or, with yarn
bun add em-kit # or, with bun
```
`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `` once: without it every chart throws `EmKit components must be rendered inside .` Every example on this page includes `` so that it runs on its own: if your app already has one, delete it from the example. A control is as wide as its parent and as tall as its title and field, so it needs no height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.
## Usage
```tsx
import { useState } from 'react';
import { ChartsProvider, TextField } from 'em-kit';
export const Example = () => {
const [text, setText] = useState('');
return (
);
};
```
## Examples
### Starting text
The field opens with text already in it, such as a search carried over from another page. `value` is read once, when the field mounts.
```tsx
import { useState } from 'react';
import { ChartsProvider, TextField } from 'em-kit';
export const Example = () => {
const [text, setText] = useState('Enterprise');
return (
);
};
```
## Props
Required props come first. A blank default means the prop is unset unless you pass it.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `value` | `string` | no | | The text the field starts with. The field then keeps what is typed and reports it through `onChange`. |
| `placeholder` | `string` | no | | Text shown while nothing is chosen. Translates like `title`. |
| `componentName` | `string` | no | | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no | | An id included in the same events, to tell two instances apart. |
| `onChange` | `(value: string) => void` | no | | Called with the text once the reader pauses typing, and once with the starting text when the field mounts. |
| `title` | `string` | no | | The title over the field. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no | | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no | | Text for an info icon beside the title. |
## Field options
Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
========================================================================
Title: Dashboard example
Source: https://emkit.embeddable.com/examples
========================================================================
# Dashboard example
A complete sales dashboard built only from EmKit components: KPIs, a time series, a breakdown by region and a table, sharing one set of filters. This is the whole file; the dashboard runs in the browser at [/examples](/examples).
```tsx title="Dashboard.tsx"
import { useMemo, useState } from 'react';
import {
BarChartHorizontal,
ChartsProvider,
DonutChart,
KpiNumber,
KpiNumberComparison,
LineChart,
TablePaginated,
dimension,
measure,
results,
} from 'em-kit';
import type { Granularity, TablePaginatedProps } from 'em-kit';
const region = dimension({ name: 'region', title: 'Region' });
const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({ name: 'revenue', title: 'Revenue', inputs: { prefix: '$' } });
const customers = measure({ name: 'customers', title: 'Customers' });
// The same measure with thousands and millions shortened, for axes and labels.
const revenueCompact = measure({
name: 'revenue',
title: 'Revenue',
inputs: { prefix: '$', abbreviateLargeNumber: true },
});
// ---- A stand-in for your data layer: daily sales for January to June 2026.
// Replace `sales` and the queries in Dashboard with calls to your own API.
type Sale = { day: Date; region: string; plan: string; revenue: number; customers: number };
type Row = Record;
const regions = ['North America', 'Europe', 'Asia Pacific', 'Latin America', 'Middle East'];
const plans = ['Starter', 'Growth', 'Enterprise'];
const days = Array.from({ length: 181 }, (_, d) => new Date(2026, 0, 1 + d));
const sales: Sale[] = days.flatMap((day, d) =>
regions.flatMap((regionName, r) =>
plans.map((planName, p) => ({
day,
region: regionName,
plan: planName,
revenue: Math.round((200 - r * 38) * (p + 1.4) * (1 + d / 450)),
customers: Math.round(((5 - r) * (3 - p)) / 5),
})),
),
);
const total = (rows: Sale[], key: 'revenue' | 'customers') =>
rows.reduce((sum, row) => sum + row[key], 0);
const groupBy = (rows: Sale[], key: (row: Sale) => string) => {
const groups = new Map();
for (const row of rows) {
const group = groups.get(key(row)) ?? [];
group.push(row);
groups.set(key(row), group);
}
return [...groups];
};
// The start of the period a day falls in, as the zone-less ISO string a time axis reads.
const periodStart = (day: Date, granularity: Granularity) => {
const start = new Date(day);
if (granularity === 'week') start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
if (['month', 'quarter', 'year'].includes(granularity)) start.setDate(1);
if (granularity === 'quarter') start.setMonth(start.getMonth() - (start.getMonth() % 3));
if (granularity === 'year') start.setMonth(0);
const pad = (n: number) => String(n).padStart(2, '0');
const date = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
return `${date}T00:00:00.000`;
};
// The windows behind the KPI's current and comparison rows: June, and the 30 days before it.
const june = { from: new Date(2026, 5, 1), to: new Date(2026, 5, 30) };
const may = { from: new Date(2026, 4, 2), to: new Date(2026, 4, 31) };
const revenueIn = (rows: Sale[], range: { from: Date; to: Date }) =>
total(rows.filter((row) => row.day >= range.from && row.day <= range.to), 'revenue');
// ---- The dashboard
const grid = {
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))',
gridAutoRows: 340,
gap: 16,
};
export function Dashboard() {
// Three pieces of state drive the whole page.
const [granularity, setGranularity] = useState('month');
const [planFilter, setPlanFilter] = useState(null);
// Clicking the selected plan again clears the filter.
const togglePlan = (name: string) => setPlanFilter((now) => (now === name ? null : name));
const [state, setState] = useState>({
page: 0,
isLoadingDownloadData: false,
});
const startDate = dimension({
name: 'startDate',
title: 'Start date',
type: 'time',
granularity,
inputs: { showGranularityDropdown: true },
});
// Every query but the donut's takes the filter: the donut is the filter.
const filtered = useMemo(
() => sales.filter((row) => !planFilter || row.plan === planFilter),
[planFilter],
);
const planRows = groupBy(sales, (row) => row.plan).map(([name, rows]) => ({
plan: name,
revenue: total(rows, 'revenue'),
}));
const trendRows = groupBy(filtered, (row) => periodStart(row.day, granularity)).map(
([start, rows]) => ({ startDate: start, revenue: total(rows, 'revenue') }),
);
const regionRows: Row[] = groupBy(filtered, (row) => row.region).map(
([name, rows]) => ({
region: name,
revenue: total(rows, 'revenue'),
customers: total(rows, 'customers'),
}),
);
// The table is controlled: sort, then hand it the page it asks for.
const { page, pageSize = 10, sort } = state;
const sign = sort?.direction === 'desc' ? -1 : 1;
const sorted = sort
? [...regionRows].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign))
: regionRows;
const pageRows = sorted.slice(page * pageSize, (page + 1) * pageSize);
return (
dimensionValue && togglePlan(dimensionValue)}
/>
);
}
```
There is a second example, [an AI chat that answers with charts](/examples/ai-chat.md), and a guide to [charts from a model](/docs/charts-from-a-model.md).
========================================================================
Title: AI chat example
Source: https://emkit.embeddable.com/examples/ai-chat
========================================================================
# AI chat example
A chat where each answer is a chart. The model is given the schema of your data and returns a JSON spec; `ChartFromSpec` turns the spec into a live component, and each click comes back as a sentence to send as the next message. This is the whole message component; the interactive chat is in the browser at [/examples/ai-chat](/examples/ai-chat).
```tsx title="AssistantMessage.tsx"
import { ChartFromSpec, intentToPrompt } from 'em-kit';
import type { ChartSpec } from 'em-kit';
type Props = {
message: { text: string; spec?: ChartSpec };
sendMessage: (text: string) => void;
};
export function AssistantMessage({ message, sendMessage }: Props) {
return (
{message.text}
{message.spec && (
sendMessage(intentToPrompt(intent))}
/>
)}
);
}
```
See [Charts from a model](/docs/charts-from-a-model.md) for the tool definition, the schema and the prompt, and [the dashboard example](/examples.md) for the other example app.