# Donut with total

A donut with a headline figure in the centre.

- Component: `<DonutLabelChart />`, 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 `<ChartsProvider>` once: without it every chart throws `EmKit components must be rendered inside <ChartsProvider>.` Every example on this page includes `<ChartsProvider>` 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 = () => (
  <ChartsProvider>
    <div style={{ height: 480 }}>
      <DonutLabelChart
        title="Revenue by region"
        dimension={region}
        measure={revenue}
        results={results(rows)}
        innerLabelMeasure={revenue}
        innerLabelText="Total"
        resultsInnerLabel={results(totalRows)}
      />
    </div>
  </ChartsProvider>
);

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 = () => (
  <ChartsProvider>
    <div style={{ height: 480 }}>
      <DonutLabelChart
        title="Revenue by region"
        dimension={region}
        measure={{
          ...revenue,
          inputs: { ...revenue.inputs, showValueAsPercentage: true },
        }}
        results={results(rows)}
        innerLabelMeasure={{
          ...revenue,
          inputs: {
            ...revenue.inputs,
            abbreviateLargeNumber: true,
            decimalPlaces: undefined,
          },
        }}
        innerLabelText="Total"
        resultsInnerLabel={results(totalRows)}
      />
    </div>
  </ChartsProvider>
);

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 = () => (
  <ChartsProvider>
    <div style={{ height: 480 }}>
      <DonutLabelChart
        title="Customers by region"
        dimension={region}
        measure={customers}
        results={results(rows)}
        innerLabelMeasure={customers}
        innerLabelText="Total"
        resultsInnerLabel={results(totalRows)}
      />
    </div>
  </ChartsProvider>
);

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. |
